Files
buzz/mobile/lib/shared/mentions/agent_identity_provider.dart
Tom Brow 99e65b6c22 perf(mobile): read channel bot roles from the member list (#9451)
Every channel view read the channel's member roster (kind 39002) twice:
once for the member list (`channelMembersProvider`) and once for bot
roles (`channelBotPubkeysProvider`, which feeds agent mention styling).
Both sent the same `kinds:[39002] #d:[channel] limit:1` query, and both
re-ran it on every roster update. Screens that show messages from
several channels did this per channel: opening Activity read 10 rosters
twice each.

Bot roles now come from `channelMembersProvider`, so each channel's
roster is fetched once. While the relay is disconnected, bot roles now
come from the member list's last loaded roster instead of going empty,
so agent mentions keep their styling offline.

### Validation

New test: watching both the member list and bot roles for a channel
fetches the roster once and both report the bot. It fails without this
change (two fetches). The existing bot-role tests (live updates,
subscription cleanup, working bots) pass unchanged. The channel page
test for a bot-role replay used a fixed member list alongside live bot
roles, which can no longer differ; it now reads both from its fake
relay. Full mobile test suite and `flutter analyze` pass.

On an iPhone 12 mini signed in to Block's Builderlab (instrumented
profile build), opening Activity right after launch read 10 channel
rosters once each (25.7 KB) instead of twice (51.5 KB), and opening a
channel read its roster once instead of twice. Agent messages kept their
agent styling. The same automated run covered cold start, opening and
scrolling Activity, scrolling the home list, opening
buzz-mobile-tomb-review (a channel with agent members) and returning
home.

### Regressions

None expected. Bot roles now refresh when the member list does (on
roster updates and after a reconnect) rather than on every relay session
state change, which only drops redundant refetches.

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-13 14:33:41 -08:00

359 lines
12 KiB
Dart

