diff --git a/app/lib/main.dart b/app/lib/main.dart index 733fb90..1be10e1 100644 --- a/app/lib/main.dart +++ b/app/lib/main.dart @@ -8,6 +8,8 @@ import 'package:diet_guard_app/services/app_settings_service.dart'; import 'package:diet_guard_app/services/background_tasks.dart'; import 'package:diet_guard_app/services/body_service.dart'; import 'package:diet_guard_app/services/budget_history_service.dart'; +import 'package:diet_guard_app/services/claude_relay_client.dart'; +import 'package:diet_guard_app/services/claude_relay_firebase.dart'; import 'package:diet_guard_app/services/foodbank_service.dart'; import 'package:diet_guard_app/services/frame_stats.dart'; import 'package:diet_guard_app/services/kuchnia_credential_service.dart'; @@ -32,6 +34,8 @@ Future main() async { await KuchniaCredentialService.init(); await BodyService.init(); await KuchniaQueueService.init(); + // The sparkle button's transport; until this line it fails closed. + claudeRelay = RtdbClaudeRelay.firebase(); final notifications = await NotificationService.init(); // Deliberately *not* awaited before the first frame: the browser's // `Notification.requestPermission()` does not complete until the user diff --git a/app/lib/screens/log_meal_claude_mixin.dart b/app/lib/screens/log_meal_claude_mixin.dart index 7403189..9889d9c 100644 --- a/app/lib/screens/log_meal_claude_mixin.dart +++ b/app/lib/screens/log_meal_claude_mixin.dart @@ -22,7 +22,6 @@ import 'package:diet_guard_app/widgets/logged_meal_row.dart'; import 'package:diet_guard_app/widgets/macro_input_row.dart'; import 'package:diet_guard_app/widgets/meal_action_row.dart'; import 'package:material_ui/material_ui.dart'; -import 'package:uuid/uuid.dart'; /// Photo attach and the Claude send, for the log screen's state. mixin LogMealClaudeMixin @@ -50,6 +49,7 @@ mixin LogMealClaudeMixin Uint8List? photo; StreamSubscription? _relaySub; + String? _pendingRid; /// Whether there is something to send (a description or a photo). bool get canSend => @@ -70,12 +70,14 @@ mixin LogMealClaudeMixin void sendToClaude() { if (!canSend) return; final request = ClaudeRelayRequest( - requestId: const Uuid().v4(), + requestId: newRequestId(), slotMinute: targetSlot, + mode: dueMode ? ClaudeRelayMode.due : ClaudeRelayMode.normal, text: claudeDesc.text.trim(), photoJpeg: photo, ); unawaited(_relaySub?.cancel()); + _pendingRid = request.requestId; setState(() => claudeState = ClaudeButtonState.sending); _relaySub = relay.send(request).listen((e) => unawaited(_onEvent(e))); } @@ -86,10 +88,13 @@ mixin LogMealClaudeMixin case ClaudeRelayQueued(): setState(() => claudeState = ClaudeButtonState.queued); case ClaudeRelayLocked(): + _pendingRid = null; setState(() => claudeState = ClaudeButtonState.locked); case ClaudeRelayFailed(): + _pendingRid = null; setState(() => claudeState = ClaudeButtonState.error); case ClaudeRelayLogged(:final entry): + _pendingRid = null; // The worker logged it under the request id; the sync would deliver // the same record, so this only shows it now and never doubles it. final stored = await LogStorageService.instance.addIfAbsent(entry); @@ -106,6 +111,26 @@ mixin LogMealClaudeMixin } } + /// Withdraws a request that is still in flight or queued, because the user + /// just logged the meal here instead. + /// + /// Unclaimed: the node is deleted and the stream dropped. Already claimed + /// (the PC is mid-estimate): the meal will be logged, so the stream stays + /// open and its row shows with an undo rather than the entry turning up + /// unseen after the next sync. That race is accepted, see + /// `docs/DOCS-claude-relay.md`. + Future withdrawClaude() async { + final rid = _pendingRid; + final waiting = + claudeState == ClaudeButtonState.sending || + claudeState == ClaudeButtonState.queued; + if (rid == null || !waiting) return; + if (await relay.cancel(rid)) { + _pendingRid = null; + await _relaySub?.cancel(); + } + } + /// Cancels the event subscription; call from `dispose`. A request still /// queued on the PC reaches this phone through sync instead. void disposeClaude() => unawaited(_relaySub?.cancel()); diff --git a/app/lib/screens/log_meal_screen.dart b/app/lib/screens/log_meal_screen.dart index 3b4cb22..adbeb54 100644 --- a/app/lib/screens/log_meal_screen.dart +++ b/app/lib/screens/log_meal_screen.dart @@ -136,6 +136,7 @@ class _LogMealScreenState extends State return; } LogFeedback.mealLogged(); // on the tap, before the write + unawaited(withdrawClaude()); // else Claude would log it a second time final entry = await LogStorageService.instance.logMeal( desc, nutritionFromControllers(_macros, _source), diff --git a/app/lib/services/claude_relay_client.dart b/app/lib/services/claude_relay_client.dart index 84cb7fd..da16edb 100644 --- a/app/lib/services/claude_relay_client.dart +++ b/app/lib/services/claude_relay_client.dart @@ -1,28 +1,68 @@ -/// The phone's side of the Claude relay: what the check-mark-gold button -/// sends and what comes back. +/// The phone's side of the Claude relay: what the sparkle button sends and +/// what comes back. /// -/// The transport (a request record synced to the PC, a worker that asks Claude -/// and logs the meal, the reply) is not here; the screen only talks to this -/// interface. See `docs/DOCS-claude-relay.md` for the wire. +/// The screen only talks to this interface; `claude_relay_firebase.dart` is the +/// real transport (Firebase RTDB, end-to-end encrypted) and +/// `claude_relay_fake.dart` the test double. The wire is +/// `docs/DOCS-claude-relay.md` plus `tests/fixtures/claude_relay_contract.json`. /// /// A `Stream`, not a `Future`: the PC may be off, so a request can sit /// [ClaudeRelayQueued] for hours before the same stream delivers /// [ClaudeRelayLogged]. Terminal events end the stream; [ClaudeRelayQueued] /// does not. /// -/// **The request id is the future entry id.** The worker logs the meal under -/// `ClaudeRelayRequest.requestId`, so the phone's copy (written from -/// [ClaudeRelayLogged]) and the PC's copy merge to one entry, and undo is a -/// tombstone on that id. +/// **The request id is a ULID** (`rtdb_relay` never serves another key shape) +/// and **the entry id is derived from it**: `uuid5(namespace, rid)`, computed +/// here by [claudeEntryId] exactly as the PC does. So the phone knows the id +/// of the entry before Claude has answered, a logged result is checked against +/// it, and undo is a tombstone on that id. /// /// **Photos are transient input.** `photoJpeg` lives in memory for one send: /// it is never stored on the phone, never put on a `FoodEntry`, and never part -/// of a synced meal record (`repo_invariants_test.dart` enforces it). +/// of a synced meal record (`repo_invariants_photo_test.dart` enforces it). library; +import 'dart:math'; import 'dart:typed_data'; import 'package:diet_guard_app/models/food_entry.dart'; +import 'package:uuid/uuid.dart'; + +/// The UUID namespace the PC derives entry ids in (`entry_id_namespace` in the +/// contract fixture). +const claudeEntryNamespace = '5d9c1a40-6f0e-5c3e-9b57-d1e7a3c0b2f4'; + +/// The id of the entry the PC logs for request [requestId]. +String claudeEntryId(String requestId) => + const Uuid().v5(claudeEntryNamespace, requestId); + +const _crockford = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'; + +/// A fresh ULID: 48 bits of [now] in ms, then 80 random bits, 26 characters of +/// Crockford base32. [random] is injectable for tests. +String newRequestId({DateTime? now, Random? random}) { + final rng = random ?? Random.secure(); + var ms = (now ?? DateTime.now()).millisecondsSinceEpoch; + final out = List.filled(26, '0'); + for (var i = 9; i >= 0; i--) { + out[i] = _crockford[ms % 32]; + ms ~/= 32; + } + for (var i = 10; i < 26; i++) { + out[i] = _crockford[rng.nextInt(32)]; + } + return out.join(); +} + +/// How the PC picks the slot: the oldest due slot, or the nearest to +/// [ClaudeRelayRequest.slotMinute]. +enum ClaudeRelayMode { + /// The phone is in due mode. + due, + + /// Nothing is due. + normal, +} /// One send: the text and/or photo, and the slot the meal belongs to. class ClaudeRelayRequest { @@ -30,17 +70,20 @@ class ClaudeRelayRequest { const ClaudeRelayRequest({ required this.requestId, required this.slotMinute, + this.mode = ClaudeRelayMode.normal, this.text = '', this.photoJpeg, }); - /// A fresh uuid; becomes the logged entry's id. + /// A ULID (see [newRequestId]); the entry id is [claudeEntryId] of it. final String requestId; - /// The slot minute the meal is logged against (the oldest due slot in due - /// mode, else `slotForLog`). + /// The slot minute the phone would log against now (`client_slot_min`). final int slotMinute; + /// Whether the phone is in due mode. + final ClaudeRelayMode mode; + /// What the user typed, trimmed; may be empty when a photo is attached. final String text; @@ -59,7 +102,7 @@ final class ClaudeRelayQueued extends ClaudeRelayEvent { const ClaudeRelayQueued(); } -/// Claude logged the meal (terminal). `entry.id == request.requestId`. +/// Claude logged the meal (terminal). `entry.id == claudeEntryId(rid)`. final class ClaudeRelayLogged extends ClaudeRelayEvent { /// Creates the event for [entry]. const ClaudeRelayLogged(this.entry); @@ -88,6 +131,11 @@ abstract interface class ClaudeRelayClient { /// Sends [request]; the stream carries zero or more [ClaudeRelayQueued] /// then one terminal event, and never throws (failures are events). Stream send(ClaudeRelayRequest request); + + /// Withdraws [requestId] if no worker has claimed it yet; true when it is + /// gone. False means it was already claimed (or the call failed), and the + /// meal will be logged: the stream keeps listening so the row still shows. + Future cancel(String requestId); } /// The stand-in until a transport is wired: every send fails closed. @@ -98,6 +146,9 @@ class UnconfiguredClaudeRelayClient implements ClaudeRelayClient { @override Stream send(ClaudeRelayRequest request) => Stream.value(const ClaudeRelayFailed('relay not configured')); + + @override + Future cancel(String requestId) async => true; } /// The client the screen uses unless it is handed one; `main.dart` assigns the diff --git a/app/lib/services/claude_relay_fake.dart b/app/lib/services/claude_relay_fake.dart index 69b1994..813f496 100644 --- a/app/lib/services/claude_relay_fake.dart +++ b/app/lib/services/claude_relay_fake.dart @@ -16,6 +16,12 @@ class FakeClaudeRelayClient implements ClaudeRelayClient { /// Events replayed on each send before the stream waits for [emit]. final List script = []; + /// Request ids passed to [cancel], oldest first. + final List cancelled = []; + + /// What [cancel] answers: true = withdrawn before any claim. + bool cancelResult = true; + StreamController? _open; @override @@ -34,4 +40,10 @@ class FakeClaudeRelayClient implements ClaudeRelayClient { controller.add(event); if (event is! ClaudeRelayQueued) unawaited(controller.close()); } + + @override + Future cancel(String requestId) async { + cancelled.add(requestId); + return cancelResult; + } } diff --git a/app/lib/services/claude_relay_firebase.dart b/app/lib/services/claude_relay_firebase.dart new file mode 100644 index 0000000..c087bad --- /dev/null +++ b/app/lib/services/claude_relay_firebase.dart @@ -0,0 +1,201 @@ +/// The real [ClaudeRelayClient]: requests and answers through Firebase RTDB, +/// end-to-end encrypted, served by the PC's `claude-worker`. +/// +/// One send: seal the request with the existing E2E key (header +/// `diet-guard-sync/e2e`, the key the log sync already uses), PUT it under +/// `requests//req`, then watch the node. No claim after +/// [claimWindow] means the PC is offline: [ClaudeRelayQueued], and the same +/// stream keeps waiting. The worker's sealed `result` becomes +/// [ClaudeRelayLogged] or [ClaudeRelayFailed], and the phone then deletes the +/// request node as `docs/DOCS-claude-relay.md` asks. +/// +/// **Fail closed, visibly.** A locked key is [ClaudeRelayLocked]; a request +/// that breaks the contract, a transport that keeps failing, a result that +/// does not open or carries an entry id the phone did not derive, and a wait +/// past [maxWait] are all [ClaudeRelayFailed]. Nothing is ever shown as +/// logged unless a valid sealed result says so. +/// +/// Polling, not a stream: the node's child keys (no values, so the photo is +/// never re-read) are listed every second, then every 5 s once the wait is +/// long. The phone is a foreground client here; a queued request that outlives +/// the screen reaches the log through the normal sync instead. +library; + +import 'dart:async'; +import 'dart:developer'; + +import 'package:crdt_sync/crdt_sync.dart'; +import 'package:diet_guard_app/services/claude_relay_client.dart'; +import 'package:diet_guard_app/services/claude_relay_rtdb.dart'; +import 'package:diet_guard_app/services/claude_relay_wire.dart'; +import 'package:diet_guard_app/services/firebase_backend.dart'; +import 'package:diet_guard_app/services/firebase_client.dart'; +import 'package:diet_guard_app/services/sync_device_id.dart'; +import 'package:diet_guard_app/services/sync_e2e.dart'; + +const _fastPoll = Duration(seconds: 1); +const _slowPoll = Duration(seconds: 5); +const _slowAfter = Duration(seconds: 30); +const _maxPollFailures = 3; + +/// [ClaudeRelayClient] over RTDB. +class RtdbClaudeRelay implements ClaudeRelayClient { + /// Creates the client; every dependency is injectable for tests. + RtdbClaudeRelay({ + required this.openNodes, + required this.openCipher, + required this.deviceId, + DateTime Function()? now, + Future Function(Duration)? delay, + this.claimWindow = const Duration(seconds: 3), + this.maxWait = const Duration(minutes: 15), + }) : _now = now ?? DateTime.now, + _delay = delay ?? Future.delayed; + + /// The app's real transport: Firebase session, E2E key from the keystore. + /// + /// Everything resolves at send time, so building it in `main` costs nothing + /// and a device that signs in later just works. + factory RtdbClaudeRelay.firebase() { + FirebaseRestClient? client; + Future session() async => client ??= + await openFirebase() ?? + (throw const RelayTransportError('not signed in to Firebase')); + return RtdbClaudeRelay( + openNodes: () async { + final auth = (await session()).auth; + return RtdbNodes( + databaseUrl: kProject.databaseUrl, + idToken: auth.idToken, + ); + }, + openCipher: () => session().then(openDietGuardCipher), + deviceId: () => currentSyncDeviceId, + ); + } + + /// Opens the node access, throwing [RelayTransportError] when unavailable. + final Future Function() openNodes; + + /// Opens the E2E cipher, throwing [SyncLockedException] when locked. + final Future Function() openCipher; + + /// This phone's sync device id, sent as `dev`. + final String Function() deviceId; + + /// How long an unclaimed request waits before it reads as queued. + final Duration claimWindow; + + /// How long one send waits for an answer before it fails. + final Duration maxWait; + + final DateTime Function() _now; + final Future Function(Duration) _delay; + + @override + Stream send(ClaudeRelayRequest request) async* { + final problem = relayBodyProblem(relayBody(request)); + if (problem != null) { + yield ClaudeRelayFailed('bad request: $problem'); + return; + } + final RelayNodes nodes; + final E2eCipher cipher; + try { + cipher = await openCipher(); + nodes = await openNodes(); + final unit = await sealRequest( + cipher, + request, + device: deviceId(), + nowMs: _now().millisecondsSinceEpoch, + ); + await nodes.put('${requestNode(request.requestId)}/req', unit); + } on SyncLockedException { + yield const ClaudeRelayLocked(); + return; + } on Object catch (error, stackTrace) { + log( + 'claude relay send failed', + level: 1000, + error: error, + stackTrace: stackTrace, + ); + yield const ClaudeRelayFailed('could not send'); + return; + } + yield* _await(nodes, cipher, request.requestId); + } + + Stream _await( + RelayNodes nodes, + E2eCipher cipher, + String rid, + ) async* { + final node = requestNode(rid); + final started = _now(); + var queued = false; + var failures = 0; + while (true) { + final waited = _now().difference(started); + if (waited > maxWait) { + yield const ClaudeRelayFailed('no answer in time'); + return; + } + try { + final keys = await nodes.keys(node); + failures = 0; + if (keys.contains('result')) { + final result = await openResult( + cipher, + rid, + await nodes.get('$node/result'), + ); + await _tidy(nodes, node); + yield result; + return; + } + if (keys.isEmpty) { + yield const ClaudeRelayFailed('request vanished'); + return; + } + if (!queued && !keys.contains('claim') && waited >= claimWindow) { + queued = true; + yield const ClaudeRelayQueued(); + } + } on Object catch (error, stackTrace) { + log( + 'claude relay poll failed', + level: 900, + error: error, + stackTrace: stackTrace, + ); + if (++failures >= _maxPollFailures) { + yield const ClaudeRelayFailed('connection lost'); + return; + } + } + await _delay(waited < _slowAfter ? _fastPoll : _slowPoll); + } + } + + /// Deletes the answered request node. Best effort: the worker also sweeps + /// answered nodes after 24 h, so a failure costs nothing but a few bytes. + Future _tidy(RelayNodes nodes, String node) async { + try { + await nodes.delete(node); + } on Object catch (error) { + log('claude relay cleanup failed', level: 900, error: error); + } + } + + @override + Future cancel(String requestId) async { + try { + return await (await openNodes()).deleteUnclaimed(requestNode(requestId)); + } on Object catch (error) { + log('claude relay cancel failed', level: 900, error: error); + return false; + } + } +} diff --git a/app/lib/services/claude_relay_rtdb.dart b/app/lib/services/claude_relay_rtdb.dart new file mode 100644 index 0000000..8b4706f --- /dev/null +++ b/app/lib/services/claude_relay_rtdb.dart @@ -0,0 +1,150 @@ +/// Raw Realtime Database nodes for the relay, over REST. +/// +/// The sync client (`FirebaseRestClient`) stores text blobs as string leaves; +/// the relay's units are JSON objects with a server-time sibling, so it needs +/// the node itself. Plain HTTPS like the sync client, so it works on Android +/// and in the browser-hosted desktop app alike. +library; + +import 'dart:convert'; + +import 'package:http/http.dart' as http; + +/// A relay call failed on the network or was refused. The message never holds +/// a URL: its query carries the ID token. +class RelayTransportError implements Exception { + /// Creates the error. + const RelayTransportError(this.message); + + /// What went wrong, safe to log. + final String message; + + @override + String toString() => 'RelayTransportError: $message'; +} + +/// The four node operations the relay needs. +abstract interface class RelayNodes { + /// The JSON value at [path], or null when absent. + Future get(String path); + + /// The child keys of [path] (no values), empty when absent. + Future> keys(String path); + + /// Replaces the node at [path] with [value]. + Future put(String path, Object value); + + /// Deletes the node at [path]. + Future delete(String path); + + /// Deletes [path] only while it holds neither a `claim` nor a `result`, + /// atomically: the delete carries the node's ETag, so a worker claiming it + /// in between turns the delete into a refusal. True when it is gone. + Future deleteUnclaimed(String path); +} + +/// [RelayNodes] over the Realtime Database REST API. +class RtdbNodes implements RelayNodes { + /// Creates the client; [idToken] mints the token each request carries. + RtdbNodes({ + required String databaseUrl, + required this.idToken, + http.Client? client, + String namespace = '', + }) : _base = databaseUrl.endsWith('/') + ? databaseUrl.substring(0, databaseUrl.length - 1) + : databaseUrl, + _prefix = namespace.isEmpty ? '' : '$namespace/', + _http = client ?? http.Client(); + + /// Supplies a fresh Firebase ID token. + final Future Function() idToken; + + final String _base; + final String _prefix; + final http.Client _http; + + Future _uri(String path, [Map query = const {}]) async => + Uri.parse( + '$_base/$_prefix$path.json', + ).replace(queryParameters: {'auth': await idToken(), ...query}); + + Future _send( + String what, + Future Function(Uri uri) call, + String path, [ + Map query = const {}, + ]) async { + try { + return await call(await _uri(path, query)); + } on http.ClientException catch (error) { + throw RelayTransportError('network error $what: ${error.message}'); + } + } + + Never _refuse(String what, http.Response res) => + throw RelayTransportError('$what refused: HTTP ${res.statusCode}'); + + bool _ok(http.Response res) => res.statusCode >= 200 && res.statusCode < 300; + + @override + Future get(String path) async { + final res = await _send('reading', _http.get, path); + if (!_ok(res)) _refuse('reading', res); + return jsonDecode(res.body); + } + + @override + Future> keys(String path) async { + final res = await _send('listing', _http.get, path, {'shallow': 'true'}); + if (!_ok(res)) _refuse('listing', res); + final decoded = jsonDecode(res.body); + return decoded is Map ? decoded.keys.cast().toSet() : {}; + } + + @override + Future put(String path, Object value) async { + final res = await _send( + 'writing', + (uri) => _http.put(uri, body: jsonEncode(value)), + path, + ); + if (!_ok(res)) _refuse('writing', res); + } + + @override + Future delete(String path) async { + final res = await _send('deleting', _http.delete, path); + if (!_ok(res)) _refuse('deleting', res); + } + + @override + Future deleteUnclaimed(String path) async { + // `X-Firebase-ETag` makes the read return the node's ETag; a claim or a + // result written afterwards changes it, and `if-match` then answers 412. + // A full read, not a shallow one: the ETag of a shallow answer is not + // guaranteed to cover the children, and this path is rare. + final read = await _send( + 'reading', + (uri) => _http.get(uri, headers: {'X-Firebase-ETag': 'true'}), + path, + ); + if (!_ok(read)) _refuse('reading', read); + final node = jsonDecode(read.body); + if (node == null) return true; + if (node is Map && + (node.containsKey('claim') || node.containsKey('result'))) { + return false; + } + final etag = read.headers['etag']; + if (etag == null) return false; + final res = await _send( + 'deleting', + (uri) => _http.delete(uri, headers: {'if-match': etag}), + path, + ); + if (res.statusCode == 412) return false; + if (!_ok(res)) _refuse('deleting', res); + return true; + } +} diff --git a/app/lib/services/claude_relay_wire.dart b/app/lib/services/claude_relay_wire.dart new file mode 100644 index 0000000..64effec --- /dev/null +++ b/app/lib/services/claude_relay_wire.dart @@ -0,0 +1,144 @@ +/// The relay's wire format: sealing a request, opening a result. +/// +/// Mirrors `docs/DOCS-claude-relay.md` sections 1 to 3 and is gated by +/// `tests/fixtures/claude_relay_contract.json`. A unit is +/// `{"_e2e": , }`; the blob is crdt_sync's [E2eCipher] +/// over compact JSON with the unit's full path as AAD, so a blob copied to +/// another path does not open. Both the request (photo included) and the +/// result are sealed: no food text or image is ever in clear. +library; + +import 'dart:convert'; + +import 'package:crdt_sync/crdt_sync.dart'; +import 'package:diet_guard_app/models/food_entry.dart'; +import 'package:diet_guard_app/services/claude_relay_client.dart'; + +/// The relay's root `R`; its header is the existing `diet-guard-sync/e2e`. +const relayRoot = 'diet-guard-sync/claude-e2e'; + +/// Largest base64 photo the worker accepts, in characters. +const relayPhotoB64Max = 600000; + +/// Longest description the worker accepts, in characters after trimming. +const relayTextMax = 2000; + +/// The node of request [rid]. +String requestNode(String rid) => '$relayRoot/requests/$rid'; + +/// Returns why [body] breaks the contract, or null when it is valid. +/// +/// The same rules the worker enforces (`bad_request`), checked here first so a +/// request that can only fail never leaves the phone. +String? relayBodyProblem(Map body) { + final text = body['text']; + final photo = body['photo_jpeg_b64']; + if (text == null && photo == null) return 'nothing to estimate'; + if (text != null) { + if (text is! String) return 'text is not a string'; + final length = text.trim().runes.length; + if (length < 1 || length > relayTextMax) return 'text length'; + } + if (photo != null) { + if (photo is! String || photo.length > relayPhotoB64Max) { + return 'photo size'; + } + try { + final bytes = base64.decode(photo); + if (bytes.length < 2 || bytes[0] != 0xFF || bytes[1] != 0xD8) { + return 'photo is not a jpeg'; + } + } on FormatException { + return 'photo is not base64'; + } + } + final slot = body['client_slot_min']; + if (slot is! int || slot < 0 || slot > 1439) return 'slot'; + if (body['mode'] != 'due' && body['mode'] != 'normal') return 'mode'; + return null; +} + +/// The request's `body` object. +Map relayBody(ClaudeRelayRequest request) => { + if (request.text.trim().isNotEmpty) 'text': request.text.trim(), + if (request.photoJpeg != null) + 'photo_jpeg_b64': base64.encode(request.photoJpeg!), + 'client_slot_min': request.slotMinute, + 'mode': request.mode.name, +}; + +/// The sealed `req` unit for [request], ready to PUT. +/// +/// `created` is the server's clock, not the phone's: it drives the worker's +/// 24 h expiry, and a phone clock can be wrong. +Future> sealRequest( + E2eCipher cipher, + ClaudeRelayRequest request, { + required String device, + required int nowMs, +}) async { + final plain = { + 'kind': 'meal', + 'dev': device, + 'sent_at': nowMs, + 'body': relayBody(request), + }; + return { + '_e2e': await cipher.seal( + jsonEncode(plain), + path: '${requestNode(request.requestId)}/req', + ), + 'created': {'.sv': 'timestamp'}, + }; +} + +/// Opens the `result` unit of [rid] into the event the screen shows. +/// +/// Fail closed: anything that is not exactly a logged meal for this request, +/// with the entry id the phone derived itself, is a [ClaudeRelayFailed]. +Future openResult( + E2eCipher cipher, + String rid, + Object? node, +) async { + try { + if (node is! Map || node['_e2e'] is! String) { + return const ClaudeRelayFailed('result is not a sealed unit'); + } + final plain = + jsonDecode( + await cipher.open( + node['_e2e'] as String, + path: '${requestNode(rid)}/result', + ), + ) + as Map; + if (plain['id'] != rid) return const ClaudeRelayFailed('result id'); + if (plain['ok'] != true || plain['status'] != 'logged') { + return ClaudeRelayFailed('${plain['error_code'] ?? 'error'}'); + } + if (plain['entry_id'] != claudeEntryId(rid)) { + return const ClaudeRelayFailed('entry id mismatch'); + } + return ClaudeRelayLogged( + FoodEntry( + id: plain['entry_id'] as String, + time: plain['time'] as String, + desc: plain['desc'] as String, + grams: (plain['grams'] as num).toDouble(), + kcal: (plain['kcal'] as num).toDouble(), + proteinG: (plain['protein_g'] as num).toDouble(), + carbsG: (plain['carbs_g'] as num).toDouble(), + fatG: (plain['fat_g'] as num).toDouble(), + source: 'claude', + slotMinute: plain['slot_min'] as int?, + ), + ); + } on E2eDecryptError { + return const ClaudeRelayFailed('result did not open'); + } on Object { + // A wrong type or a missing field in a result is a bad answer, not a + // crash; the meal is not shown as logged. + return const ClaudeRelayFailed('result is malformed'); + } +} diff --git a/app/lib/services/sync_e2e.dart b/app/lib/services/sync_e2e.dart index f64447a..be38bd1 100644 --- a/app/lib/services/sync_e2e.dart +++ b/app/lib/services/sync_e2e.dart @@ -65,6 +65,22 @@ Future openDietGuardStore(RemoteStore backend) async { ); } +/// The cipher of the diet_guard E2E key, for units outside the log sync (the +/// Claude relay seals its requests with it). +/// +/// Throws [SyncLockedException] when there is no usable key, same as +/// [openDietGuardStore]. The relay lives under `diet-guard-sync/claude-e2e`, +/// whose header path is the existing `diet-guard-sync/e2e`: one passphrase, +/// one salt, one key. +Future openDietGuardCipher(RemoteStore backend) async { + final state = await _open(backend, legacyDevicesDir); + syncLocked.value = state is! E2eReady; + if (state is E2eReady) return state.store.key.cipher(acceptPlaintext: false); + throw SyncLockedException( + state is E2eLocked ? state.reason : E2eLockReason.badHeader, + ); +} + /// The encrypted wake-alarm store over [backend], or null when locked or /// unreachable. /// diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 32f62e8..9167d30 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -2,7 +2,7 @@ name: diet_guard_app description: "Companion phone app for diet_guard: log meals on the go." publish_to: 'none' -version: 1.0.170+1 +version: 1.0.171+1 environment: sdk: ^3.12.2 diff --git a/app/test/screens/log_meal_claude_test.dart b/app/test/screens/log_meal_claude_test.dart index 5a765c3..95c4149 100644 --- a/app/test/screens/log_meal_claude_test.dart +++ b/app/test/screens/log_meal_claude_test.dart @@ -118,8 +118,6 @@ void main() { await tester.tap(byIconLabel('Remove photo')); await settle(tester); expect(sparkleEnabled(tester), isFalse); - - }); }); @@ -158,7 +156,7 @@ void main() { await settle(tester); expect(byIconLabel('Waiting for the PC'), findsOneWidget); - final id = relay.sent.single.requestId; + final id = claudeEntryId(relay.sent.single.requestId); relay.emit(ClaudeRelayLogged(_claudeEntry(id))); await settle(tester); diff --git a/app/test/screens/log_meal_claude_withdraw_test.dart b/app/test/screens/log_meal_claude_withdraw_test.dart new file mode 100644 index 0000000..96c4f0a --- /dev/null +++ b/app/test/screens/log_meal_claude_withdraw_test.dart @@ -0,0 +1,97 @@ +/// A local log while a Claude request waits withdraws it, and the request id +/// the screen makes is one the relay serves. +library; + +import 'package:diet_guard_app/models/food_entry.dart'; +import 'package:diet_guard_app/screens/log_meal_screen.dart'; +import 'package:diet_guard_app/services/claude_relay_client.dart'; +import 'package:diet_guard_app/services/claude_relay_fake.dart'; +import 'package:diet_guard_app/services/log_storage_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; + +import '../label_finders.dart'; +import 'log_meal_test_support.dart'; + +FoodEntry _claudeEntry(String id) => FoodEntry( + id: id, + time: DateTime.now().toIso8601String().substring(0, 19), + desc: 'kurczak z ryzem', + grams: 300, + kcal: 540, + proteinG: 42, + carbsG: 61, + fatG: 9, + source: 'claude', + slotMinute: 480, +); + +void main() { + late Future Function() restore; + late FakeClaudeRelayClient relay; + + setUp(() async { + restore = await isolateLogScreenState(); + relay = FakeClaudeRelayClient(); + }); + tearDown(() => restore()); + + Future open(WidgetTester tester) async { + await tester.pumpWidget(MaterialApp(home: LogMealScreen(relay: relay))); + await settle(tester); + } + + testWidgets('the request id is a ULID and the mode follows due mode', ( + tester, + ) async { + pinLogMealClock(13); + await tester.runAsync(() async { + await open(tester); + await tester.enterText(find.byType(TextField).at(0), 'kurczak'); + await settle(tester); + await tester.tap(controlByLabel('Ask Claude')); + await tester.pump(); + final sent = relay.sent.single; + expect( + RegExp(r'^[0-9A-HJKMNP-TV-Z]{26}$').hasMatch(sent.requestId), + isTrue, + ); + expect(sent.mode, ClaudeRelayMode.due); + }); + }); + + for (final claimed in [false, true]) { + testWidgets('a local log while queued withdraws the request ' + '(${claimed ? 'already claimed' : 'unclaimed'})', (tester) async { + pinLogMealClock(13); + relay.cancelResult = !claimed; + await tester.runAsync(() async { + await open(tester); + await tester.enterText(find.byType(TextField).at(0), 'kurczak'); + await settle(tester); + await tester.tap(controlByLabel('Ask Claude')); + await tester.pump(); + relay.emit(const ClaudeRelayQueued()); + await settle(tester); + + await tester.tap(controlByLabel('Log meal')); + await settle(tester); + + expect(relay.cancelled, [relay.sent.single.requestId]); + expect(byIconLabel('Ask Claude'), findsOneWidget); + expect(await LogStorageService.instance.todayEntries(), hasLength(1)); + + // Claimed: the PC still logs it, so the stream stays open and the + // duplicate shows with an undo instead of arriving unseen. + relay.emit( + ClaudeRelayLogged( + _claudeEntry(claudeEntryId(relay.sent.single.requestId)), + ), + ); + await settle(tester); + final live = await LogStorageService.instance.todayEntries(); + expect(live, hasLength(claimed ? 2 : 1)); + }); + }); + } +} diff --git a/app/test/screens/log_meal_geometry_test.dart b/app/test/screens/log_meal_geometry_test.dart index dcf19d2..27dbcae 100644 --- a/app/test/screens/log_meal_geometry_test.dart +++ b/app/test/screens/log_meal_geometry_test.dart @@ -116,7 +116,11 @@ void main() { await tester.tap(controlByLabel('Claude failed')); await tester.pump(); - relay.emit(ClaudeRelayLogged(claudeEntry(relay.sent.last.requestId))); + relay.emit( + ClaudeRelayLogged( + claudeEntry(claudeEntryId(relay.sent.last.requestId)), + ), + ); await settle(tester); expect(find.byIcon(Icons.undo), findsOneWidget); // Still due (12:00 is open): the screen stays in due mode. diff --git a/app/test/services/claude_relay_client_test.dart b/app/test/services/claude_relay_client_test.dart index 56607ac..874b66e 100644 --- a/app/test/services/claude_relay_client_test.dart +++ b/app/test/services/claude_relay_client_test.dart @@ -9,7 +9,7 @@ import 'package:diet_guard_app/services/claude_relay_fake.dart'; import 'package:flutter_test/flutter_test.dart'; const _request = ClaudeRelayRequest( - requestId: 'r1', + requestId: '01JD5Z8K3M7Q2W9XH4TBN6VR0E', slotMinute: 480, text: 'x', ); @@ -27,8 +27,8 @@ void main() { await Future.delayed(Duration.zero); expect(done.isCompleted, isFalse); - const entry = FoodEntry( - id: 'r1', + final entry = FoodEntry( + id: claudeEntryId(_request.requestId), time: 't', desc: 'x', grams: 1, @@ -38,13 +38,16 @@ void main() { fatG: 1, source: 'claude', ); - relay.emit(const ClaudeRelayLogged(entry)); + relay.emit(ClaudeRelayLogged(entry)); await done.future; expect(events.map((e) => e.runtimeType), [ ClaudeRelayQueued, ClaudeRelayLogged, ]); - expect((events.last as ClaudeRelayLogged).entry.id, _request.requestId); + expect( + (events.last as ClaudeRelayLogged).entry.id, + claudeEntryId(_request.requestId), + ); }, ); diff --git a/app/test/services/claude_relay_contract_test.dart b/app/test/services/claude_relay_contract_test.dart new file mode 100644 index 0000000..561fab6 --- /dev/null +++ b/app/test/services/claude_relay_contract_test.dart @@ -0,0 +1,204 @@ +/// The relay wire against `tests/fixtures/claude_relay_contract.json`, the +/// same file the Python worker's tests read. Seal and open go through the +/// fixture's key, so a drift on either side fails here. +library; + +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:crdt_sync/crdt_sync.dart'; +import 'package:diet_guard_app/services/claude_relay_client.dart'; +import 'package:diet_guard_app/services/claude_relay_wire.dart'; +import 'package:diet_guard_app/services/sync_e2e.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Map _fixture() { + var dir = Directory.current; + while (!File( + '${dir.path}/tests/fixtures/claude_relay_contract.json', + ).existsSync()) { + dir = dir.parent; + } + return jsonDecode( + File( + '${dir.path}/tests/fixtures/claude_relay_contract.json', + ).readAsStringSync(), + ) + as Map; +} + +List _hex(String s) => [ + for (var i = 0; i < s.length; i += 2) + int.parse(s.substring(i, i + 2), radix: 16), +]; + +void main() { + final fx = _fixture(); + final rid = fx['rid'] as String; + late E2eCipher cipher; + + setUp(() async { + // The fixture key is the cipher key itself, as `E2eKey.cipher()` hands + // it out on both devices (no further derivation). + cipher = E2eCipher(_hex(fx['key_hex'] as String), acceptPlaintext: false); + }); + + test('root, header and entry id agree with the contract', () { + expect(relayRoot, fx['root']); + // The relay reuses the diet-guard header: same passphrase, same salt. + expect(E2eLayout.of('diet-guard-sync/claude').e2ePath, fx['header_path']); + expect(E2eLayout.of(legacyDevicesDir).e2ePath, fx['header_path']); + expect(claudeEntryNamespace, fx['entry_id_namespace']); + expect(claudeEntryId(rid), fx['entry_id']); + }); + + test('a ULID the phone makes is one the relay serves', () { + final id = newRequestId(); + expect(RegExp(r'^[0-9A-HJKMNP-TV-Z]{26}$').hasMatch(id), isTrue); + expect(newRequestId(), isNot(id)); + }); + + test('the fixture request opens to its plaintext at its path', () async { + final request = fx['request'] as Map; + final node = request['node'] as Map; + final plain = await cipher.open( + node['_e2e'] as String, + path: '$relayRoot/${request['path']}', + ); + expect(jsonDecode(plain), request['plain']); + }); + + test('our sealed request opens, at its own path only', () async { + final plain = + (fx['request'] as Map)['plain'] + as Map; + final body = plain['body'] as Map; + final unit = await sealRequest( + cipher, + ClaudeRelayRequest( + requestId: rid, + slotMinute: body['client_slot_min'] as int, + mode: ClaudeRelayMode.due, + text: body['text'] as String, + photoJpeg: Uint8List.fromList( + base64.decode(body['photo_jpeg_b64'] as String), + ), + ), + device: plain['dev'] as String, + nowMs: plain['sent_at'] as int, + ); + expect(unit.keys.toSet(), {'_e2e', 'created'}); + expect(unit['created'], {'.sv': 'timestamp'}); + final opened = jsonDecode( + await cipher.open( + unit['_e2e']! as String, + path: '${requestNode(rid)}/req', + ), + ); + expect(opened, plain); + await expectLater( + cipher.open(unit['_e2e']! as String, path: '${requestNode(rid)}/result'), + throwsA(isA()), + ); + }); + + test('the fixture logged result becomes a Claude entry', () async { + final logged = + (fx['results'] as Map)['logged'] + as Map; + final event = await openResult(cipher, rid, logged['node']); + final entry = (event as ClaudeRelayLogged).entry; + final plain = logged['plain'] as Map; + expect(entry.id, fx['entry_id']); + expect(entry.desc, plain['desc']); + expect(entry.kcal, plain['kcal']); + expect(entry.proteinG, plain['protein_g']); + expect(entry.slotMinute, plain['slot_min']); + expect(entry.time, plain['time']); + expect(entry.source, 'claude'); + }); + + for (final name in ['error', 'expired']) { + test('the fixture $name result fails with its code', () async { + final res = + (fx['results'] as Map)[name] as Map; + final event = await openResult(cipher, rid, res['node']); + expect( + (event as ClaudeRelayFailed).reason, + (res['plain'] as Map)['error_code'], + ); + }); + } + + test('a result for another request does not open', () async { + final logged = + (fx['results'] as Map)['logged'] + as Map; + final event = await openResult( + cipher, + '01JD5Z8K3M7Q2W9XH4TBN6VR0F', + logged['node'], + ); + expect(event, isA()); + }); + + test('a wrong key, a plain node and junk all fail closed', () async { + final other = (await E2eKey.fromBytes( + List.filled(32, 7), + )).cipher(acceptPlaintext: false); + final logged = + (fx['results'] as Map)['logged'] + as Map; + expect( + await openResult(other, rid, logged['node']), + isA(), + ); + expect(await openResult(cipher, rid, null), isA()); + expect( + await openResult(cipher, rid, {'ok': true}), + isA(), + ); + }); + + test('an entry id the phone did not derive is refused', () async { + final sealed = await cipher.seal( + jsonEncode({ + 'ok': true, + 'status': 'logged', + 'id': rid, + 'entry_id': 'not-the-derived-id', + 'desc': 'x', + 'grams': 1, + 'kcal': 1, + 'protein_g': 1, + 'carbs_g': 1, + 'fat_g': 1, + 'slot_min': 480, + 'time': '2026-11-17T12:00:00+01:00', + }), + path: '${requestNode(rid)}/result', + ); + final event = await openResult(cipher, rid, {'_e2e': sealed, 'at': 1}); + expect(event, isA()); + }); + + group('body cases', () { + for (final c in (fx['body_cases'] as List).cast>()) { + test('${c['name']} is ${c['valid'] == true ? 'valid' : 'refused'}', () { + final problem = relayBodyProblem( + (c['body'] as Map).cast(), + ); + expect(problem == null, c['valid']); + }); + } + + test('our own body for a text-only request is valid', () { + final body = relayBody( + const ClaudeRelayRequest(requestId: 'x', slotMinute: 720, text: ' a '), + ); + expect(body, {'text': 'a', 'client_slot_min': 720, 'mode': 'normal'}); + expect(relayBodyProblem(body), isNull); + }); + }); +} diff --git a/app/test/services/claude_relay_firebase_fail_test.dart b/app/test/services/claude_relay_firebase_fail_test.dart new file mode 100644 index 0000000..781de61 --- /dev/null +++ b/app/test/services/claude_relay_firebase_fail_test.dart @@ -0,0 +1,122 @@ +/// The real relay client's failure paths and `cancel`, on virtual time. +library; + +import 'dart:convert'; + +import 'package:crdt_sync/crdt_sync.dart'; +import 'package:diet_guard_app/services/claude_relay_client.dart'; +import 'package:diet_guard_app/services/claude_relay_firebase.dart'; +import 'package:diet_guard_app/services/claude_relay_rtdb.dart'; +import 'package:diet_guard_app/services/claude_relay_wire.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'claude_relay_test_support.dart'; + +const _rid = '01JD5Z8K3M7Q2W9XH4TBN6VR0E'; +final _node = requestNode(_rid); + +void main() { + late E2eCipher cipher; + late MemoryNodes nodes; + late DateTime clock; + late void Function() tick; + late RtdbClaudeRelay relay; + + const request = ClaudeRelayRequest( + requestId: _rid, + slotMinute: 720, + text: 'kurczak', + ); + + Future workerLogs() async { + nodes.data['$_node/claim'] = {'by': 'pc-worker'}; + nodes.data['$_node/result'] = { + '_e2e': await cipher.seal( + jsonEncode({ + 'ok': true, + 'status': 'logged', + 'id': _rid, + 'entry_id': claudeEntryId(_rid), + 'desc': 'kurczak', + 'grams': 1, + 'kcal': 1, + 'protein_g': 1, + 'carbs_g': 1, + 'fat_g': 1, + 'slot_min': 480, + 'time': '2026-11-17T12:03:41+01:00', + }), + path: '$_node/result', + ), + 'at': 1, + }; + } + + setUp(() { + cipher = E2eCipher(List.filled(32, 3), acceptPlaintext: false); + nodes = MemoryNodes(); + clock = DateTime(2026, 11, 17, 12); + tick = () {}; + relay = RtdbClaudeRelay( + openNodes: () async => nodes, + openCipher: () async => cipher, + deviceId: () => 'phone-1', + now: () => clock, + delay: (d) async { + clock = clock.add(d); + tick(); + }, + ); + }); + + test('one bad poll is tolerated, three in a row are not', () async { + nodes.failReads = 1; + tick = workerLogs; + expect( + (await relay.send(request).toList()).single, + isA(), + ); + + nodes.data.clear(); + nodes.failReads = 3; + expect( + (await relay.send(request).toList()).single, + isA(), + ); + }); + + test('no answer within the wait fails closed, after queued', () async { + final events = await relay.send(request).toList(); + expect(events.first, isA()); + expect((events.last as ClaudeRelayFailed).reason, 'no answer in time'); + }); + + test('a node that disappears fails closed', () async { + tick = nodes.data.clear; + final events = await relay.send(request).toList(); + expect((events.last as ClaudeRelayFailed).reason, 'request vanished'); + }); + + test( + 'cancel removes an unclaimed request and refuses a claimed one', + () async { + await nodes.put('$_node/req', {'_e2e': 'x'}); + expect(await relay.cancel(_rid), isTrue); + expect(nodes.data, isEmpty); + + nodes.data['$_node/req'] = {'_e2e': 'x'}; + nodes.data['$_node/claim'] = {'by': 'pc-worker'}; + expect(await relay.cancel(_rid), isFalse); + expect(nodes.data, isNotEmpty); + }, + ); + + test('cancel is false when the transport is down', () async { + final down = RtdbClaudeRelay( + openNodes: () async => throw const RelayTransportError('offline'), + openCipher: () async => cipher, + deviceId: () => 'p', + ); + expect(await down.cancel(_rid), isFalse); + }); +} diff --git a/app/test/services/claude_relay_firebase_test.dart b/app/test/services/claude_relay_firebase_test.dart new file mode 100644 index 0000000..2f0b7f0 --- /dev/null +++ b/app/test/services/claude_relay_firebase_test.dart @@ -0,0 +1,182 @@ +/// The real relay client against an in-memory node store and a scripted +/// worker, on virtual time (every delay just advances the clock). +library; + +import 'dart:convert'; + +import 'package:crdt_sync/crdt_sync.dart'; +import 'package:diet_guard_app/services/claude_relay_client.dart'; +import 'package:diet_guard_app/services/claude_relay_firebase.dart'; +import 'package:diet_guard_app/services/claude_relay_rtdb.dart'; +import 'package:diet_guard_app/services/claude_relay_wire.dart'; +import 'package:diet_guard_app/services/sync_e2e.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'claude_relay_test_support.dart'; + +const _rid = '01JD5Z8K3M7Q2W9XH4TBN6VR0E'; +final _node = requestNode(_rid); + +void main() { + late E2eCipher cipher; + late MemoryNodes nodes; + late DateTime clock; + late void Function(Duration waited) tick; + late bool locked; + late RtdbClaudeRelay relay; + + const request = ClaudeRelayRequest( + requestId: _rid, + slotMinute: 720, + mode: ClaudeRelayMode.due, + text: 'kurczak z ryzem', + ); + + Future> sealedResult(Map plain) async => + { + '_e2e': await cipher.seal(jsonEncode(plain), path: '$_node/result'), + 'at': 1, + }; + + Future workerLogs() async { + nodes.data['$_node/claim'] = {'by': 'pc-worker'}; + nodes.data['$_node/result'] = await sealedResult({ + 'ok': true, + 'kind': 'meal', + 'status': 'logged', + 'id': _rid, + 'entry_id': claudeEntryId(_rid), + 'desc': 'kurczak z ryzem', + 'grams': 300, + 'kcal': 540, + 'protein_g': 42, + 'carbs_g': 61, + 'fat_g': 9, + 'slot_min': 480, + 'time': '2026-11-17T12:03:41+01:00', + }); + } + + setUp(() { + cipher = E2eCipher(List.filled(32, 3), acceptPlaintext: false); + nodes = MemoryNodes(); + clock = DateTime(2026, 11, 17, 12); + locked = false; + tick = (_) {}; + relay = RtdbClaudeRelay( + openNodes: () async => nodes, + openCipher: () async { + if (locked) + throw const SyncLockedException(E2eLockReason.needsPassphrase); + return cipher; + }, + deviceId: () => 'phone-1', + now: () => clock, + delay: (d) async { + clock = clock.add(d); + tick(d); + }, + ); + }); + + Future> run([ClaudeRelayRequest r = request]) => + relay.send(r).toList(); + + test('the request is sealed at its own path with server time', () async { + tick = (_) => workerLogs(); + await run(); + // Answered and tidied: the node is gone, but the put happened as sealed. + expect(nodes.deleted, [_node]); + }); + + test('a sealed request opens to the contract body', () async { + Map? unit; + tick = (_) { + unit ??= nodes.data['$_node/req']! as Map; + workerLogs(); + }; + await run(); + expect(unit!.keys.toSet(), {'_e2e', 'created'}); + final plain = + jsonDecode( + await cipher.open(unit!['_e2e']! as String, path: '$_node/req'), + ) + as Map; + expect(plain['kind'], 'meal'); + expect(plain['dev'], 'phone-1'); + expect(plain['sent_at'], DateTime(2026, 11, 17, 12).millisecondsSinceEpoch); + expect(plain['body'], { + 'text': 'kurczak z ryzem', + 'client_slot_min': 720, + 'mode': 'due', + }); + }); + + test('claimed quickly: no queued state, then the logged entry', () async { + tick = (_) => workerLogs(); + final events = await run(); + expect(events.map((e) => e.runtimeType), [ClaudeRelayLogged]); + final entry = (events.single as ClaudeRelayLogged).entry; + expect(entry.id, claudeEntryId(_rid)); + expect(entry.kcal, 540); + }); + + test( + 'no claim within 3 s reads as queued, once, then still delivers', + () async { + var polls = 0; + tick = (_) { + if (++polls == 8) workerLogs(); + }; + final events = await run(); + expect(events.map((e) => e.runtimeType), [ + ClaudeRelayQueued, + ClaudeRelayLogged, + ]); + }, + ); + + test('a claim without a result is not queued', () async { + var polls = 0; + tick = (_) { + nodes.data['$_node/claim'] = {'by': 'pc-worker'}; + if (++polls == 8) workerLogs(); + }; + final events = await run(); + expect(events.map((e) => e.runtimeType), [ClaudeRelayLogged]); + }); + + test('locked sync sends nothing', () async { + locked = true; + final events = await run(); + expect(events.single, isA()); + expect(nodes.data, isEmpty); + }); + + test('an error result becomes its code', () async { + tick = (_) async { + nodes.data['$_node/result'] = await sealedResult({ + 'ok': false, + 'status': 'error', + 'id': _rid, + 'error_code': 'estimate_timeout', + }); + }; + final events = await run(); + expect((events.single as ClaudeRelayFailed).reason, 'estimate_timeout'); + expect(nodes.deleted, [_node]); + }); + + test('a request that breaks the contract never leaves the phone', () async { + final events = await run( + const ClaudeRelayRequest(requestId: _rid, slotMinute: 5000, text: 'x'), + ); + expect(events.single, isA()); + expect(nodes.data, isEmpty); + }); + + test('a failed put is a visible failure', () async { + nodes.failPut = true; + expect((await run()).single, isA()); + }); +} diff --git a/app/test/services/claude_relay_rtdb_test.dart b/app/test/services/claude_relay_rtdb_test.dart new file mode 100644 index 0000000..1d59e2f --- /dev/null +++ b/app/test/services/claude_relay_rtdb_test.dart @@ -0,0 +1,126 @@ +/// The relay's REST node access against a recording mock server. +library; + +import 'dart:convert'; + +import 'package:diet_guard_app/services/claude_relay_rtdb.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; + +void main() { + late List seen; + late http.Response Function(http.Request) answer; + late RtdbNodes nodes; + + setUp(() { + seen = []; + answer = (_) => http.Response('null', 200); + nodes = RtdbNodes( + databaseUrl: 'https://db.example/', + idToken: () async => 'TOKEN', + client: MockClient((request) async { + seen.add(request); + return answer(request); + }), + ); + }); + + test('reads go to .json with the token and parse the JSON', () async { + answer = (_) => http.Response('{"a":1}', 200); + expect(await nodes.get('r/requests/X/result'), {'a': 1}); + expect(seen.single.url.path, '/r/requests/X/result.json'); + expect(seen.single.url.queryParameters['auth'], 'TOKEN'); + }); + + test('keys are a shallow read', () async { + answer = (_) => http.Response('{"req":true,"claim":true}', 200); + expect(await nodes.keys('r/requests/X'), {'req', 'claim'}); + expect(seen.single.url.queryParameters['shallow'], 'true'); + answer = (_) => http.Response('null', 200); + expect(await nodes.keys('r/requests/X'), isEmpty); + }); + + test( + 'put sends the unit as a JSON object, with the server timestamp', + () async { + await nodes.put('r/requests/X/req', { + '_e2e': 'blob', + 'created': {'.sv': 'timestamp'}, + }); + expect(seen.single.method, 'PUT'); + expect(jsonDecode(seen.single.body), { + '_e2e': 'blob', + 'created': {'.sv': 'timestamp'}, + }); + }, + ); + + test('a refusal raises an error that never carries the token', () async { + answer = (_) => http.Response('Permission denied', 401); + await expectLater( + nodes.get('r'), + throwsA( + isA().having( + (e) => e.toString(), + 'message', + allOf(contains('401'), isNot(contains('TOKEN'))), + ), + ), + ); + }); + + test('a network failure raises without the url', () async { + final broken = RtdbNodes( + databaseUrl: 'https://db.example', + idToken: () async => 'TOKEN', + client: MockClient((_) async => throw http.ClientException('boom')), + ); + await expectLater( + broken.delete('r'), + throwsA( + isA().having( + (e) => e.message, + 'message', + isNot(contains('TOKEN')), + ), + ), + ); + }); + + group('deleteUnclaimed', () { + test('deletes with the ETag it read', () async { + answer = (request) => request.method == 'GET' + ? http.Response('{"req":true}', 200, headers: {'etag': 'E1'}) + : http.Response('null', 200); + expect(await nodes.deleteUnclaimed('r/requests/X'), isTrue); + expect(seen.first.headers['X-Firebase-ETag'], 'true'); + expect(seen.last.method, 'DELETE'); + expect(seen.last.headers['if-match'], 'E1'); + }); + + test('a claim or a result stops it before any delete', () async { + for (final key in ['claim', 'result']) { + seen.clear(); + answer = (_) => http.Response('{"req":true,"$key":true}', 200); + expect(await nodes.deleteUnclaimed('r/requests/X'), isFalse); + expect(seen.map((r) => r.method), ['GET']); + } + }); + + test( + 'a claim that lands in between turns the delete into a refusal', + () async { + answer = (request) => request.method == 'GET' + ? http.Response('{"req":true}', 200, headers: {'etag': 'E1'}) + : http.Response('ETag mismatch', 412); + expect(await nodes.deleteUnclaimed('r/requests/X'), isFalse); + }, + ); + + test('a node already gone counts as withdrawn', () async { + expect(await nodes.deleteUnclaimed('r/requests/X'), isTrue); + expect(seen.map((r) => r.method), ['GET']); + }); + }); +} diff --git a/app/test/services/claude_relay_test_support.dart b/app/test/services/claude_relay_test_support.dart new file mode 100644 index 0000000..0a32e0f --- /dev/null +++ b/app/test/services/claude_relay_test_support.dart @@ -0,0 +1,48 @@ +/// An in-memory [RelayNodes] for the relay client tests. +library; + +import 'package:diet_guard_app/services/claude_relay_rtdb.dart'; + +class MemoryNodes implements RelayNodes { + final Map data = {}; + final List deleted = []; + int failReads = 0; + bool failPut = false; + + @override + Future get(String path) async => data[path]; + + @override + Future> keys(String path) async { + if (failReads > 0) { + failReads--; + throw const RelayTransportError('offline'); + } + return { + for (final key in data.keys) + if (key.startsWith('$path/')) + key.substring(path.length + 1).split('/').first, + }; + } + + @override + Future put(String path, Object value) async { + if (failPut) throw const RelayTransportError('offline'); + data[path] = value; + } + + @override + Future delete(String path) async { + deleted.add(path); + data.removeWhere((key, _) => key == path || key.startsWith('$path/')); + } + + @override + Future deleteUnclaimed(String path) async { + if (data.containsKey('$path/claim') || data.containsKey('$path/result')) { + return false; + } + await delete(path); + return true; + } +} diff --git a/docs/DOCS-claude-relay-phone.md b/docs/DOCS-claude-relay-phone.md new file mode 100644 index 0000000..6858721 --- /dev/null +++ b/docs/DOCS-claude-relay-phone.md @@ -0,0 +1,31 @@ +# The phone's side of the Claude relay + +Code in `app/lib/services/claude_relay_*.dart`; the other half of [the contract](DOCS-claude-relay.md). + + +`RtdbClaudeRelay` implements the screen's `ClaudeRelayClient`; the wire is +`claude_relay_wire.dart`, gated by the fixture +(`app/test/services/claude_relay_contract_test.dart`). The fixture's +`key_hex` is the cipher key itself, which is what `E2eKey.cipher()` hands out +on both devices; the phone gets it through `openDietGuardCipher`, the same +keystore passphrase and header as the log sync (locked = `SyncLockedException` += the lock glyph on the sparkle). + +- `rid` is a ULID made on the phone (`newRequestId`); the entry id is + `uuid5(entry_id_namespace, rid)` (`claudeEntryId`), computed before any + answer. A result whose `entry_id` differs is refused, so undo (a tombstone on + that id) and the logged row always address the entry the PC wrote. +- The phone PUTs `requests//req` with `created = {".sv": "timestamp"}`, + then lists the node's child keys (shallow: the photo is never re-read) every + 1 s, every 5 s after 30 s. No `claim` within 3 s: queued (hourglass), the + same stream keeps waiting, up to 15 min. A `result` is opened, the node + `requests/` is deleted, and the event is shown. +- Fail closed, visibly (error glyph): a body that breaks section 2 (checked + first, nothing is sent), a failed PUT, three failed polls in a row, a result + that does not open or is malformed, an entry id mismatch, the node vanishing. +- **Withdrawing.** A local check-mark log while a request is in flight or queued + calls `cancel(rid)`: one read with `X-Firebase-ETag`, then a `DELETE` with + `if-match`. A claim written in between changes the ETag and turns the delete + into a 412, so "unclaimed" is decided atomically. If it was claimed the PC + *will* log the meal; that race is accepted. The phone keeps the stream open so + the second meal still shows as a row with an undo instead of arriving unseen. diff --git a/docs/DOCS-claude-relay.md b/docs/DOCS-claude-relay.md index f677a01..d909576 100644 --- a/docs/DOCS-claude-relay.md +++ b/docs/DOCS-claude-relay.md @@ -238,5 +238,4 @@ model answer with a grilling round. in `~/src/utils/crdt-sync`. 3. `bash install.sh` (copies and enables `diet-guard-claude.service` once the session file exists). -4. Phone side: the sender, hourglass state and result screen. They follow - sections 1 to 3 and the fixture. +4. Phone side: [DOCS-claude-relay-phone.md](DOCS-claude-relay-phone.md). diff --git a/docs/DOCS-log-screen.md b/docs/DOCS-log-screen.md index 98b122c..5b591fc 100644 --- a/docs/DOCS-log-screen.md +++ b/docs/DOCS-log-screen.md @@ -52,8 +52,11 @@ tombstone by id (several rows can be on screen, so not `undoLastToday`). ## Claude and photos The sparkle talks to `ClaudeRelayClient` (`services/claude_relay_client.dart`), -injectable; `FakeClaudeRelayClient` drives the tests. The request id becomes the -logged entry's id. A photo is **transient input**: `image_picker` scales it to +injectable; `FakeClaudeRelayClient` drives the tests and `RtdbClaudeRelay` +(`claude_relay_firebase.dart`, assigned in `main.dart`) is the real transport, +described in [DOCS-claude-relay-phone.md](DOCS-claude-relay-phone.md). The request +id is a ULID and the logged entry's id is `uuid5` of it. A check-mark log while +a request is waiting withdraws it (`cancel`). A photo is **transient input**: `image_picker` scales it to 1024 px JPEG, the bytes are read into memory and the plugin's cache file is deleted at once (`meal_photo_cleanup_io.dart`). It is never stored, put on a `FoodEntry`, or synced; `repo_invariants_test.dart` asserts it structurally. The