Skip to content

Commit 745ad85

Browse files
browgeorgeclaude
committed
fix(mobile): recover a pending setup whose instructions were lost
Preferences can outlive device-only secure storage, so a pending setup whose private instructions are missing is restored with the instructions field re-enabled instead of failing every registry operation. Adds a loopback relay test that registration publish and removal reach an http(s)-saved community over a WebSocket URL. Co-authored-by: george <973be878edd6d4f79692a3827f20a6f7fe0ed0362f269ff6b6ba8867033d7d8e@sprout-oss.stage.blox.sqprod.co> Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Tom Brow <[email protected]>
1 parent 3697d52 commit 745ad85

3 files changed

Lines changed: 109 additions & 7 deletions

File tree

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ class CreateAgentSheet extends HookConsumerWidget {
3535
final active = ref.watch(activeCommunityProvider).asData?.value;
3636
final sameCommunity = active?.id == community.id;
3737
final pending = controller.pending != null;
38+
final instructionsMissing =
39+
controller.pending?['instructionsMissing'] == true;
3840
final canCreate =
3941
!controller.busy && sameCommunity && name.text.trim().isNotEmpty;
4042
final actionStyle = IconButton.styleFrom(
@@ -134,7 +136,8 @@ class CreateAgentSheet extends HookConsumerWidget {
134136
const SizedBox(height: Grid.sm),
135137
TextField(
136138
controller: instructions,
137-
enabled: !controller.busy && !pending,
139+
enabled:
140+
!controller.busy && (!pending || instructionsMissing),
138141
minLines: 4,
139142
maxLines: 6,
140143
textCapitalization: TextCapitalization.sentences,

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

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -250,9 +250,12 @@ class RemoteAgentController extends ChangeNotifier {
250250
agents = listed
251251
.where((row) => !deletedAgents.contains(row['agent_pubkey']))
252252
.toList();
253-
status = pending == null
254-
? ''
255-
: 'Unfinished setup saved. Resume to use the same agent.';
253+
status = switch (pending) {
254+
null => '',
255+
{'instructionsMissing': true} =>
256+
'Unfinished setup saved. Enter its instructions again, then Resume.',
257+
_ => 'Unfinished setup saved. Resume to use the same agent.',
258+
};
256259
}
257260

258261
/// Requires this account's saved key to be its current server binding.
@@ -282,9 +285,12 @@ class RemoteAgentController extends ChangeNotifier {
282285
key: '$scope:instructions:${restored!['request']}',
283286
);
284287
if (instructions == null) {
285-
throw StateError('Saved agent instructions are unavailable.');
288+
// Preferences can outlive device-only secure storage, for example
289+
// after a device restore. Keep the setup and ask for them again.
290+
restored['instructionsMissing'] = true;
291+
} else {
292+
restored['instructions'] = instructions;
286293
}
287-
restored['instructions'] = instructions;
288294
}
289295
deletedAgents = prefs.getStringList('$scope:deleted')?.toSet() ?? {};
290296
pending = restored;
@@ -294,7 +300,9 @@ class RemoteAgentController extends ChangeNotifier {
294300
Future<void> _savePending(Map<String, dynamic> value) async {
295301
final scope = _storageScope;
296302
final prefs = await SharedPreferences.getInstance();
297-
final persisted = Map<String, dynamic>.from(value)..remove('instructions');
303+
final persisted = Map<String, dynamic>.from(value)
304+
..remove('instructions')
305+
..remove('hasInstructions');
298306
final instructions = value['instructions'] as String?;
299307
if (instructions != null && instructions.isNotEmpty) {
300308
await accountSecureStorage.write(
@@ -348,6 +356,14 @@ class RemoteAgentController extends ChangeNotifier {
348356
if (setup['owner'] != owner || setup['community'] != community.relayUrl) {
349357
throw StateError('Finish the pending setup in its original community.');
350358
}
359+
if (setup['instructionsMissing'] == true) {
360+
if (instructions.trim().length > 20000) {
361+
throw StateError('Use at most 20,000 characters for instructions.');
362+
}
363+
setup = {...setup, 'instructions': instructions.trim()}
364+
..remove('instructionsMissing');
365+
await _savePending(setup);
366+
}
351367
if (setup['pubkey'] == null) {
352368
status = 'Creating remote identity…';
353369
_notify();

‎mobile/test/shared/agents/remote_agents_test.dart‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
1+
import 'dart:convert';
2+
import 'dart:io';
3+
14
import 'package:buzz/features/profile/presence_cache_provider.dart';
25
import 'package:buzz/shared/agents/remote_agents.dart';
36
import 'package:buzz/shared/community/community.dart';
47
import 'package:buzz/shared/community/community_provider.dart';
58
import 'package:buzz/shared/crypto/nip_oa.dart';
69
import 'package:buzz/shared/hosted/account_identity_store.dart';
710
import 'package:buzz/shared/hosted/hosted_environment.dart';
11+
import 'package:buzz/shared/hosted/hosted_relay_auth.dart';
812
import 'package:buzz/shared/relay/relay.dart';
913
import 'package:buzz/shared/storage/secure_storage.dart';
1014
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
@@ -239,6 +243,85 @@ void main() {
239243
},
240244
);
241245

246+
test('a setup whose instructions were lost asks for them again', () async {
247+
final registry = FakeRegistry(bound: fakeOwner.public)
248+
..failInstructions = true;
249+
final controller = await _controller(registry);
250+
final community = _community();
251+
expect(
252+
await controller.create(community, 'Scout', instructions: 'Private.'),
253+
isFalse,
254+
);
255+
final request = controller.pending!['request'];
256+
// Device-only secure storage is gone; preferences survived (a restore).
257+
await accountSecureStorage.delete(key: '$_scope:instructions:$request');
258+
259+
final restarted = RelayFakeController(registry);
260+
addTearDown(() {
261+
restarted.dispose();
262+
restarted.relayAuth.dispose();
263+
});
264+
expect(await restarted.run(restarted.refresh), isTrue);
265+
expect(restarted.pending?['instructionsMissing'], isTrue);
266+
expect(restarted.status, contains('Enter its instructions again'));
267+
268+
registry
269+
..failInstructions = false
270+
..calls.clear();
271+
expect(
272+
await restarted.create(community, 'Scout', instructions: 'Again.'),
273+
isTrue,
274+
);
275+
expect(
276+
registry.bodies['/v3/beekeeper/update-agent']?['agent_instructions'],
277+
'Again.',
278+
);
279+
expect(restarted.pending, isNull);
280+
final prefs = await SharedPreferences.getInstance();
281+
expect(prefs.getString('$_scope:pending'), isNull);
282+
});
283+
284+
test(
285+
'registrations use a WebSocket URL for https-saved communities',
286+
() async {
287+
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
288+
addTearDown(() => server.close(force: true));
289+
final kinds = <int>[];
290+
server.listen((request) async {
291+
final peer = await WebSocketTransformer.upgrade(request);
292+
addTearDown(peer.close);
293+
peer.listen((frame) {
294+
final data = jsonDecode(frame as String) as List;
295+
final event = Map<String, dynamic>.from(data[1] as Map);
296+
if (data.first == 'EVENT') kinds.add(event['kind'] as int);
297+
peer.add(jsonEncode(['OK', event['id'], true, '']));
298+
});
299+
peer.add(jsonEncode(['AUTH', 'challenge']));
300+
});
301+
final registry = FakeRegistry(bound: fakeOwner.public);
302+
await AccountIdentityStore()
303+
.forSubject(fakeSubject)
304+
.create(fakeOwner.nsec);
305+
final controller = RemoteAgentController(
306+
account: registry,
307+
keys: AccountIdentityStore(),
308+
relayAuth: HostedRelayAuth(registry),
309+
);
310+
addTearDown(() {
311+
controller.dispose();
312+
controller.relayAuth.dispose();
313+
});
314+
// Stored the way paired communities may keep it: an HTTP(S) origin.
315+
final relay = 'http://127.0.0.1:${server.port}';
316+
await controller.publishPolicy(relay, {
317+
'pubkey': fakeAgent,
318+
'name': 'Scout',
319+
});
320+
await controller.removePolicy(relay, fakeAgent);
321+
expect(kinds, [30177, 5]);
322+
},
323+
);
324+
242325
test('a setup without a server identity can be discarded', () async {
243326
final registry = FakeRegistry(bound: fakeOwner.public)
244327
..rejectRegistration = true;

0 commit comments

Comments
 (0)