diff --git a/mobile/lib/features/agents/agents_sheet.dart b/mobile/lib/features/agents/agents_sheet.dart index 8696f1f285..9191680f0a 100644 --- a/mobile/lib/features/agents/agents_sheet.dart +++ b/mobile/lib/features/agents/agents_sheet.dart @@ -135,7 +135,7 @@ class AgentsSheet extends HookConsumerWidget { final directory = ref.watch(agentDirectoryProvider); final registryFuture = useMemoized(() async { final fetch = ref.read(relaySessionProvider.notifier).fetchHistory; - return registeredCommunityAgents( + return ownedCommunityAgents( { for (final agent in controller.agents) agent['agent_pubkey'] as String, diff --git a/mobile/lib/shared/agents/remote_agents.dart b/mobile/lib/shared/agents/remote_agents.dart index 1137efac4c..c5ed1b8576 100644 --- a/mobile/lib/shared/agents/remote_agents.dart +++ b/mobile/lib/shared/agents/remote_agents.dart @@ -59,17 +59,18 @@ final availableRemoteAgentsProvider = FutureProvider>((ref) async { // Loading notifies listeners, which must not happen during this build. scheduleMicrotask(() => controller.load(community!.relayUrl)); if (active.isEmpty) return const {}; - // The registry is account-wide; only agents registered here belong here. - return registeredCommunityAgents( + // The registry is account-wide; only agents live on this relay count. + return liveCommunityAgents( active, controller.owner, ref.read(relaySessionProvider.notifier).fetchHistory, ); }); -/// Only registry identities with verified owner profiles on this relay belong -/// to its community. Account-wide registry entries alone are not membership. -Future> registeredCommunityAgents( +/// Registry identities with verified owner profiles on this relay. Account-wide +/// registry entries alone are not membership. A deletion interrupted after its +/// relay registration was removed still counts, so it can be retried. +Future> ownedCommunityAgents( Set keys, String? owner, Future> Function(NostrFilter) fetch, @@ -84,6 +85,30 @@ Future> registeredCommunityAgents( }; } +/// Owned agents whose kind 30177 registration is live on this relay, so they +/// can answer here. Only these are presented as available. +Future> liveCommunityAgents( + Set keys, + String? owner, + Future> Function(NostrFilter) fetch, +) async { + final owned = await ownedCommunityAgents(keys, owner, fetch); + if (owned.isEmpty) return {}; + final registrations = await fetch( + NostrFilter( + kinds: const [30177], + authors: [owner!], + tags: {'#d': owned.toList()}, + ), + ); + return { + for (final event in registrations) + if (event.kind == 30177 && event.pubkey == owner) + for (final tag in event.tags) + if (tag.length > 1 && tag[0] == 'd' && owned.contains(tag[1])) tag[1], + }; +} + /// Owner-side registry client for Builderlab remote agents, using the same /// account and Beekeeper contracts as desktop. class RemoteAgentController extends ChangeNotifier { @@ -297,7 +322,7 @@ class RemoteAgentController extends ChangeNotifier { await ensureBinding(); if (community.pubkey != owner) { throw StateError( - 'Sign in with the Builderlab account for this community.', + 'Sign in with the Builderlab account you use in this community.', ); } final scope = _storageScope; @@ -478,8 +503,9 @@ class RemoteAgentController extends ChangeNotifier { await ensureBinding(); check(); final scope = _storageScope; - final communityOwner = community.pubkey; - if (communityOwner == null || owner != communityOwner) { + // Agents belong to the member who owns them (NIP-OA), not the community. + final member = community.pubkey; + if (member == null || owner != member) { throw AccountIdentityFailure.mismatch; } final agent = agents @@ -512,7 +538,7 @@ class RemoteAgentController extends ChangeNotifier { final remaining = await fetch( NostrFilter( kinds: const [30177], - authors: [communityOwner], + authors: [member], tags: { '#d': [pubkey], }, diff --git a/mobile/test/shared/agents/remote_agents_test.dart b/mobile/test/shared/agents/remote_agents_test.dart index 5497e21574..7733c4c408 100644 --- a/mobile/test/shared/agents/remote_agents_test.dart +++ b/mobile/test/shared/agents/remote_agents_test.dart @@ -1,6 +1,7 @@ import 'package:buzz/features/profile/presence_cache_provider.dart'; import 'package:buzz/shared/agents/remote_agents.dart'; import 'package:buzz/shared/community/community.dart'; +import 'package:buzz/shared/community/community_provider.dart'; import 'package:buzz/shared/crypto/nip_oa.dart'; import 'package:buzz/shared/hosted/account_identity_store.dart'; import 'package:buzz/shared/hosted/hosted_environment.dart'; @@ -312,54 +313,74 @@ void main() { }); test( - 'availability counts only agents registered in this community', + 'availability requires an owned profile and a live registration', () async { final other = nostr.Keys('0' * 63 + '3').public; - final stranger = nostr.Keys('0' * 63 + '4'); final elsewhere = nostr.Keys('0' * 63 + '5').public; final profiles = [ - NostrEvent( - id: '1', - pubkey: fakeAgent, - createdAt: 1, - kind: 0, - tags: [signOwnerAuthorization(fakeOwner, fakeAgent)], - content: '{}', - sig: '', - ), + _profile(fakeAgent, fakeOwner), // Attested by someone else, so not this owner's agent. - NostrEvent( - id: '2', - pubkey: other, - createdAt: 1, - kind: 0, - tags: [signOwnerAuthorization(stranger, other)], - content: '{}', - sig: '', - ), + _profile(other, nostr.Keys('0' * 63 + '4')), ]; - expect( - await registeredCommunityAgents( - {fakeAgent, other, elsewhere}, - fakeOwner.public, - (filter) async { - expect(filter.kinds, [0]); - return profiles; - }, - ), - {fakeAgent}, - ); - expect( - await registeredCommunityAgents( - {fakeAgent}, - null, - (_) async => profiles, - ), - isEmpty, - ); + var registrations = []; + Future> fetch(NostrFilter filter) async { + if (filter.kinds.single == 0) return profiles; + expect(filter.kinds, [30177]); + expect(filter.authors, [fakeOwner.public]); + expect(filter.tags, { + '#d': [fakeAgent], + }); + return registrations; + } + + final keys = {fakeAgent, other, elsewhere}; + // The list keeps owned agents, so an interrupted delete stays retryable. + expect(await ownedCommunityAgents(keys, fakeOwner.public, fetch), { + fakeAgent, + }); + expect(await liveCommunityAgents(keys, fakeOwner.public, fetch), isEmpty); + registrations = [_registration(fakeAgent)]; + expect(await liveCommunityAgents(keys, fakeOwner.public, fetch), { + fakeAgent, + }); + expect(await liveCommunityAgents(keys, null, fetch), isEmpty); }, ); + test('presence stays local until the agent registration is live', () async { + final registry = FakeRegistry(bound: fakeOwner.public) + ..listed = [ + { + 'agent_pubkey': fakeAgent, + 'agent_id': 'remote-id', + 'status': 'BEEKEEPER_AGENT_STATUS_ACTIVE', + }, + ]; + final controller = await _controller(registry); + final relay = _AgentRelay(); + final container = ProviderContainer( + overrides: [ + presenceCacheProvider.overrideWith(_AgentPresence.new), + activeCommunityProvider.overrideWith((ref) async => _community()), + remoteAgentControllerProvider.overrideWithValue(controller), + relaySessionProvider.overrideWith(() => relay), + ], + ); + addTearDown(container.dispose); + await container.read(activeCommunityProvider.future); + await controller.run(controller.refresh); + + expect(await container.read(availableRemoteAgentsProvider.future), isEmpty); + expect(container.read(presentedPresenceProvider)[fakeAgent], 'offline'); + + relay.live = true; + container.invalidate(availableRemoteAgentsProvider); + expect(await container.read(availableRemoteAgentsProvider.future), { + fakeAgent, + }); + expect(container.read(presentedPresenceProvider)[fakeAgent], 'online'); + }, skip: !HostedEnvironment.enabled); + test('owner proof verifies for only the provisioned agent key', () { final other = nostr.Keys('0' * 63 + '3'); final auth = signOwnerAuthorization(fakeOwner, fakeAgent); @@ -406,3 +427,48 @@ class _Presence extends PresenceCacheNotifier { @override Map build() => {'remote': 'offline', 'local': 'away'}; } + +class _AgentPresence extends PresenceCacheNotifier { + @override + Map build() => {fakeAgent: 'offline'}; +} + +NostrEvent _profile(String pubkey, nostr.Keys owner) => NostrEvent( + id: 'profile-$pubkey', + pubkey: pubkey, + createdAt: 1, + kind: 0, + tags: [signOwnerAuthorization(owner, pubkey)], + content: '{}', + sig: '', +); + +NostrEvent _registration(String agent) => NostrEvent( + id: 'registration-$agent', + pubkey: fakeOwner.public, + createdAt: 1, + kind: 30177, + tags: [ + ['d', agent], + ], + content: '{}', + sig: '', +); + +/// Serves the owner's agent profile, and its registration once [live]. +class _AgentRelay extends RelaySessionNotifier { + bool live = false; + + @override + SessionState build() => const SessionState(status: SessionStatus.connected); + + @override + Future> fetchHistory( + NostrFilter filter, { + Duration timeout = const Duration(seconds: 8), + }) async => switch (filter.kinds.single) { + 0 => [_profile(fakeAgent, fakeOwner)], + 30177 when live => [_registration(fakeAgent)], + _ => [], + }; +}