Files
buzz/mobile/test/helpers/remote_agents_fixture.dart
Tom Brow ec1b786ef0 fix(mobile): diagnostic reporting follow-ups (#9808)
Follow-ups to the mobile diagnostic reporting work in
docs/mobile-diagnostic-reporting.md.

## Changes

- **Install ID repair:** if the install ID file holds something that
isn't text, the app now replaces it with a new ID, as it already does
for an empty file. Before, every report went out without an install ID.
A read that fails (for example, no file descriptor free) still keeps the
file, so a passing error never replaces a good ID.
- **Clock-window refusals are not reported as errors:** the spec treats
relay refusals for a timestamp outside the relay's clock window as
expected (counting them is still pending). The app only recognized one
of the relay's wordings ("timestamp too far from server time"), so
refusals for canvas events, relay-admin commands, leave requests and
observer frames were reported as invalid requests. The five wordings are
matched from the start of the reason, so unrelated `invalid:` reasons
that mention a timestamp, such as the feedback timestamp overflow or one
that echoes a value, are still reported.
- **Diagnostics card:** rows get subtitles, and the divider indent
matches the neighbouring Settings cards.
- **Comments:** explain why push stop gates its current-identity request
on the community key, and correct a test comment about who drops a
repeated error object.

## Validation

New tests cover:
- member attribution on relay sessions, including a missing key and an
answer that arrives after the member changed;
- push stop reports while signed out;
- reporter wiring for hosted admission and the self-hosted probe;
- frames the socket can't decode;
- a table of relay refusal reasons, each either reported or not, for
both `OK` and `CLOSED`;
- an install ID file whose reads fail keeps its ID.

Full-app run on an iPhone 17 Pro simulator at 61b04f6: startup, channel
list, sending and reacting, Settings, the Diagnostics card and Send test
report, and install ID repair (a file that isn't valid UTF-8 and an
empty file each got a new ID that stayed the same on the next launch).
Not covered: a relay clock-window refusal, which the live relay would
not produce.

## Diagnostics card

| Before | After |
| --- | --- |
| ![Diagnostics card
before](https://github.com/user-attachments/assets/b8fa7100-3efd-4c36-ac4d-006d487f4902)
| ![Diagnostics card after, with row
subtitles](https://github.com/user-attachments/assets/9ca7e95b-6061-4efa-b476-d7bb4c113a9b)
|

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-20 12:49:57 -08:00

202 lines
6.2 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'package:buzz/shared/agents/remote_agents.dart';
import 'package:buzz/shared/hosted/account_identity_store.dart';
import 'package:buzz/shared/hosted/builderlab_account.dart';
import 'package:buzz/shared/hosted/hosted_relay_auth.dart';
import 'package:buzz/shared/relay/relay.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:nostr/nostr.dart' as nostr;
final fakeOwner = nostr.Keys('0' * 63 + '1');
final fakeAgentKeys = nostr.Keys('0' * 63 + '2');
final fakeAgent = fakeAgentKeys.public;
const fakeSubject = 'remote-owner';
/// Fakes only the Builderlab network boundary.
class FakeRegistry extends BuilderlabAccountClient {
FakeRegistry({this.bound, bool signedIn = true}) : _signedIn = signedIn {
_changes.value = signedIn ? fakeSubject : null;
}
String? bound;
bool _signedIn;
String _subjectValue = fakeSubject;
final _changes = ValueNotifier<String?>(null);
bool get signedIn => _signedIn;
set signedIn(bool value) {
_signedIn = value;
_changes.value = value ? _subjectValue : null;
}
String get subject => _subjectValue;
set subject(String value) {
_subjectValue = value;
if (_signedIn) _changes.value = value;
}
@override
ValueListenable<String?> get subjectChanges => _changes;
bool failInstructions = false;
bool ignoreModelUpdate = false;
List<Map<String, dynamic>> models = [
{
'id': 'test-model',
'display_name': 'Test model',
'supported_reasoning_efforts': ['low', 'high'],
},
{
'id': 'other-model',
'display_name': 'Other model',
'supported_reasoning_efforts': ['max'],
},
];
Map<String, dynamic>? recommendedSelection;
Completer<void>? catalogGate;
bool failCatalog = false;
bool failListing = false;
bool rejectRegistration = false;
bool loseRegistration = false;
bool refuseRegistration = false;
Object deleteStatus = 1;
final calls = <String>[];
final bodies = <String, Map<String, dynamic>>{};
List<Map<String, dynamic>> listed = [];
@override
BuilderlabAccount? get account => signedIn
? BuilderlabAccount(subject: subject, expiresAt: DateTime.utc(2030))
: null;
/// Holds [restore] open so a test can observe a cold-start restoration.
Completer<void>? restoreGate;
@override
Future<BuilderlabAccount?> restore() async {
await restoreGate?.future;
return account;
}
@override
Future<Map<String, dynamic>> currentIdentity({String? signer}) async => {
'identity': {'pubkey_hex': bound},
};
@override
Future<Map<String, dynamic>> post(
String path,
Map<String, dynamic> body, {
String? expectedSubject,
String? signer,
}) async {
if (expectedSubject != null && account?.subject != expectedSubject) {
throw AccountFailure.differentAccount;
}
calls.add(path.split('/').last);
bodies[path] = body;
switch (path) {
case '/v3/beekeeper/get-model-catalog':
await catalogGate?.future;
if (failCatalog) throw StateError('Catalog unavailable.');
return {
'models': models,
'recommended_selection': ?recommendedSelection,
};
case '/v3/beekeeper/list-agents':
if (failListing) throw StateError('Registry unavailable.');
return {'status': 1, 'agents': listed};
case '/v3/beekeeper/register-agent':
if (refuseRegistration) throw AccountFailure.rejected;
if (rejectRegistration) {
return {'status': 'REGISTER_AGENT_STATUS_NAME_TAKEN'};
}
listed.add({
'agent_pubkey': fakeAgent,
'agent_id': 'agent',
'agent_name': body['agent_name'],
'status': 'BEEKEEPER_AGENT_STATUS_ACTIVE',
});
// The server committed the identity, but the response never arrived.
if (loseRegistration) throw StateError('Connection lost.');
return {'status': 1, 'agent_pubkey': fakeAgent, 'agent_id': 'agent'};
case '/v3/beekeeper/attest-agent':
return {'status': 'ATTEST_AGENT_STATUS_ACTIVE'};
case '/v3/beekeeper/update-agent':
if (failInstructions) throw StateError('instructions unavailable');
if (body.containsKey('model_id') && !ignoreModelUpdate) {
listed = [
for (final row in listed)
if (row['agent_pubkey'] == body['agent_pubkey'])
{
...row,
'model_id': body['model_id'],
'reasoning_effort': body['reasoning_effort'],
'model_selection_status': 1,
}
else
row,
];
}
return {};
case '/v3/beekeeper/delete-agent':
expect(body, {'agent_id': 'remote-id'});
return {'status': deleteStatus};
default:
throw StateError('Unexpected request: $path');
}
}
}
/// Fakes only relay publication; registry logic stays real.
class RelayFakeController extends RemoteAgentController {
RelayFakeController(FakeRegistry account, {super.onCreated})
: super(
account: account,
keys: AccountIdentityStore(),
relayAuth: HostedRelayAuth(account),
);
bool rejectRemoval = false;
FakeRegistry get registry => account as FakeRegistry;
@override
Future<void> publishPolicy(String relay, Map<String, dynamic> setup) async {
registry.calls.add('publish-policy');
}
@override
Future<void> removePolicy(String relay, String pubkey) async {
registry.calls.add('remove-registration');
if (rejectRemoval) throw StateError('Relay rejected deletion');
}
}
/// A signed agent profile carrying [owner]'s attestation under [conditions].
NostrEvent signedAgentProfile(
nostr.Keys agent,
nostr.Keys owner, {
String conditions = '',
String content = '{}',
}) {
final pubkey = agent.public;
final digest = sha256
.convert(utf8.encode('nostr:agent-auth:$pubkey:$conditions'))
.toString();
final auth = [
'auth',
owner.public,
conditions,
nostr.Schnorr.sign(secretKey: owner.secret, message: digest),
];
return NostrEvent.fromJson(
nostr.Event.from(
kind: 0,
content: content,
secretKey: agent.secret,
createdAt: 100,
tags: [auth],
).toMap(),
);
}