Files
buzz/mobile/lib/shared/me/me_assistants.dart
Tom Brow 1bef1da77d fix(mobile): show newly created remote agents in the new-chat picker (#9030)
After creating a remote agent on mobile (for example in onboarding), the
agent doesn't appear in the Solo **New chat** agent picker. Mentioning
it in a channel, or restarting the app, works around this.

The picker's agent list (`meAssistantsProvider`) is loaded once and kept
for the app session. Creating a remote agent publishes its owner
registration (kind 30177), and Beekeeper publishes the agent's attested
profile, but nothing told the cached list to reload. So the new agent
stayed missing until something unrelated (a relay reconnect or an app
restart) rebuilt the list.

With this change, the list reloads whenever this device publishes or
removes a remote agent registration, using the controller's existing
`registrationRevision`. Agents created on another device still show up
only after the next reload, as before.

### Validation

- Added test: `Solo agent choices reload after this device creates an
agent` (hosted build) creates an agent through the real
`RemoteAgentController.create` path and checks that the picker's list
includes it. It fails without the fix (list stays empty) and passes with
it.
- Full mobile suite passes, and so do the hosted-build `shared`,
`features/agents` and `features/channels/me` suites. Analyzer and format
are clean.
- Automated simulator pass on the fixed build (signed in to a
Builderlab-hosted community): opened **New chat**, the picker listed all
7 agents, picked one, opened an existing Solo chat and the Agents page,
then reopened the picker and it still loaded correctly. Human testing is
waived per the repository's mobile testing exception.
- Limitation: I didn't create a real remote agent on the simulator,
because its Builderlab web sign-in stalled. The create → picker path is
covered by the added test.

🤖 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-03 17:04:07 -08:00

156 lines
5.2 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'dart:isolate';
import 'package:buzz/shared/crypto/event_signing.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../crypto/nip_oa.dart';
import '../agents/remote_agents.dart';
import '../mentions/agent_identity_provider.dart';
import '../relay/relay.dart';
import 'me_agent_inventory.dart';
import 'me_archived_agents.dart';
import 'me_sync.dart';
/// The owner's current inventory, with verified ownership and desktop's
/// known-archived exclusion. Never scan the community's historical profiles.
final meAssistantsProvider = FutureProvider<List<AgentDirectoryEntry>>((
ref,
) async {
final sync = ref.watch(meSyncProvider);
if (sync.connectionState != null) {
ref.watch(relaySessionProvider.select((state) => state.status));
}
// An agent this device just created or deleted changes the inventory.
ref.watch(remoteAgentRegistrationRevisionProvider);
// Refresh archive evidence with the inventory, including explicit retries.
// Ordinary sheet openings reuse this provider's completed directory.
final archivedRequest = ref.refresh(meArchivedAgentsProvider.future);
final inventory = await loadMeAgentInventory(sync);
sync.check();
final profiles = await _loadProfiles(sync, inventory.keys.toList());
final archived = await archivedRequest;
sync.check();
final choices = [
for (final profile in profiles)
if (!archived.contains(profile.pubkey))
AgentDirectoryEntry(
pubkey: profile.pubkey,
displayName: inventory[profile.pubkey],
avatarUrl: profile.avatarUrl,
respondTo: profile.respondTo,
respondToAllowlist: profile.respondToAllowlist,
channelIds: profile.channelIds,
),
];
choices.sort(
(a, b) => (a.displayName ?? '').toLowerCase().compareTo(
(b.displayName ?? '').toLowerCase(),
),
);
return choices;
}, retry: (_, _) => null);
/// Reads the owner's inventory keys. Tests replace the read.
final meAgentInventoryReadProvider = Provider<Future<Set<String>> Function()>((
ref,
) {
final sync = ref.watch(meSyncProvider);
if (sync.connectionState != null) {
ref.watch(relaySessionProvider.select((state) => state.status));
}
return () async => (await loadMeAgentInventory(sync)).keys.toSet();
});
/// How long one inventory read is reused, watched or not.
const meAgentInventoryMaxAge = Duration(seconds: 30);
/// Every agent in the owner's inventory, archived ones included, like
/// desktop's `agentChoices.identities`. Presentation only, never admission.
/// Each read, failed ones included, is reused for [meAgentInventoryMaxAge]:
/// then it is read again if still watched, or dropped.
final meAgentInventoryProvider = FutureProvider.autoDispose<Set<String>>((ref) {
final read = ref.watch(meAgentInventoryReadProvider);
final link = ref.keepAlive();
final expiry = Timer(meAgentInventoryMaxAge, () {
ref.invalidateSelf();
link.close();
});
ref.onDispose(expiry.cancel);
return read();
}, retry: (_, _) => null);
/// Freshness-controlled ownership check for one personal-chat recipient.
final meAssistantOwnershipProvider = FutureProvider.family<bool, String>((
ref,
pubkey,
) {
final sync = ref.watch(meSyncProvider);
if (sync.connectionState != null) {
ref.watch(relaySessionProvider.select((state) => state.status));
}
return isOwnedMeAssistant(sync, pubkey);
});
/// Revalidate the selected recipient, including existing chats whose agent may
/// no longer be offered in the new-chat inventory. Discovery is not admission.
Future<bool> isOwnedMeAssistant(MeSync sync, String pubkey) async =>
(await _loadProfiles(sync, [
pubkey,
])).any((agent) => agent.pubkey == pubkey);
Future<List<AgentDirectoryEntry>> _loadProfiles(
MeSync sync,
List<String> pubkeys,
) async {
final profiles = <NostrEvent>[];
const batchSize = 100;
for (var start = 0; start < pubkeys.length; start += batchSize) {
sync.check();
final batch = pubkeys.skip(start).take(batchSize).toList();
final events = await sync.session.queryRelay([
NostrFilter(kinds: const [0], authors: batch, limit: batchSize),
]);
sync.check();
if (events.length > batchSize) {
throw StateError('Agent profiles exceeded the requested batch size.');
}
profiles.addAll(
events.where((e) => e.kind == 0 && batch.contains(e.pubkey)),
);
}
final owner = sync.pubkey;
final result = await _parseProfiles(profiles, owner);
sync.check();
return result;
}
Future<List<AgentDirectoryEntry>> _parseProfiles(
List<NostrEvent> events,
String owner,
) => Isolate.run(() => _verifiedProfiles(events, owner));
List<AgentDirectoryEntry> _verifiedProfiles(
List<NostrEvent> events,
String owner,
) {
final latest = <String, NostrEvent>{};
for (final event in events) {
try {
verifiedNostrEventFromJson(jsonEncode(event.toJson()));
} catch (_) {
continue;
}
final previous = latest[event.pubkey];
if (previous == null || meEventIsNewer(event, previous)) {
latest[event.pubkey] = event;
}
}
return [
for (final event in latest.values)
if (verifiedProfileOaOwnerPubkey(event) == owner)
AgentDirectoryEntry.fromEvent(event),
];
}