Files
buzz/mobile/lib/shared/mentions/agent_identity_provider.dart
Tom Brow ec21753e1b Make mobile New DM and Add members pick recipients like mention autocomplete (#9065)
The mobile New DM picker listed the first 50 relay profiles
alphabetically, mostly identities the viewer doesn't know. It ran its
own debounced directory search with no cache, and its rows disappeared
on every keystroke until the search returned. Mention autocomplete in
the composer already solves the same problem well, so New DM and Add
members now use its implementation. Add members was reusing the same New
DM directory search.

### What changes

- **Same candidates and order as mention autocomplete.** The chooser's
candidate building, ranking, row stability, 200 ms debounced search and
search cache now back both surfaces. New DM is treated like a stream
with no members yet: the viewer's own agents and agents shared with them
appear up front, people are found by name, and agents that couldn't
answer the viewer are left out. Typing a name shows the same people in
the same order as `@name` in a stream.
- **Results stay on screen while a search runs.** A query searched
before shows its people immediately, and a longer query starts from the
shorter query's results. A failed search keeps its rows and adds a retry
row below them.
- **Presentation matches the mention rows.** Rows show the name, and
agents show "agent · managed by …". Npub lines are gone.
- **Sheet chrome.** The title is "New DM", like the menu item that opens
it. Both pickers keep their grouped cards but drop the "People and
agents" and "Selected" section titles and the empty header bands above
them (selected recipients stay in their own card at the top with
checkmarks on iOS, as chips on Android). The native iOS picker now
focuses search once it appears, which iOS used to ignore. In New DM a
pick clears the query, as an inserted mention ends its query.
- **Add members keeps what is specific to it.** Existing members and
members just added are never offered, names are still compared with the
channel roster so a same-name candidate is told apart, the query stays
after a pick so several matches can be added in a row, and agents that
don't answer the viewer can still be added, since a channel can hold
them.

While the WebSocket reconnects, the relay agent directory and its owners
keep their last read in the community instead of going empty, so shared
agents already found stay eligible in both New DM and the composer
chooser.

The debug-only offline preview directory and the old directory listing
and search providers are removed, since no picker reads them any more.

### Validation

Added tests: the New DM widget journey now drives the real mention
search through a fake relay session. It covers the empty-query state,
the debounce, rows kept while a longer query searches, cached results
shown again at once, selection, chips and submit. The layout journey
covers the 50-row cap, and the native-bridge journey covers title, rows
without key detail lines, the selection limit and failure handling. The
full `mobile/test/features/channels` suite passes.

Automated app run (iPhone 17 Pro simulator, iOS 27, debug build, Remote
Agents Pilot community): opened New DM from the menu, confirmed the
keyboard comes up with only the viewer's own agents listed, searched for
people and an agent, selected both and confirmed the query cleared after
each pick. Also exercised the composer mention chooser (same results and
order for the same query) and the shared Add members sheet (plain style,
autofocus, search, query kept after a pick). Captures show real
community members, so they're shared internally rather than here. The DM
was not actually created, to avoid a stray conversation; submit is
covered by the widget tests.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 13:55:26 -08:00

366 lines
13 KiB
Dart

import 'dart:collection';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:hooks_riverpod/hooks_riverpod.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.
final channelBotPubkeysProvider = FutureProvider.autoDispose
.family<Set<String>, String>((ref, channelId) async {
ref.watch(
channelMembershipUpdateProvider(
channelId,
).select((update) => update.version),
);
final sessionState = ref.watch(relaySessionProvider);
if (sessionState.status != SessionStatus.connected) return const {};
final session = ref.read(relaySessionProvider.notifier);
final events = await session.fetchHistory(
NostrFilters.channelMembers(channelId),
);
if (events.isEmpty) return const {};
return _AgentPubkeySet({
for (final member in membersFromEvent(events.first))
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);
}