Skip to content

Commit 638f5ec

Browse files
square-tombclaude
andcommitted
fix(mobile): keep open Agents work and saved setups safe from card links
- A card link arriving while a form or sheet is open in Agents shows a snackbar instead of replacing the open work. - Reload the registry for the signed-in account before the unfinished setup check, so a link that needed sign-in still respects a saved setup. - Unexpected card responses show a retryable message. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Tom Brow <[email protected]>
1 parent a22a7b4 commit 638f5ec

8 files changed

Lines changed: 193 additions & 15 deletions

File tree

‎mobile/README.md‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,12 @@ agent. A Builderlab agent card's QR leads to its share page
3838

3939
The app fetches `<avatars CDN>/<id>/agent.json` from the CDN for this build's
4040
Builderlab environment (`HostedEnvironment.avatarsCdnOrigin`), never from a
41-
host named by the link. The link carries only the id, so instructions can be
42-
any length while the QR stays small.
41+
host named by the link. The link carries only the id, so the QR stays small
42+
however long the instructions are.
4343

4444
```json
4545
{
46+
"id": "<id>",
4647
"name": "Scout",
4748
"avatarUrl": "https://<avatars CDN>/<id>/<revision>/avatar.png",
4849
"instructions": "Reply concisely.",
@@ -55,16 +56,23 @@ any length while the QR stays small.
5556
required. `instructions`, `model` and `reasoningEffort` are optional and left
5657
for the user when absent. A missing required field or a known field of the
5758
wrong type makes the card invalid, and no form opens. Other keys, including
58-
`v`, are ignored. The card id is opaque to the app.
59+
`v` and `description`, are ignored whatever their type. The card id is opaque
60+
to the app.
61+
- Prefilled values are only a draft: Create applies its usual rules, so a name
62+
outside 1 to 64 letters, numbers, spaces, dots, hyphens or underscores, or
63+
instructions over 20,000 characters, must be edited before Create succeeds.
5964
- The fetch shares the image loader's limits (`lib/shared/utils/bounded_fetch.dart`):
6065
it is aborted after 20 seconds without a byte or 5 minutes overall, and a card
6166
over 2 MB is rejected.
6267
- `model` and `reasoningEffort` are pre-selected only if the live model catalog
6368
offers them (the effort only for that model).
6469
- The link waits for sign-in and community load. It needs Builderlab login and a
65-
hosted community that supports remote agents, and is dropped with a message if
66-
an unfinished agent setup exists (resume or discard that first) or the card
67-
can't be loaded.
70+
hosted community that supports remote agents. It reloads the signed-in
71+
account's agents first, and is dropped with a message if an unfinished agent
72+
setup exists (resume or discard that first) or the card can't be loaded.
73+
- A link that arrives while Agents is open replaces it only when the list is
74+
all that's showing. With a form, profile or dialog open, the link is dropped
75+
with a message so unfinished work is kept.
6876

6977
The parser is `lib/shared/deeplink/agent_creation_link.dart`; the card reader
7078
is `lib/features/agents/agent_creation_draft.dart`.

‎mobile/lib/features/agents/agent_creation_draft.dart‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import 'dart:convert';
22

3+
import 'package:flutter/foundation.dart';
34
import 'package:hooks_riverpod/hooks_riverpod.dart';
45
import 'package:http/http.dart' as http;
56

@@ -82,8 +83,9 @@ class AgentCreationDraft {
8283
throw const AgentCardException('This agent card isn’t available.');
8384
}
8485
if (response.statusCode != 200) {
85-
throw AgentCardException(
86-
'Couldn’t load this agent card (HTTP ${response.statusCode}).',
86+
debugPrint('agents: agent card HTTP ${response.statusCode}');
87+
throw const AgentCardException(
88+
'Couldn’t load this agent card. Try again later.',
8789
);
8890
}
8991
final Object? json;

‎mobile/lib/features/agents/agents_page.dart‎

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@ import 'bestie_agent_action.dart';
3737

3838
Route<Channel>? _openAgentsRoute;
3939

40+
/// The open Agents stack's nested navigator, so a link can tell whether
41+
/// anything is open above its list.
42+
GlobalKey<NavigatorState>? _openAgentsNavigator;
43+
4044
/// Opens the active community's full-page Agents navigation stack.
4145
///
4246
/// A [draft] from a `buzz://agent/new` link opens [CreateAgentPage] pre-filled
@@ -47,23 +51,39 @@ Future<void> showAgents(
4751
}) async {
4852
final container = ProviderScope.containerOf(context);
4953
final controller = container.read(remoteAgentControllerProvider);
50-
unawaited(controller.run(controller.refresh));
5154
final navigator = Navigator.of(context);
5255
// A link replaces an Agents stack that is already open instead of stacking
53-
// a second one on top of it.
56+
// a second one on top of it, but only while it shows just its list: a form,
57+
// profile or dialog above it may hold work the user hasn't finished.
5458
final open = _openAgentsRoute;
5559
if (draft != null &&
5660
open != null &&
5761
open.isActive &&
5862
open.navigator == navigator) {
63+
if (!open.isCurrent ||
64+
(_openAgentsNavigator?.currentState?.canPop() ?? false)) {
65+
ScaffoldMessenger.maybeOf(context)?.showFeedbackSnackBar(
66+
const SnackBar(
67+
content: Text(
68+
'Finish or close what’s open in Agents, then reopen the link.',
69+
),
70+
),
71+
kind: ToastKind.error,
72+
);
73+
return;
74+
}
5975
navigator.removeRoute(open);
6076
}
77+
unawaited(controller.run(controller.refresh));
6178
final route = MaterialPageRoute<Channel>(
6279
builder: (_) => _AgentsNavigation(controller: controller, draft: draft),
6380
);
6481
_openAgentsRoute = route;
6582
final channel = await navigator.push(route);
66-
if (identical(_openAgentsRoute, route)) _openAgentsRoute = null;
83+
if (identical(_openAgentsRoute, route)) {
84+
_openAgentsRoute = null;
85+
_openAgentsNavigator = null;
86+
}
6787
if (channel != null && context.mounted) {
6888
await Navigator.of(context).push<void>(
6989
MaterialPageRoute(builder: (_) => ChannelDetailPage(channel: channel)),
@@ -84,6 +104,9 @@ class _AgentsNavigation extends HookConsumerWidget {
84104
final navigator = useMemoized(() => GlobalKey<NavigatorState>(), [
85105
communityId,
86106
]);
107+
if (identical(ModalRoute.of(context), _openAgentsRoute)) {
108+
_openAgentsNavigator = navigator;
109+
}
87110
return NavigatorPopHandler<Channel>(
88111
onPopWithResult: (result) {
89112
if (navigator.currentState?.canPop() ?? false) {
@@ -288,6 +311,7 @@ class AgentsPage extends HookConsumerWidget {
288311
// Open a link's draft once: sign in first if needed, then wait for the
289312
// registry so an unfinished setup is known before anything is offered.
290313
final draftStep = useRef(draft == null ? _DraftStep.done : _DraftStep.wait);
314+
final draftRefreshFor = useRef<String?>(null);
291315
// Looked up during build: effects cannot read inherited widgets, and
292316
// snack bars cannot show while a frame is building.
293317
final messenger = ScaffoldMessenger.maybeOf(context);
@@ -333,6 +357,18 @@ class AgentsPage extends HookConsumerWidget {
333357
}
334358
return null;
335359
}
360+
// The setup check below needs this account's registry, which a
361+
// sign-in started by the link doesn't reload by itself.
362+
final subject = controller.account.account!.subject;
363+
if (!controller.loadedForCurrentAccount) {
364+
if (draftRefreshFor.value != subject) {
365+
draftRefreshFor.value = subject;
366+
unawaited(controller.run(controller.refresh));
367+
} else {
368+
drop('Couldn’t load your agents. Reopen the link to retry.');
369+
}
370+
return null;
371+
}
336372
if (controller.listingFailed) {
337373
drop('Couldn’t load your agents. Reopen the link to retry.');
338374
return null;
@@ -345,7 +381,6 @@ class AgentsPage extends HookConsumerWidget {
345381
}
346382
draftStep.value = _DraftStep.done;
347383
// The checks above hold for this account; the fetch can take minutes.
348-
final subject = controller.account.account?.subject;
349384
final client = ref.read(agentCardClientProvider)();
350385
unawaited(() async {
351386
// Hold Create (+) off while the card loads, like an open form does.
@@ -393,6 +428,7 @@ class AgentsPage extends HookConsumerWidget {
393428
flow.stage,
394429
community?.id,
395430
controller.account.account?.subject,
431+
controller.loadedForCurrentAccount,
396432
],
397433
);
398434

‎mobile/lib/features/channels/deep_link_dispatcher.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ class _DeepLinkDispatcherState extends ConsumerState<DeepLinkDispatcher> {
138138
if (mounted) {
139139
ScaffoldMessenger.maybeOf(context)?.showFeedbackSnackBar(
140140
const SnackBar(
141-
content: Text('Couldn’t open this agent draft. Reopen the link.'),
141+
content: Text('Couldn’t open this agent card. Reopen the link.'),
142142
),
143143
kind: ToastKind.error,
144144
);

‎mobile/lib/shared/agents/remote_agents.dart‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,10 @@ class RemoteAgentController extends ChangeNotifier {
179179
return _keys.forSubject(subject);
180180
}
181181

182+
/// Whether the signed-in account's saved state (its binding and any
183+
/// unfinished setup) has been read since it signed in.
184+
bool get loadedForCurrentAccount => _scope != null && _scope == _currentScope;
185+
182186
/// Empty until the signed-in account's own registry has loaded.
183187
Set<String> get activeAgents => _scope == null || _scope != _currentScope
184188
? const {}

‎mobile/test/features/agents/agent_creation_link_journey_test.dart‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,23 @@ void main() {
142142
// Everything stays editable, then Create submits the edited values.
143143
await tester.enterText(_field('Name'), 'Scout Two');
144144
await tester.enterText(_field('Instructions'), 'Be formal.');
145+
146+
// A link arriving now must not discard the open form or its edits.
147+
await receive(_link('av_v1'));
148+
expect(find.byType(CreateAgentPage), findsOneWidget);
149+
expect(find.text('Scout Two'), findsOneWidget);
150+
expect(
151+
find.text(
152+
'Finish or close what’s open in Agents, then reopen the link.',
153+
),
154+
findsOneWidget,
155+
);
156+
expect(_cdnRequests, hasLength(1));
157+
ScaffoldMessenger.of(
158+
tester.element(find.byType(CreateAgentPage)),
159+
).removeCurrentSnackBar();
160+
await tester.pumpAndSettle();
161+
145162
await tester.ensureVisible(find.text('Thinking'));
146163
await tester.tap(find.text('Thinking'));
147164
await tester.pumpAndSettle();
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import 'dart:convert';
2+
3+
import 'package:buzz/features/agents/agent_creation_draft.dart';
4+
import 'package:buzz/features/agents/agents_page.dart';
5+
import 'package:buzz/features/agents/create_agent_page.dart';
6+
import 'package:buzz/shared/deeplink/deep_link.dart';
7+
import 'package:buzz/shared/hosted/hosted_environment.dart';
8+
import 'package:buzz/shared/hosted/hosted_flow.dart';
9+
import 'package:buzz/shared/hosted/hosted_flow_provider.dart';
10+
import 'package:flutter/material.dart';
11+
import 'package:flutter_test/flutter_test.dart';
12+
import 'package:http/http.dart' as http;
13+
import 'package:http/testing.dart';
14+
import 'package:shared_preferences/shared_preferences.dart';
15+
16+
import '../../helpers/remote_agents_fixture.dart';
17+
import 'agents_harness.dart';
18+
19+
/// Fakes only the browser sign-in. Like the real flow, completion clears
20+
/// `reconnecting` in the same synchronous step that reports `complete`.
21+
class _SignInFlow extends ChangeNotifier implements HostedFlow {
22+
@override
23+
HostedFlowStage stage = HostedFlowStage.idle;
24+
@override
25+
bool reconnecting = false;
26+
int starts = 0;
27+
28+
@override
29+
Future<void> reconnectAccount({bool changeAccount = false}) async {
30+
starts++;
31+
reconnecting = true;
32+
stage = HostedFlowStage.signIn;
33+
notifyListeners();
34+
}
35+
36+
void complete() {
37+
stage = HostedFlowStage.complete;
38+
reconnecting = false;
39+
notifyListeners();
40+
}
41+
42+
@override
43+
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
44+
}
45+
46+
void main() {
47+
testWidgets(
48+
'a link that needs sign-in still respects a saved unfinished setup',
49+
(tester) async {
50+
final h = await AgentsHarness.create();
51+
// The login expired, but this account saved an unfinished setup.
52+
h.registry.signedIn = false;
53+
final prefs = await SharedPreferences.getInstance();
54+
await prefs.setString(
55+
'remote-agents:${HostedEnvironment.origin.host}:$fakeSubject:pending',
56+
jsonEncode({
57+
'name': 'Saved',
58+
'instructions': '',
59+
'community': h.community.relayUrl,
60+
'owner': fakeOwner.public,
61+
'request': 'saved-request',
62+
}),
63+
);
64+
final flow = _SignInFlow();
65+
var cardFetches = 0;
66+
await h.open(
67+
tester,
68+
directory: const [],
69+
overrides: [
70+
hostedFlowProvider.overrideWithValue(flow),
71+
agentCardClientProvider.overrideWithValue(
72+
() => MockClient((_) async {
73+
cardFetches++;
74+
return http.Response('{}', 404);
75+
}),
76+
),
77+
],
78+
home: Builder(
79+
builder: (context) => Scaffold(
80+
body: TextButton(
81+
onPressed: () => showAgents(
82+
context,
83+
draft: const AgentCreationDeepLink('av_card'),
84+
),
85+
child: const Text('Open link'),
86+
),
87+
),
88+
),
89+
);
90+
await tester.tap(find.text('Open link'));
91+
await tester.pumpAndSettle();
92+
expect(flow.starts, 1);
93+
94+
// Sign-in lands. The registry is reloaded for this account before the
95+
// card is considered, so the saved setup blocks it.
96+
h.registry.signedIn = true;
97+
flow.complete();
98+
await tester.pumpAndSettle();
99+
expect(find.byType(CreateAgentPage), findsNothing);
100+
expect(cardFetches, 0);
101+
expect(
102+
find.text(
103+
'Finish your unfinished agent setup first, then reopen the link.',
104+
),
105+
findsOneWidget,
106+
);
107+
expect(h.controller.pending?['name'], 'Saved');
108+
},
109+
skip: !HostedEnvironment.enabled,
110+
);
111+
}

‎mobile/test/shared/deeplink/agent_creation_link_test.dart‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -215,11 +215,11 @@ void main() {
215215
'404': ((_, _) async => respond(404), 'This agent card isn’t available.'),
216216
'redirect': (
217217
(_, _) async => respond(302),
218-
'Couldn’t load this agent card (HTTP 302).',
218+
'Couldn’t load this agent card. Try again later.',
219219
),
220220
'500': (
221221
(_, _) async => respond(500),
222-
'Couldn’t load this agent card (HTTP 500).',
222+
'Couldn’t load this agent card. Try again later.',
223223
),
224224
'network error': (
225225
(_, _) async => throw http.ClientException('offline'),

0 commit comments

Comments
 (0)