From 928d4863d5adcda1b30c087107e5d4fb7e69012b Mon Sep 17 00:00:00 2001 From: Tom Brow Date: Mon, 19 Oct 2026 16:23:43 -0700 Subject: [PATCH] Add community-scoped Agents prototype and remote availability presentation Signed-off-by: Tom Brow --- .../channels/channel_detail_page/app_bar.dart | 2 +- .../lib/features/channels/channels_page.dart | 13 ++ .../channels/channels_page/channel_tile.dart | 2 +- .../channels_page/header_actions.dart | 8 + .../mentions/mention_candidates_provider.dart | 2 +- .../profile/presence_cache_provider.dart | 8 + .../features/profile/user_profile_sheet.dart | 2 +- mobile/lib/main_prototype.dart | 191 ++--------------- mobile/lib/prototype/README.md | 20 +- mobile/lib/prototype/agents_sheet.dart | 196 ++++++++++++++++++ mobile/lib/prototype/create_agent_sheet.dart | 156 ++++++++++++++ .../prototype/remote_agent_controller.dart | 71 +++++-- mobile/lib/shared/agents/agents_surface.dart | 11 + .../lib/shared/hosted/builderlab_account.dart | 1 + mobile/test/prototype/agents_ui_test.dart | 183 ++++++++++++++++ .../prototype/creation_contract_test.dart | 131 ++++++++++++ 16 files changed, 797 insertions(+), 200 deletions(-) create mode 100644 mobile/lib/prototype/agents_sheet.dart create mode 100644 mobile/lib/prototype/create_agent_sheet.dart create mode 100644 mobile/lib/shared/agents/agents_surface.dart create mode 100644 mobile/test/prototype/agents_ui_test.dart create mode 100644 mobile/test/prototype/creation_contract_test.dart diff --git a/mobile/lib/features/channels/channel_detail_page/app_bar.dart b/mobile/lib/features/channels/channel_detail_page/app_bar.dart index 22cbcf82fc..685d09b185 100644 --- a/mobile/lib/features/channels/channel_detail_page/app_bar.dart +++ b/mobile/lib/features/channels/channel_detail_page/app_bar.dart @@ -153,7 +153,7 @@ class _ConversationAppBarTitle extends StatelessWidget { ), ); final presence = ref.watch( - presenceCacheProvider.select( + presentedPresenceProvider.select( (presenceMap) => otherPubkey == null ? null : presenceMap[otherPubkey], ), ); diff --git a/mobile/lib/features/channels/channels_page.dart b/mobile/lib/features/channels/channels_page.dart index 08c5376c63..69036ca1fa 100644 --- a/mobile/lib/features/channels/channels_page.dart +++ b/mobile/lib/features/channels/channels_page.dart @@ -1,3 +1,4 @@ +import '../../shared/agents/agents_surface.dart'; import 'channel_unread.dart'; import '../../shared/widgets/collapsible_section_body.dart'; import '../../shared/widgets/compose_morph_icon.dart'; @@ -447,6 +448,9 @@ class ChannelsPage extends HookConsumerWidget { final topSectionGradient = context.appColors.topSectionGradient; final usesPinnedGradient = topSectionGradient != null; + final openAgents = ref.watch(agentsSurfaceProvider); + final onAgents = openAgents == null ? null : () => openAgents(context); + return FrostedScaffold( backgroundColor: usesPinnedGradient ? Colors.transparent @@ -486,6 +490,14 @@ class ChannelsPage extends HookConsumerWidget { icon: BuzzIcons.search300, onPressed: onSearch, ), + if (onAgents != null) + IosNavigationAction( + label: 'Agents', + symbol: 'person.2', + sharesBackground: true, + icon: BuzzIcons.bot, + onPressed: onAgents, + ), if (onInbox != null) IosNavigationAction( label: 'Inbox', @@ -534,6 +546,7 @@ class ChannelsPage extends HookConsumerWidget { actions: [ _ChannelHeaderActions( onSearch: onSearch, + onAgents: onAgents, onInbox: onInbox, hasUnreadInbox: hasUnreadInbox, onSettings: () { diff --git a/mobile/lib/features/channels/channels_page/channel_tile.dart b/mobile/lib/features/channels/channels_page/channel_tile.dart index 553df6abaf..72e73b3a3e 100644 --- a/mobile/lib/features/channels/channels_page/channel_tile.dart +++ b/mobile/lib/features/channels/channels_page/channel_tile.dart @@ -181,7 +181,7 @@ class _DmAvatar extends ConsumerWidget { ), ); final presence = ref.watch( - presenceCacheProvider.select( + presentedPresenceProvider.select( (presenceMap) => otherPubkey == null ? null : presenceMap[otherPubkey], ), ); diff --git a/mobile/lib/features/channels/channels_page/header_actions.dart b/mobile/lib/features/channels/channels_page/header_actions.dart index ce5bfd35ca..921b6aba97 100644 --- a/mobile/lib/features/channels/channels_page/header_actions.dart +++ b/mobile/lib/features/channels/channels_page/header_actions.dart @@ -3,12 +3,14 @@ part of '../channels_page.dart'; class _ChannelHeaderActions extends StatelessWidget { const _ChannelHeaderActions({ required this.onSearch, + required this.onAgents, required this.onInbox, required this.hasUnreadInbox, required this.onSettings, }); final VoidCallback? onSearch; + final VoidCallback? onAgents; final VoidCallback? onInbox; final bool hasUnreadInbox; final VoidCallback onSettings; @@ -28,6 +30,12 @@ class _ChannelHeaderActions extends StatelessWidget { icon: const Icon(BuzzIcons.search300), onPressed: onSearch, ), + if (onAgents != null) + IconButton( + tooltip: 'Agents', + icon: const Icon(BuzzIcons.bot), + onPressed: onAgents, + ), if (onInbox != null) Semantics( label: hasUnreadInbox ? 'Inbox, unread' : 'Inbox', diff --git a/mobile/lib/features/channels/mentions/mention_candidates_provider.dart b/mobile/lib/features/channels/mentions/mention_candidates_provider.dart index 86bab7a801..a5589d08a4 100644 --- a/mobile/lib/features/channels/mentions/mention_candidates_provider.dart +++ b/mobile/lib/features/channels/mentions/mention_candidates_provider.dart @@ -218,7 +218,7 @@ final mentionCandidatesProvider = Provider.family candidates, ); loadIdentityNameOwners(ref, names); - final presence = ref.watch(presenceCacheProvider); + final presence = ref.watch(presentedPresenceProvider); return rankMentionCandidates( [ for (final candidate in candidates) diff --git a/mobile/lib/features/profile/presence_cache_provider.dart b/mobile/lib/features/profile/presence_cache_provider.dart index 8738e34f50..5694776086 100644 --- a/mobile/lib/features/profile/presence_cache_provider.dart +++ b/mobile/lib/features/profile/presence_cache_provider.dart @@ -1,3 +1,4 @@ +import '../../shared/agents/agents_surface.dart'; import 'dart:async'; import 'package:flutter/foundation.dart'; @@ -240,3 +241,10 @@ final presenceCacheProvider = NotifierProvider>( PresenceCacheNotifier.new, ); + +/// Presentation shared by profiles, DMs and mentions. Local presence is unchanged. +final presentedPresenceProvider = Provider>((ref) { + final presence = ref.watch(presenceCacheProvider); + final remote = ref.watch(availableRemoteAgentsProvider); + return {...presence, for (final pubkey in remote) pubkey: 'online'}; +}, dependencies: [availableRemoteAgentsProvider]); diff --git a/mobile/lib/features/profile/user_profile_sheet.dart b/mobile/lib/features/profile/user_profile_sheet.dart index 1899129880..a03db79834 100644 --- a/mobile/lib/features/profile/user_profile_sheet.dart +++ b/mobile/lib/features/profile/user_profile_sheet.dart @@ -82,7 +82,7 @@ class UserProfileSheet extends HookConsumerWidget { final profile = ref.watch(userCacheProvider.select((cache) => cache[pk])) ?? ref.read(userCacheProvider.notifier).get(pk); - final presenceMap = ref.watch(presenceCacheProvider); + final presenceMap = ref.watch(presentedPresenceProvider); final presence = presenceMap[pk]; final statusCache = ref.watch(userStatusCacheProvider); final userStatus = statusCache[pk]; diff --git a/mobile/lib/main_prototype.dart b/mobile/lib/main_prototype.dart index d76f9da5db..fc36726497 100644 --- a/mobile/lib/main_prototype.dart +++ b/mobile/lib/main_prototype.dart @@ -13,9 +13,8 @@ import 'prototype/simulator_browser.dart'; import 'shared/hosted/account_identity_store.dart'; import 'shared/hosted/browser_auth.dart'; import 'shared/hosted/hosted_relay_auth.dart'; -import 'shared/identity_transfer/nsec_import_sheet.dart'; -import 'shared/theme/app_theme.dart'; -import 'shared/theme/grid.dart'; +import 'shared/agents/agents_surface.dart'; +import 'prototype/agents_sheet.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); @@ -51,180 +50,20 @@ class RemotePrototype extends HookConsumerWidget { unawaited(controller.initialize()); return controller.dispose; }, [controller]); - final name = useTextEditingController(text: 'Tom staging prototype'); - final inBuzz = useState(false); - if (inBuzz.value) { - return MaterialApp( - theme: AppTheme.light(), - darkTheme: AppTheme.dark(), - home: Stack( - children: [ - const App(), - Positioned( - right: Grid.xs, - top: Grid.xl, - child: Material( - borderRadius: BorderRadius.circular(Radii.card), - child: TextButton( - onPressed: () => inBuzz.value = false, - child: const Text('Remote agents'), - ), - ), - ), - ], + return ProviderScope( + overrides: [ + agentsSurfaceProvider.overrideWithValue( + (context) => showPrototypeAgents(context, controller), ), - ); - } - return MaterialApp( - title: 'Buzz Remote Prototype', - theme: AppTheme.light(), - darkTheme: AppTheme.dark(), - home: Builder( - builder: (context) => Scaffold( - appBar: AppBar(title: const Text('Remote agents · staging')), - body: ListView( - padding: const EdgeInsets.all(Grid.gutter), - children: [ - const Text( - 'Create a BuilderLab agent from your phone', - style: TextStyle(fontSize: 22, fontWeight: FontWeight.w600), - ), - const SizedBox(height: Grid.xs), - Text(controller.status), - if (controller.busy) - const Padding( - padding: EdgeInsets.symmetric(vertical: Grid.xs), - child: LinearProgressIndicator(), - ), - const SizedBox(height: Grid.xs), - Text( - controller.account.account == null - ? 'BuilderLab: signed out' - : 'BuilderLab: ${controller.account.account!.subject}', - ), - Text( - controller.owner == null - ? 'Buzz identity: not transferred' - : 'Buzz identity: ${controller.owner!.substring(0, 16)}…', - ), - const SizedBox(height: Grid.xs), - FilledButton( - onPressed: controller.busy ? null : controller.signIn, - child: const Text('Sign in to BuilderLab staging'), - ), - if (controller.owner == null) - OutlinedButton( - onPressed: controller.busy - ? null - : () async { - await showNsecImportSheet( - context, - onImport: (nsec) async { - await controller.keys.create(nsec); - }, - ); - await controller.run(controller.refresh); - }, - child: const Text('Import existing Buzz identity'), - ), - if (controller.account.account != null) ...[ - const SizedBox(height: Grid.sm), - const Text('Community'), - for (final community in controller.communities) - ListTile( - title: Text(community.name), - subtitle: Text(community.relayUrl), - leading: Icon( - controller.community?.relayUrl == community.relayUrl - ? Icons.radio_button_checked - : Icons.radio_button_unchecked, - ), - selected: - controller.community?.relayUrl == community.relayUrl, - onTap: controller.busy || controller.pending != null - ? null - : () => controller.run( - () => controller.selectCommunity(community), - ), - ), - if (controller.communities.isEmpty) ...[ - const Text('No owned staging communities found.'), - OutlinedButton( - onPressed: controller.busy - ? null - : controller.createTestCommunity, - child: const Text('Create disposable staging community'), - ), - ], - const SizedBox(height: Grid.xs), - TextField( - controller: name, - enabled: !controller.busy && controller.pending == null, - decoration: const InputDecoration( - labelText: 'Agent name', - border: OutlineInputBorder(), - ), - ), - const SizedBox(height: Grid.xs), - FilledButton( - onPressed: - controller.busy || - controller.owner == null || - controller.community == null - ? null - : () => controller.create(name.text), - child: Text( - controller.pending == null - ? 'Create remote agent' - : 'Resume agent setup', - ), - ), - OutlinedButton( - onPressed: - controller.busy || - controller.owner == null || - controller.community == null - ? null - : () => controller.run(() async { - await controller.saveCommunity(); - inBuzz.value = true; - }), - child: const Text('Open community in Buzz'), - ), - TextButton( - onPressed: controller.busy - ? null - : () => controller.run(controller.refresh), - child: const Text('Refresh'), - ), - const Divider(), - const Text('Your remote agents'), - for (final agent in controller.agents) - ListTile( - title: Text( - agent['agent_name'] as String? ?? 'Unnamed agent', - ), - subtitle: Text( - '${agent['status']}\n${agent['agent_pubkey']}', - ), - isThreeLine: true, - trailing: IconButton( - tooltip: 'Subscribe to selected community', - icon: const Icon(Icons.link), - onPressed: controller.busy || controller.community == null - ? null - : () => controller.run( - () => controller.subscribe( - agent['agent_id'] as String, - ), - ), - ), - ), - ], - ], - ), - ), - ), + availableRemoteAgentsProvider.overrideWithValue({ + for (final agent in controller.agents) + if (controller.account.account != null && + (agent['status'] == 'BEEKEEPER_AGENT_STATUS_ACTIVE' || + agent['status'] == 2)) + agent['agent_pubkey'] as String, + }), + ], + child: const App(), ); } } diff --git a/mobile/lib/prototype/README.md b/mobile/lib/prototype/README.md index 195803d911..7dabe606a0 100644 --- a/mobile/lib/prototype/README.md +++ b/mobile/lib/prototype/README.md @@ -6,15 +6,19 @@ Entry point: `lib/main_prototype.dart`. Required build defines: `BUZZ_BUILDERLAB ## Simulator use -1. Tap **Sign in to BuilderLab staging**. -2. In Mac Chrome, open `http://127.0.0.1:18763/start` and finish the staging account login. The loopback handoff expires after ten minutes. The app validates state and exchanges the code with PKCE. -3. Choose an owned staging community, or create the disposable staging community, and enter an agent name. -4. Tap **Create remote agent**. If an operation fails, **Resume agent setup** reuses the saved registration ID and idempotency key. -5. Open the community in Buzz to interact with the agent. +1. Open the saved staging community in the normal Buzz app. +2. Tap **Agents**, immediately to the right of Search. The list is scoped to that community and opens the existing profile when an agent is selected. +3. Tap **Add agent**, enter a display name and optional private instructions, then **Create**. Successful creation returns to the list. A failed attempt offers **Resume**, preserving its identity and instructions. +4. Open an agent profile to copy its public key or **Message** it. Normal channel mention discovery and admission rules still apply. +5. If signed out, use **Sign in** in Agents, then finish Mac Chrome login through `http://127.0.0.1:18763/start`. The loopback handoff expires after ten minutes and validates state and PKCE. + +Remote availability is an explicit product presentation: exact keys returned ACTIVE by the authenticated Beekeeper registry show green Online in the list, profile, DM header/list and mention ranking. Beekeeper listens for messages and starts/resumes workers, so the worker's transient WebSocket presence is not its availability. Other agents and humans retain relay presence. This does not claim sandbox tool authorization or service-health guarantees. + +The current registry supports name and private instructions, via registration then activation then `update-agent`. It offers no harness or model selection. Instructions are stored in device-only secure storage while setup is pending, separately from public pending metadata. The prototype reuses an existing owner identity only after the current account binding confirms the same key. It adopts the saved key into the account-scoped slot without deleting the old record. New-community admission uses the shared encrypted-backup, binding verification, and relay probe services. Reopening an existing saved community verifies its key and current binding without redoing onboarding or replacing its record. It does not implement new-user identity selection or recovery UI. A debug-only native method transfers a one-time simulator launch environment value into device-only Keychain. It is compiled only for a debug simulator and checks the prototype bundle identifier. No key is embedded in source or build configuration. -The agent's private key remains on BuilderLab. Activation uses the owner's NIP-OA authorization, explicitly subscribes the agent to the selected community, and publishes a relay listing with owner-only responses and parallelism 1. Attestation alone only reconciles server-configured communities, so it is insufficient for a newly created community. The link button beside an existing agent idempotently subscribes it to the selected community. Pending setup contains public identifiers only and is scoped to the staging account. +The agent's private key remains on BuilderLab. Activation uses the owner's NIP-OA authorization, explicitly subscribes the agent to the selected community, and publishes a relay listing with owner-only responses and parallelism 1. Attestation alone only reconciles server-configured communities, so it is insufficient for a newly created community. Pending setup contains public identifiers only and is scoped to the staging account. This is a local experiment, not a production onboarding implementation. Browser account sign-in, live registration, relay admission and agent response must all be verified before treating the end-to-end flow as working. @@ -24,4 +28,6 @@ Adaptation source was recovered from Codex startup-cleanup snapshot `902ca75bae2 October 19 validation so far: 122 hosted/prototype tests and full mobile-check passed, simulator build succeeded, fresh Chrome sign-in and account setup completed for the original subject, and original bound Buzz identity adopted without replacement. Fresh simulator E2E passed: selected the existing agent mention, sent event `b77569c7c013d1a807a2e4530c0b93f1a76fc997cf7dcd1d1d5e529abfb51b95` from the app, and received `d9cef9ae50dee8796cc59ce72578b7f39fac1a5df181970a2e124b9f6cf15b73`, “Rebased mobile prototype works.” Existing account, key, agent and private channel were preserved. Eight staging-specific prototype tests pass, including saved-community identity mismatch rejection. -Remaining live gates: public staging returns 404 for joined-community discovery and federated assertion issuance, and 400 for the current HPKE backup upload. New-community onboarding and federated enforcement are not claimed verified. The successful October 19 acceptance path resumes the already-admitted community and existing agent; it does not claim new-agent provisioning was repeated or sandbox tool execution verified. No production or conference release changes. +Remaining live gates: public staging returns 404 for joined-community discovery and federated assertion issuance, and 400 for the current HPKE backup upload. New-community onboarding and federated enforcement are not claimed verified. New agent creation in the already-admitted community has also been repeated through the Agents modal; sandbox tool execution remains unverified. No production or conference release changes. + +The clean Agents UI was validated on October 19: two fresh agents were created through the modal, successful creation returned to the updated list, and the existing profile supported Copy public key and Message into the correct DM. The controlled `UI Verification` agent received its optional instructions and replied exactly “Mobile Agents UI works.” to a verification request. Profiles opened from the list and the DM both showed Online. Focused validation: 107 mobile tests plus 13 staging prototype tests; full mobile-check and Xcode simulator build passed. These are agent-run simulator checks, not a user walkthrough. diff --git a/mobile/lib/prototype/agents_sheet.dart b/mobile/lib/prototype/agents_sheet.dart new file mode 100644 index 0000000000..0c66f47f29 --- /dev/null +++ b/mobile/lib/prototype/agents_sheet.dart @@ -0,0 +1,196 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +import '../features/profile/user_profile_sheet.dart'; +import '../features/profile/presence_cache_provider.dart'; +import '../shared/community/community_provider.dart'; +import '../shared/crypto/nip_oa.dart'; +import '../shared/identity_names/identity_names_provider.dart'; +import '../shared/mentions/agent_identity_provider.dart'; +import '../shared/profile/user_cache_provider.dart'; +import '../shared/relay/relay.dart'; +import '../shared/theme/theme.dart'; +import '../shared/widgets/avatar_image.dart'; +import '../shared/widgets/buzz_titled_sheet_layout.dart'; +import '../shared/widgets/modal_presentation.dart'; +import 'create_agent_sheet.dart'; +import 'remote_agent_controller.dart'; + +/// Community-scoped list. Returning a key opens the existing profile from the +/// app navigator, so Message can leave both sheets and navigate to the DM. +Future showPrototypeAgents( + BuildContext context, + RemoteAgentController controller, +) async { + final pubkey = await showBuzzModalBottomSheet( + context: context, + isScrollControlled: true, + showCloseButton: false, + builder: (_) => PrototypeAgentsSheet(controller: controller), + ); + if (pubkey != null && context.mounted) { + showUserProfileSheet(context, pubkey); + } +} + +/// Only registry identities with verified owner profiles on this relay belong +/// in its list. Account-wide registry entries alone are not community membership. +Future> registeredCommunityAgents( + List> agents, + String? owner, + Future> Function(NostrFilter) fetch, +) async { + if (agents.isEmpty || owner == null) return {}; + final keys = agents.map((agent) => agent['agent_pubkey'] as String).toSet(); + final events = await fetch(NostrFilters.profilesBatch(keys.toList())); + return { + for (final event in events) + if (keys.contains(event.pubkey) && + verifiedOaOwnerPubkey(event.tags, event.pubkey) == owner) + event.pubkey, + }; +} + +class PrototypeAgentsSheet extends HookConsumerWidget { + const PrototypeAgentsSheet({required this.controller, super.key}); + final RemoteAgentController controller; + + @override + Widget build(BuildContext context, WidgetRef ref) { + useListenable(controller); + final community = ref.watch(activeCommunityProvider).asData?.value; + final directory = ref.watch(agentDirectoryProvider); + final registryFuture = useMemoized( + () => registeredCommunityAgents( + controller.agents, + controller.owner, + ref.read(relaySessionProvider.notifier).fetchHistory, + ), + [community?.relayUrl, controller.agents, controller.owner], + ); + final registered = useFuture(registryFuture, preserveState: false); + final keys = { + ...?registered.data, + for (final entry in directory.asData?.value ?? []) + entry.pubkey, + }.toList(); + final names = watchIdentityNames( + ref, + keys, + agentPubkeys: keys.toSet(), + fallbackNames: { + for (final agent in controller.agents) + agent['agent_pubkey'] as String: agent['agent_name'] as String, + }, + ); + keys.sort((a, b) => names.labelFor(a).compareTo(names.labelFor(b))); + final profiles = ref.watch(userCacheProvider); + final presence = ref.watch(presentedPresenceProvider); + final failed = directory.hasError || registered.hasError; + final loading = + controller.busy || + directory.isLoading || + registered.connectionState != ConnectionState.done; + + Future refresh() async { + await controller.run(controller.refresh); + if (context.mounted) ref.invalidate(agentDirectoryProvider); + } + + return SizedBox( + height: MediaQuery.sizeOf(context).height * .72, + child: BuzzTitledSheetLayout( + title: 'Agents', + leading: IconButton( + tooltip: 'Close', + icon: const Icon(Icons.close), + onPressed: () => Navigator.pop(context), + ), + trailing: TextButton( + onPressed: community == null || controller.busy + ? null + : () => showBuzzModalBottomSheet( + context: context, + isScrollControlled: true, + showCloseButton: false, + builder: (_) => CreatePrototypeAgentSheet( + controller: controller, + community: community, + onCreated: () => ref.invalidate(agentDirectoryProvider), + ), + ), + child: const Text('Add agent'), + ), + child: RefreshIndicator( + onRefresh: refresh, + child: ListView( + physics: const AlwaysScrollableScrollPhysics(), + padding: const EdgeInsets.fromLTRB(Grid.xs, 0, Grid.xs, Grid.sm), + children: [ + if (loading) const LinearProgressIndicator(), + if (controller.account.account == null) + ListTile( + title: const Text('Sign in to create an agent'), + subtitle: controller.busy ? Text(controller.status) : null, + trailing: TextButton( + onPressed: controller.busy ? null : controller.signIn, + child: const Text('Sign in'), + ), + ), + if (failed) + ListTile( + title: const Text('Could not load agents'), + trailing: TextButton( + onPressed: refresh, + child: const Text('Retry'), + ), + ), + if (!loading && !failed && keys.isEmpty) + const Padding( + padding: EdgeInsets.all(Grid.sm), + child: Text( + 'No agents in this community yet.', + textAlign: TextAlign.center, + ), + ), + for (final key in keys) + ListTile( + key: ValueKey(key), + contentPadding: const EdgeInsets.symmetric( + horizontal: Grid.xxs, + ), + leading: AvatarImage( + imageUrl: profiles[key]?.avatarUrl, + radius: Grid.sm, + isAgent: true, + backgroundColor: context.colors.surfaceContainerHighest, + fallback: Center( + child: Text(names.labelFor(key).characters.first), + ), + ), + title: Text(names.labelFor(key)), + subtitle: presence[key] == 'online' + ? Row( + children: [ + Icon( + Icons.circle, + size: Grid.xxs, + color: context.appColors.success, + ), + const SizedBox(width: Grid.half), + const Text('Online'), + ], + ) + : null, + onTap: () => Navigator.pop(context, key), + ), + ], + ), + ), + ), + ); + } +} diff --git a/mobile/lib/prototype/create_agent_sheet.dart b/mobile/lib/prototype/create_agent_sheet.dart new file mode 100644 index 0000000000..038b6f6d48 --- /dev/null +++ b/mobile/lib/prototype/create_agent_sheet.dart @@ -0,0 +1,156 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +import '../shared/community/community.dart'; +import '../shared/community/community_provider.dart'; +import '../shared/deeplink/deep_link.dart'; +import '../shared/theme/theme.dart'; +import '../shared/widgets/buzz_titled_sheet_layout.dart'; +import 'remote_agent_controller.dart'; + +/// Uses the registry's name and private-instructions contract. Runtime/model +/// selection belongs to the remote service and is not an API option here. +class CreatePrototypeAgentSheet extends HookConsumerWidget { + const CreatePrototypeAgentSheet({ + required this.controller, + required this.community, + required this.onCreated, + super.key, + }); + final RemoteAgentController controller; + final Community community; + final VoidCallback onCreated; + + @override + Widget build(BuildContext context, WidgetRef ref) { + useListenable(controller); + final name = useTextEditingController( + text: controller.pending?['name'] as String? ?? '', + ); + final instructions = useTextEditingController( + text: controller.pending?['instructions'] as String? ?? '', + ); + useListenable(name); + final error = useState(null); + final active = ref.watch(activeCommunityProvider).asData?.value; + final sameCommunity = active?.id == community.id; + final pending = controller.pending != null; + + Future create() async { + error.value = null; + final prepared = await controller.run(() async { + if (!sameCommunity) { + throw StateError('The active community changed. Reopen Agents.'); + } + await controller.ensureBinding(); + if (community.pubkey != controller.owner) { + throw StateError('Sign in with the account for this community.'); + } + if (controller.pending != null) { + if (controller.pending!['community'] != community.relayUrl) { + throw StateError( + 'Finish the pending setup in its original community.', + ); + } + controller.community = AddCommunityDeepLink( + name: community.name, + relayUrl: community.relayUrl, + ); + } else { + await controller.selectCommunity( + AddCommunityDeepLink( + name: community.name, + relayUrl: community.relayUrl, + ), + ); + } + }); + if (!prepared) { + if (context.mounted) error.value = controller.status; + return; + } + final success = await controller.create( + name.text, + instructions: instructions.text, + ); + if (!context.mounted) return; + if (success) { + onCreated(); + Navigator.pop(context, true); + } else { + error.value = controller.status; + } + } + + return PopScope( + canPop: !controller.busy, + child: Padding( + padding: EdgeInsets.only( + bottom: MediaQuery.viewInsetsOf(context).bottom, + ), + child: BuzzTitledSheetLayout( + title: 'Create agent', + leading: TextButton( + onPressed: controller.busy ? null : () => Navigator.pop(context), + child: const Text('Cancel'), + ), + trailing: TextButton( + onPressed: + controller.busy || !sameCommunity || name.text.trim().isEmpty + ? null + : create, + child: Text(pending ? 'Resume' : 'Create'), + ), + child: SingleChildScrollView( + padding: const EdgeInsets.all(Grid.gutter), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + TextField( + controller: name, + autofocus: true, + enabled: !controller.busy && !pending, + textCapitalization: TextCapitalization.words, + decoration: const InputDecoration( + labelText: 'Display name', + border: OutlineInputBorder(), + ), + ), + const SizedBox(height: Grid.sm), + TextField( + controller: instructions, + enabled: !controller.busy && !pending, + minLines: 4, + maxLines: 7, + decoration: const InputDecoration( + labelText: 'Instructions (optional)', + hintText: 'Describe what this agent should do.', + border: OutlineInputBorder(), + ), + ), + const SizedBox(height: Grid.xs), + Text( + 'Runs remotely and responds to you in ${community.name}.', + style: context.textTheme.bodySmall, + ), + if (controller.busy) ...[ + const SizedBox(height: Grid.xs), + const LinearProgressIndicator(), + Text(controller.status), + ], + if (error.value != null) ...[ + const SizedBox(height: Grid.xs), + Text( + error.value!, + style: TextStyle(color: context.colors.error), + ), + ], + ], + ), + ), + ), + ), + ); + } +} diff --git a/mobile/lib/prototype/remote_agent_controller.dart b/mobile/lib/prototype/remote_agent_controller.dart index 5b1d96780e..80d7c68522 100644 --- a/mobile/lib/prototype/remote_agent_controller.dart +++ b/mobile/lib/prototype/remote_agent_controller.dart @@ -19,6 +19,7 @@ import '../shared/hosted/hosted_backup_service.dart'; import '../shared/hosted/hosted_community_creation.dart'; import '../shared/hosted/hosted_relay_auth.dart'; import '../shared/relay/relay_provider.dart'; +import '../shared/storage/secure_storage.dart'; import '../shared/relay/signed_event_relay.dart'; /// Staging-only experiment using the same account and Beekeeper contracts as desktop. @@ -80,13 +81,14 @@ class RemoteAgentController extends ChangeNotifier { }); } - Future run(Future Function() action) async { - if (busy) return; + Future run(Future Function() action) async { + if (busy) return false; busy = true; final operation = ++_operation; notifyListeners(); try { await action(); + return true; } catch (error) { // Account failures never carry credentials or response bodies. status = error is AccountFailure @@ -96,6 +98,7 @@ class RemoteAgentController extends ChangeNotifier { : error is StateError ? error.message.toString() : 'Operation failed (${error.runtimeType}). Retry the same setup.'; + return false; } finally { if (operation == _operation) { busy = false; @@ -104,7 +107,7 @@ class RemoteAgentController extends ChangeNotifier { } } - Future signIn() => run(() async { + Future signIn() => run(() async { status = 'Waiting for Mac Chrome. Open http://127.0.0.1:18763/start ' 'on your Mac, then sign in to your public staging account. ' @@ -128,6 +131,15 @@ class RemoteAgentController extends ChangeNotifier { pending = raw == null ? null : Map.from(jsonDecode(raw) as Map); + if (pending?['hasInstructions'] == true) { + final instructions = await accountSecureStorage.read( + key: '$_scope:instructions:${pending!['request']}', + ); + if (instructions == null) { + throw StateError('Saved agent instructions are unavailable.'); + } + pending!['instructions'] = instructions; + } if (owner == null) { status = 'Import your existing Buzz identity to discover communities.'; return; @@ -150,7 +162,7 @@ class RemoteAgentController extends ChangeNotifier { : 'Unfinished setup saved. Resume to use the same agent.'; } - Future createTestCommunity() => run(() async { + Future createTestCommunity() => run(() async { await ensureBinding(); final subject = account.account!.subject; await HostedCreateCommunity( @@ -210,13 +222,22 @@ class RemoteAgentController extends ChangeNotifier { Future _savePending(Map value) async { final prefs = await SharedPreferences.getInstance(); - if (!await prefs.setString('$_scope:pending', jsonEncode(value))) { + final persisted = Map.from(value)..remove('instructions'); + final instructions = value['instructions'] as String?; + if (instructions != null && instructions.isNotEmpty) { + await accountSecureStorage.write( + key: '$_scope:instructions:${value['request']}', + value: instructions, + ); + persisted['hasInstructions'] = true; + } + if (!await prefs.setString('$_scope:pending', jsonEncode(persisted))) { throw StateError('Could not save unfinished setup.'); } pending = value; } - Future create(String name) => run(() async { + Future create(String name, {String instructions = ''}) => run(() async { final selected = community; if (selected == null) { throw StateError('Choose an existing staging community.'); @@ -232,8 +253,12 @@ class RemoteAgentController extends ChangeNotifier { 'Use 1–64 letters, numbers, spaces, dots, hyphens or underscores.', ); } + if (instructions.trim().length > 20000) { + throw StateError('Use at most 20,000 characters for instructions.'); + } await _savePending({ 'name': trimmed, + 'instructions': instructions.trim(), 'community': selected.relayUrl, 'owner': owner, 'request': const Uuid().v4(), @@ -272,7 +297,33 @@ class RemoteAgentController extends ChangeNotifier { 'community_url': selected.relayUrl, }); requireStatus(result, 'ACTIVE', 1); + if ((setup['instructions'] as String?)?.isNotEmpty == true) { + await account.post('/v3/beekeeper/update-agent', { + 'agent_pubkey': pubkey, + 'agent_instructions': setup['instructions'], + }); + } await subscribe(setup['id'] as String); + await publishPolicy(selected, setup); + // Retain the completed registration if the listing refresh fails, so Retry + // resumes the same identity instead of creating another agent. + await refresh(); + final prefs = await SharedPreferences.getInstance(); + await accountSecureStorage.delete( + key: '$_scope:instructions:${setup['request']}', + ); + await prefs.remove('$_scope:pending'); + pending = null; + status = + '${setup['name']} is active. Open Buzz and mention it in a channel.'; + }); + + /// Publish the owner policy only after activation and subscription succeed. + Future publishPolicy( + AddCommunityDeepLink selected, + Map setup, + ) async { + final pubkey = setup['pubkey'] as String; await keys.withKeys((key) async { await submitSignedEventOnce( wsUrl: selected.relayUrl, @@ -292,13 +343,7 @@ class RemoteAgentController extends ChangeNotifier { ], ); }); - final prefs = await SharedPreferences.getInstance(); - await prefs.remove('$_scope:pending'); - pending = null; - await refresh(); - status = - '${setup['name']} is active. Open Buzz and mention it in a channel.'; - }); + } Future subscribe(String agentId) async { final selected = community; diff --git a/mobile/lib/shared/agents/agents_surface.dart b/mobile/lib/shared/agents/agents_surface.dart new file mode 100644 index 0000000000..a13dc420a6 --- /dev/null +++ b/mobile/lib/shared/agents/agents_surface.dart @@ -0,0 +1,11 @@ +import 'package:flutter/widgets.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +/// Optional agent-management entry point supplied by the app composition root. +final agentsSurfaceProvider = Provider( + (ref) => null, +); + +/// Exact public keys whose remote service has confirmed ACTIVE lifecycle. +/// Remote workers wake on messages, so this means available, not socket presence. +final availableRemoteAgentsProvider = Provider>((ref) => const {}); diff --git a/mobile/lib/shared/hosted/builderlab_account.dart b/mobile/lib/shared/hosted/builderlab_account.dart index a2e7f96fdc..b5f0865e65 100644 --- a/mobile/lib/shared/hosted/builderlab_account.dart +++ b/mobile/lib/shared/hosted/builderlab_account.dart @@ -228,6 +228,7 @@ class BuilderlabAccountClient { }) { const agentRoutes = { '/v3/beekeeper/register-agent', + '/v3/beekeeper/update-agent', '/v3/beekeeper/attest-agent', '/v3/beekeeper/list-agents', '/v3/beekeeper/add-buzz-subscription', diff --git a/mobile/test/prototype/agents_ui_test.dart b/mobile/test/prototype/agents_ui_test.dart new file mode 100644 index 0000000000..176a5de32b --- /dev/null +++ b/mobile/test/prototype/agents_ui_test.dart @@ -0,0 +1,183 @@ +import 'package:buzz/prototype/agents_sheet.dart'; +import 'package:buzz/shared/relay/relay.dart'; +import 'package:nostr/nostr.dart' as nostr; +import 'package:buzz/prototype/create_agent_sheet.dart'; +import 'package:buzz/prototype/remote_agent_controller.dart'; +import 'package:buzz/shared/agents/agents_surface.dart'; +import 'package:buzz/shared/community/community.dart'; +import 'package:buzz/shared/community/community_provider.dart'; +import 'package:buzz/shared/deeplink/deep_link.dart'; +import 'package:buzz/shared/hosted/account_identity_store.dart'; +import 'package:buzz/shared/hosted/browser_auth.dart'; +import 'package:buzz/shared/hosted/builderlab_account.dart'; +import 'package:buzz/shared/hosted/hosted_relay_auth.dart'; +import 'package:buzz/features/profile/presence_cache_provider.dart'; +import 'package:buzz/shared/theme/theme.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +class _Presence extends PresenceCacheNotifier { + @override + Map build() => {'remote': 'offline', 'local': 'away'}; +} + +class _Controller extends RemoteAgentController { + _Controller(BuilderlabAccountClient account) + : super( + account: account, + browser: BrowserAuth(), + keys: AccountIdentityStore(), + relayAuth: HostedRelayAuth(account), + ); + String? submittedName; + String? submittedInstructions; + bool succeed = true; + @override + Future ensureBinding() async { + owner = 'owner'; + } + + @override + Future selectCommunity(AddCommunityDeepLink value) async { + community = value; + } + + @override + Future create(String name, {String instructions = ''}) async { + submittedName = name; + submittedInstructions = instructions; + status = 'Creation failed. Retry.'; + return succeed; + } +} + +void main() { + test( + 'account-wide agents require verified owner profiles on the current relay', + () async { + final owner = nostr.Keys('0' * 63 + '1'); + final here = nostr.Keys('0' * 63 + '2'); + final elsewhere = nostr.Keys('0' * 63 + '3'); + final forged = nostr.Keys('0' * 63 + '4'); + final keys = await registeredCommunityAgents( + [ + for (final key in [here, elsewhere, forged]) + {'agent_pubkey': key.public}, + ], + owner.public, + (filter) async => [ + NostrEvent( + id: 'here', + pubkey: here.public, + createdAt: 1, + kind: 0, + tags: [signOwnerAuthorization(owner, here.public)], + content: '{}', + sig: '', + ), + NostrEvent( + id: 'forged', + pubkey: forged.public, + createdAt: 1, + kind: 0, + tags: [signOwnerAuthorization(owner, here.public)], + content: '{}', + sig: '', + ), + ], + ); + expect(keys, {here.public}); + }, + ); + + test( + 'remote availability overrides socket offline without changing local presence', + () { + final container = ProviderContainer( + overrides: [ + presenceCacheProvider.overrideWith(_Presence.new), + availableRemoteAgentsProvider.overrideWithValue({'remote'}), + ], + ); + addTearDown(container.dispose); + expect(container.read(presentedPresenceProvider), { + 'remote': 'online', + 'local': 'away', + }); + expect(container.read(presenceCacheProvider)['remote'], 'offline'); + }, + ); + + for (final succeed in [true, false]) { + testWidgets( + 'Create returns to list only after confirmed success: $succeed', + (tester) async { + final account = BuilderlabAccountClient(); + final controller = _Controller(account)..succeed = succeed; + addTearDown(() { + controller.dispose(); + controller.relayAuth.dispose(); + account.dispose(); + }); + final community = Community.create( + name: 'Test community', + relayUrl: 'wss://test.communities.public.builderlabstaging.xyz', + pubkey: 'owner', + ); + var refreshed = false; + await tester.pumpWidget( + ProviderScope( + overrides: [ + activeCommunityProvider.overrideWith((ref) async => community), + ], + child: MaterialApp( + theme: AppTheme.light(), + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => showModalBottomSheet( + context: context, + isScrollControlled: true, + builder: (_) => CreatePrototypeAgentSheet( + controller: controller, + community: community, + onCreated: () => refreshed = true, + ), + ), + child: const Text('Agents list'), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Agents list')); + await tester.pumpAndSettle(); + await tester.enterText( + find.widgetWithText(TextField, 'Display name'), + 'Scout', + ); + await tester.enterText( + find.widgetWithText(TextField, 'Instructions (optional)'), + 'Reply concisely.', + ); + await tester.pump(); + await tester.tap(find.text('Create')); + await tester.pumpAndSettle(); + expect(controller.submittedName, 'Scout'); + expect(controller.submittedInstructions, 'Reply concisely.'); + expect(controller.community?.relayUrl, community.relayUrl); + expect(refreshed, succeed); + expect( + find.text('Create agent'), + succeed ? findsNothing : findsOneWidget, + ); + if (!succeed) { + expect(find.text('Creation failed. Retry.'), findsOneWidget); + } + }, + ); + } +} diff --git a/mobile/test/prototype/creation_contract_test.dart b/mobile/test/prototype/creation_contract_test.dart new file mode 100644 index 0000000000..e2407ca1a1 --- /dev/null +++ b/mobile/test/prototype/creation_contract_test.dart @@ -0,0 +1,131 @@ +import 'package:buzz/prototype/remote_agent_controller.dart'; +import 'package:buzz/shared/deeplink/deep_link.dart'; +import 'package:buzz/shared/hosted/account_identity_store.dart'; +import 'package:buzz/shared/hosted/browser_auth.dart'; +import 'package:buzz/shared/hosted/hosted_environment.dart'; +import 'package:buzz/shared/hosted/hosted_relay_auth.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:nostr/nostr.dart' as nostr; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'remote_agent_controller_test.dart' show BoundAccount; + +class _Registry extends BoundAccount { + _Registry(super.pubkey); + final calls = []; + final bodies = >{}; + bool failInstructions = true; + @override + Future> post( + String path, + Map body, + ) async { + calls.add(path.split('/').last); + bodies[path] = body; + switch (path) { + case '/v3/beekeeper/register-agent': + return { + 'status': 1, + 'agent_pubkey': nostr.Keys('0' * 63 + '2').public, + 'agent_id': 'agent', + }; + case '/v3/beekeeper/attest-agent': + return {'status': 1}; + case '/v3/beekeeper/update-agent': + if (failInstructions) throw StateError('instructions unavailable'); + return {}; + case '/v3/beekeeper/add-buzz-subscription': + return {'status': 1}; + default: + throw StateError('Unexpected request: $path'); + } + } +} + +class _Controller extends RemoteAgentController { + _Controller(_Registry account, AccountIdentityStore keys) + : super( + account: account, + browser: BrowserAuth(), + keys: keys, + relayAuth: HostedRelayAuth(account), + ); + @override + Future refresh() async {} + @override + Future publishPolicy( + AddCommunityDeepLink selected, + Map setup, + ) async { + (account as _Registry).calls.add('publish-policy'); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + test( + 'instructions follow activation; failed update resumes same identity before subscription', + () async { + FlutterSecureStorage.setMockInitialValues({}); + SharedPreferences.setMockInitialValues({}); + final key = nostr.Keys('0' * 63 + '1'); + final keys = AccountIdentityStore(); + await keys.create(key.nsec); + final account = _Registry(key.public); + final controller = _Controller(account, keys) + ..community = const AddCommunityDeepLink( + name: 'Test', + relayUrl: 'wss://test.communities.public.builderlabstaging.xyz', + ); + addTearDown(() { + controller.dispose(); + controller.relayAuth.dispose(); + account.dispose(); + }); + expect( + await controller.create('Scout', instructions: 'x' * 20001), + isFalse, + ); + expect(account.calls, isEmpty); + expect(controller.pending, isNull); + expect( + await controller.create('Scout', instructions: 'Reply concisely.'), + isFalse, + ); + expect(account.calls, ['register-agent', 'attest-agent', 'update-agent']); + expect(controller.pending?['id'], 'agent'); + expect(controller.pending?['instructions'], 'Reply concisely.'); + final prefs = await SharedPreferences.getInstance(); + expect( + prefs.getString('null:pending'), + isNot(contains('Reply concisely.')), + ); + account.failInstructions = false; + expect( + await controller.create( + 'Other name', + instructions: 'Other instructions', + ), + isTrue, + ); + expect(account.calls, [ + 'register-agent', + 'attest-agent', + 'update-agent', + 'attest-agent', + 'update-agent', + 'add-buzz-subscription', + 'publish-policy', + ]); + expect( + account.bodies['/v3/beekeeper/update-agent']?['agent_instructions'], + 'Reply concisely.', + ); + expect(controller.pending, isNull); + }, + skip: HostedEnvironment.origin.host != 'app.builderlabstaging.xyz' + ? 'Run with the staging build define.' + : false, + ); +}