import 'dart:collection';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../../features/channels/channel_management_provider.dart';
import '../../shared/crypto/nip_oa.dart';
import '../../shared/relay/relay.dart';
import '../../shared/utils/string_utils.dart';
/// A relay agent parsed from its kind:10100 agent-profile event.
///
/// Mirrors the fields desktop's `RelayAgent` uses for mention eligibility
/// (`agentAutocompleteEligibility.ts`): who the agent responds to and which
/// channels it sits in.
class AgentDirectoryEntry {
final String pubkey;
final String? displayName;
final String? avatarUrl;
final String? respondTo;
final List<String> respondToAllowlist;
final List<String> channelIds;
const AgentDirectoryEntry({
required this.pubkey,
this.displayName,
this.avatarUrl,
this.respondTo,
this.respondToAllowlist = const [],
this.channelIds = const [],
});
factory AgentDirectoryEntry.fromEvent(NostrEvent event) {
final content = _tryDecodeJsonMap(event.content);
String? text(String field) =>
content?[field] is String ? content![field] as String : null;
List<String> strings(String field) => content?[field] is List
? (content![field] as List).whereType<String>().toList()
: const [];
return AgentDirectoryEntry(
pubkey: event.pubkey.toLowerCase(),
displayName: text('display_name') ?? text('name'),
avatarUrl: text('picture'),
respondTo: text('respond_to'),
respondToAllowlist: strings(
'respond_to_allowlist',
).map((value) => value.toLowerCase()).toList(),
channelIds: strings('channel_ids'),
);
}
}
Map<String, dynamic>? _tryDecodeJsonMap(String content) {
try {
final decoded = jsonDecode(content);
return decoded is Map<String, dynamic> ? decoded : null;
} catch (_) {
return null;
}
}
/// The agent directory and owners last read over a live connection.
///
/// Only the newest directory read writes here, so a read that outlived its
/// connection never replaces a newer one. [owners] are kept with the
/// [ownersOf] directory they were read for, and only for the directory
/// held, so a reconnect never pairs a fresh directory with older owners.
class _AgentDirectoryMemo {
var reads = 0;
List<AgentDirectoryEntry>? agents;
Map<String, String>? owners;
List<AgentDirectoryEntry>? ownersOf;
}
/// One memo per community, so nothing read in one reaches another.
final _agentDirectoryMemoProvider = Provider<_AgentDirectoryMemo>((ref) {
ref.watch(relayConfigProvider);
return _AgentDirectoryMemo();
});
/// Relay agent directory from kind:10100 agent-profile events.
///
/// Watches the session and only fetches after the WebSocket connects.
/// While it reconnects, the directory last read in this community stands,
/// so agents already found stay eligible.
final agentDirectoryProvider = FutureProvider<List<AgentDirectoryEntry>>((
ref,
) async {
final memo = ref.watch(_agentDirectoryMemoProvider);
final sessionState = ref.watch(relaySessionProvider);
if (sessionState.status != SessionStatus.connected) {
return memo.agents ?? const [];
}
final read = ++memo.reads;
final session = ref.read(relaySessionProvider.notifier);
final events = await session.fetchHistory(NostrFilters.agentProfiles());
final agents = [
for (final event in events) AgentDirectoryEntry.fromEvent(event),
];
if (read == memo.reads) memo.agents = agents;
return agents;
});
/// Verified NIP-OA owner pubkey per agent pubkey, from the agents' kind:0
/// profiles. An entry exists only when the `auth` tag verifies — mirrors
/// desktop's `profile_valid_oa_owner_pubkey`.
final agentOwnersProvider = FutureProvider<Map<String, String>>((ref) async {
final memo = ref.watch(_agentDirectoryMemoProvider);
final agents = await ref.watch(agentDirectoryProvider.future);
if (agents.isEmpty) return const {};
// While the session reconnects, the owners last read stand with the
// directory they belong to.
final status = ref.read(relaySessionProvider).status;
if (status != SessionStatus.connected) {
return identical(memo.ownersOf, agents) ? memo.owners! : const {};
}
final session = ref.read(relaySessionProvider.notifier);
final events = await session.fetchHistory(
NostrFilters.profilesBatch([for (final agent in agents) agent.pubkey]),
);
final owners = <String, String>{};
for (final event in events) {
final owner = verifiedOaOwnerPubkey(event.tags, event.pubkey);
if (owner != null) owners[event.pubkey.toLowerCase()] = owner;
}
if (identical(agents, memo.agents)) {
memo
..owners = owners
..ownersOf = agents;
}
return owners;
});
/// Pubkeys currently known to represent agents across the active relay.
///
/// Message surfaces that do not own channel membership can use this shared
/// identity source; channel features add their bot roles separately.
final knownAgentPubkeysProvider = Provider<Set<String>>((ref) {
final relayAgents =
ref.watch(agentDirectoryProvider).asData?.value ??
const <AgentDirectoryEntry>[];
final owners = ref.watch(agentOwnersProvider).asData?.value ?? const {};
return _AgentPubkeySet({
for (final agent in relayAgents) agent.pubkey.toLowerCase(),
...owners.keys.map((pubkey) => pubkey.toLowerCase()),
});
});
/// Directory display names keyed by agent pubkey for mention presentation.
final agentDirectoryDisplayNamesProvider = Provider<Map<String, String>>((ref) {
final agents =
ref.watch(agentDirectoryProvider).asData?.value ??
const <AgentDirectoryEntry>[];
return Map.unmodifiable({
for (final agent in agents)
if (agent.displayName?.trim().isNotEmpty == true)
agent.pubkey.toLowerCase(): agent.displayName!.trim(),
});
});
/// Adds channel bot roles to relay-wide agent identities.
Set<String> agentPubkeysWithChannelBots({
required Set<String> knownAgentPubkeys,
required Iterable<String> channelBotPubkeys,
}) => _AgentPubkeySet({
...knownAgentPubkeys,
...channelBotPubkeys.map((pubkey) => pubkey.toLowerCase()),
});
/// Adds agent identities derived from locally cached verified profiles.
Set<String> agentPubkeysWithProfileOwners({
required Set<String> knownAgentPubkeys,
required Iterable<String> profileOwnedAgentPubkeys,
}) => _AgentPubkeySet({
...knownAgentPubkeys,
...profileOwnedAgentPubkeys.map((pubkey) => pubkey.toLowerCase()),
});
/// Preserves profile labels while filling missing agent mentions from the
/// relay's agent directory.
Map<String, String> mentionNamesWithDirectoryLabels({
required Iterable<String> mentionPubkeys,
required Map<String, String> profileMentionNames,
required Map<String, String> directoryDisplayNames,
required Set<String> agentMentionPubkeys,
}) {
final names = Map<String, String>.from(profileMentionNames);
for (final pubkey in mentionPubkeys) {
final normalizedPubkey = pubkey.toLowerCase();
if (names[normalizedPubkey]?.trim().isEmpty == true) {
names.remove(normalizedPubkey);
}
final directoryName = directoryDisplayNames[normalizedPubkey];
if (!names.containsKey(normalizedPubkey) && directoryName != null) {
names[normalizedPubkey] = directoryName;
}
if (!names.containsKey(normalizedPubkey) &&
agentMentionPubkeys.contains(normalizedPubkey)) {
names[normalizedPubkey] = _agentFallbackLabel(normalizedPubkey);
}
}
return names;
}
String _agentFallbackLabel(String pubkey) => shortPubkey(pubkey);
/// Readiness and refresh state for a channel's live membership subscription.
class ChannelMembershipUpdateState {
final int version;
final bool isReady;
final Object? error;
const ChannelMembershipUpdateState({
this.version = 0,
this.isReady = false,
this.error,
});
}
/// Keeps the role feed alive for consumers that render mentions outside the
/// channel timeline, such as search results. A membership change refreshes the
/// shared bot-role lookup below, regardless of which surface owns the channel.
class _ChannelBotRoleSubscription
extends Notifier<ChannelMembershipUpdateState> {
final String channelId;
void Function()? _unsubscribe;
int _subscriptionVersion = 0;
_ChannelBotRoleSubscription(this.channelId);
@override
ChannelMembershipUpdateState build() {
final sessionState = ref.watch(relaySessionProvider);
final subscriptionVersion = ++_subscriptionVersion;
_clearSubscription();
ref.onDispose(() {
_subscriptionVersion++;
_clearSubscription();
});
if (sessionState.status != SessionStatus.connected) {
return const ChannelMembershipUpdateState();
}
Future.microtask(() => _subscribe(channelId, subscriptionVersion));
return const ChannelMembershipUpdateState();
}
Future<void> _subscribe(String channelId, int subscriptionVersion) async {
final session = ref.read(relaySessionProvider.notifier);
var subscriptionStatus = RelaySubscriptionStatus.retrying;
try {
final unsubscribe = await session.subscribeWithStatus(
NostrFilter(
kinds: const [39002],
tags: {
'#d': [channelId],
},
).copyWithSince(DateTime.now().millisecondsSinceEpoch ~/ 1000),
(_) {
if (_isCurrent(subscriptionVersion)) {
state = ChannelMembershipUpdateState(
version: state.version + 1,
isReady: state.isReady,
);
}
},
onClosed: (message) {
if (_isCurrent(subscriptionVersion)) {
state = ChannelMembershipUpdateState(
version: state.version,
error: Exception(message),
);
}
},
onStatusChanged: (status) {
subscriptionStatus = status;
if (!_isCurrent(subscriptionVersion)) return;
state = ChannelMembershipUpdateState(
version: state.version,
isReady: status == RelaySubscriptionStatus.ready,
);
},
);
if (!_isCurrent(subscriptionVersion)) {
unsubscribe();
return;
}
_unsubscribe = unsubscribe;
state = ChannelMembershipUpdateState(
version: state.version,
isReady: subscriptionStatus == RelaySubscriptionStatus.ready,
);
} catch (error) {
if (_isCurrent(subscriptionVersion)) {
state = ChannelMembershipUpdateState(
version: state.version,
error: error,
);
debugPrint(
'[ChannelBotRoleSubscription] failed for $channelId: $error',
);
}
}
}
bool _isCurrent(int subscriptionVersion) =>
subscriptionVersion == _subscriptionVersion;
void _clearSubscription() {
_unsubscribe?.call();
_unsubscribe = null;
}
}
/// Monotonically increments when the channel's kind:39002 membership snapshot
/// changes. Channel-member and agent-role views share this source so remote
/// membership updates refresh both snapshots together.
final channelMembershipUpdateProvider = NotifierProvider.autoDispose
.family<_ChannelBotRoleSubscription, ChannelMembershipUpdateState, String>(
_ChannelBotRoleSubscription.new,
);
/// Bot pubkeys currently assigned a channel bot role.
///
/// Read from [channelMembersProvider] so a channel's roster is fetched once
/// for both its member list and its bot roles.
final channelBotPubkeysProvider = FutureProvider.autoDispose
.family<Set<String>, String>((ref, channelId) async {
final members = await ref.watch(channelMembersProvider(channelId).future);
return _AgentPubkeySet({
for (final member in members)
if (member.role == 'bot') member.pubkey.toLowerCase(),
});
});
/// Pubkeys currently known to represent agents in a channel.
final agentMentionPubkeysProvider = Provider.autoDispose
.family<Set<String>, String>((ref, channelId) {
final channelBotPubkeys =
ref.watch(channelBotPubkeysProvider(channelId)).asData?.value ??
const <String>{};
return agentPubkeysWithChannelBots(
knownAgentPubkeys: ref.watch(knownAgentPubkeysProvider),
channelBotPubkeys: channelBotPubkeys,
);
});
class _AgentPubkeySet extends UnmodifiableSetView<String> {
_AgentPubkeySet(Iterable<String> pubkeys) : super(Set.unmodifiable(pubkeys));
@override
bool operator ==(Object other) =>
other is Set && length == other.length && every(other.contains);
@override
int get hashCode => Object.hashAllUnordered(this);
}