Send meals to Claude over the E2E relay

RtdbClaudeRelay against the contract fixture, ULID ids, uuid5 entry ids, withdraw on local log.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
This commit is contained in:
Krzysztof Rudnicki 2026-11-17 21:41:07 +01:00
parent 26d6a68ac0
commit b0c556b745
22 changed files with 1451 additions and 30 deletions

View File

@ -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/background_tasks.dart';
import 'package:diet_guard_app/services/body_service.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/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/foodbank_service.dart';
import 'package:diet_guard_app/services/frame_stats.dart'; import 'package:diet_guard_app/services/frame_stats.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.dart'; import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
@ -32,6 +34,8 @@ Future<void> main() async {
await KuchniaCredentialService.init(); await KuchniaCredentialService.init();
await BodyService.init(); await BodyService.init();
await KuchniaQueueService.init(); await KuchniaQueueService.init();
// The sparkle button's transport; until this line it fails closed.
claudeRelay = RtdbClaudeRelay.firebase();
final notifications = await NotificationService.init(); final notifications = await NotificationService.init();
// Deliberately *not* awaited before the first frame: the browser's // Deliberately *not* awaited before the first frame: the browser's
// `Notification.requestPermission()` does not complete until the user // `Notification.requestPermission()` does not complete until the user

View File

@ -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/macro_input_row.dart';
import 'package:diet_guard_app/widgets/meal_action_row.dart'; import 'package:diet_guard_app/widgets/meal_action_row.dart';
import 'package:material_ui/material_ui.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. /// Photo attach and the Claude send, for the log screen's state.
mixin LogMealClaudeMixin<T extends StatefulWidget> mixin LogMealClaudeMixin<T extends StatefulWidget>
@ -50,6 +49,7 @@ mixin LogMealClaudeMixin<T extends StatefulWidget>
Uint8List? photo; Uint8List? photo;
StreamSubscription<ClaudeRelayEvent>? _relaySub; StreamSubscription<ClaudeRelayEvent>? _relaySub;
String? _pendingRid;
/// Whether there is something to send (a description or a photo). /// Whether there is something to send (a description or a photo).
bool get canSend => bool get canSend =>
@ -70,12 +70,14 @@ mixin LogMealClaudeMixin<T extends StatefulWidget>
void sendToClaude() { void sendToClaude() {
if (!canSend) return; if (!canSend) return;
final request = ClaudeRelayRequest( final request = ClaudeRelayRequest(
requestId: const Uuid().v4(), requestId: newRequestId(),
slotMinute: targetSlot, slotMinute: targetSlot,
mode: dueMode ? ClaudeRelayMode.due : ClaudeRelayMode.normal,
text: claudeDesc.text.trim(), text: claudeDesc.text.trim(),
photoJpeg: photo, photoJpeg: photo,
); );
unawaited(_relaySub?.cancel()); unawaited(_relaySub?.cancel());
_pendingRid = request.requestId;
setState(() => claudeState = ClaudeButtonState.sending); setState(() => claudeState = ClaudeButtonState.sending);
_relaySub = relay.send(request).listen((e) => unawaited(_onEvent(e))); _relaySub = relay.send(request).listen((e) => unawaited(_onEvent(e)));
} }
@ -86,10 +88,13 @@ mixin LogMealClaudeMixin<T extends StatefulWidget>
case ClaudeRelayQueued(): case ClaudeRelayQueued():
setState(() => claudeState = ClaudeButtonState.queued); setState(() => claudeState = ClaudeButtonState.queued);
case ClaudeRelayLocked(): case ClaudeRelayLocked():
_pendingRid = null;
setState(() => claudeState = ClaudeButtonState.locked); setState(() => claudeState = ClaudeButtonState.locked);
case ClaudeRelayFailed(): case ClaudeRelayFailed():
_pendingRid = null;
setState(() => claudeState = ClaudeButtonState.error); setState(() => claudeState = ClaudeButtonState.error);
case ClaudeRelayLogged(:final entry): case ClaudeRelayLogged(:final entry):
_pendingRid = null;
// The worker logged it under the request id; the sync would deliver // 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. // the same record, so this only shows it now and never doubles it.
final stored = await LogStorageService.instance.addIfAbsent(entry); final stored = await LogStorageService.instance.addIfAbsent(entry);
@ -106,6 +111,26 @@ mixin LogMealClaudeMixin<T extends StatefulWidget>
} }
} }
/// 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<void> 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 /// Cancels the event subscription; call from `dispose`. A request still
/// queued on the PC reaches this phone through sync instead. /// queued on the PC reaches this phone through sync instead.
void disposeClaude() => unawaited(_relaySub?.cancel()); void disposeClaude() => unawaited(_relaySub?.cancel());

View File

@ -136,6 +136,7 @@ class _LogMealScreenState extends State<LogMealScreen>
return; return;
} }
LogFeedback.mealLogged(); // on the tap, before the write LogFeedback.mealLogged(); // on the tap, before the write
unawaited(withdrawClaude()); // else Claude would log it a second time
final entry = await LogStorageService.instance.logMeal( final entry = await LogStorageService.instance.logMeal(
desc, desc,
nutritionFromControllers(_macros, _source), nutritionFromControllers(_macros, _source),

View File

@ -1,28 +1,68 @@
/// The phone's side of the Claude relay: what the check-mark-gold button /// The phone's side of the Claude relay: what the sparkle button sends and
/// sends and what comes back. /// what comes back.
/// ///
/// The transport (a request record synced to the PC, a worker that asks Claude /// The screen only talks to this interface; `claude_relay_firebase.dart` is the
/// and logs the meal, the reply) is not here; the screen only talks to this /// real transport (Firebase RTDB, end-to-end encrypted) and
/// interface. See `docs/DOCS-claude-relay.md` for the wire. /// `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 /// A `Stream`, not a `Future`: the PC may be off, so a request can sit
/// [ClaudeRelayQueued] for hours before the same stream delivers /// [ClaudeRelayQueued] for hours before the same stream delivers
/// [ClaudeRelayLogged]. Terminal events end the stream; [ClaudeRelayQueued] /// [ClaudeRelayLogged]. Terminal events end the stream; [ClaudeRelayQueued]
/// does not. /// does not.
/// ///
/// **The request id is the future entry id.** The worker logs the meal under /// **The request id is a ULID** (`rtdb_relay` never serves another key shape)
/// `ClaudeRelayRequest.requestId`, so the phone's copy (written from /// and **the entry id is derived from it**: `uuid5(namespace, rid)`, computed
/// [ClaudeRelayLogged]) and the PC's copy merge to one entry, and undo is a /// here by [claudeEntryId] exactly as the PC does. So the phone knows the id
/// tombstone on that 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: /// **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 /// 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; library;
import 'dart:math';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:diet_guard_app/models/food_entry.dart'; 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<String>.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. /// One send: the text and/or photo, and the slot the meal belongs to.
class ClaudeRelayRequest { class ClaudeRelayRequest {
@ -30,17 +70,20 @@ class ClaudeRelayRequest {
const ClaudeRelayRequest({ const ClaudeRelayRequest({
required this.requestId, required this.requestId,
required this.slotMinute, required this.slotMinute,
this.mode = ClaudeRelayMode.normal,
this.text = '', this.text = '',
this.photoJpeg, 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; final String requestId;
/// The slot minute the meal is logged against (the oldest due slot in due /// The slot minute the phone would log against now (`client_slot_min`).
/// mode, else `slotForLog`).
final int slotMinute; 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. /// What the user typed, trimmed; may be empty when a photo is attached.
final String text; final String text;
@ -59,7 +102,7 @@ final class ClaudeRelayQueued extends ClaudeRelayEvent {
const ClaudeRelayQueued(); 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 { final class ClaudeRelayLogged extends ClaudeRelayEvent {
/// Creates the event for [entry]. /// Creates the event for [entry].
const ClaudeRelayLogged(this.entry); const ClaudeRelayLogged(this.entry);
@ -88,6 +131,11 @@ abstract interface class ClaudeRelayClient {
/// Sends [request]; the stream carries zero or more [ClaudeRelayQueued] /// Sends [request]; the stream carries zero or more [ClaudeRelayQueued]
/// then one terminal event, and never throws (failures are events). /// then one terminal event, and never throws (failures are events).
Stream<ClaudeRelayEvent> send(ClaudeRelayRequest request); Stream<ClaudeRelayEvent> 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<bool> cancel(String requestId);
} }
/// The stand-in until a transport is wired: every send fails closed. /// The stand-in until a transport is wired: every send fails closed.
@ -98,6 +146,9 @@ class UnconfiguredClaudeRelayClient implements ClaudeRelayClient {
@override @override
Stream<ClaudeRelayEvent> send(ClaudeRelayRequest request) => Stream<ClaudeRelayEvent> send(ClaudeRelayRequest request) =>
Stream.value(const ClaudeRelayFailed('relay not configured')); Stream.value(const ClaudeRelayFailed('relay not configured'));
@override
Future<bool> cancel(String requestId) async => true;
} }
/// The client the screen uses unless it is handed one; `main.dart` assigns the /// The client the screen uses unless it is handed one; `main.dart` assigns the

View File

@ -16,6 +16,12 @@ class FakeClaudeRelayClient implements ClaudeRelayClient {
/// Events replayed on each send before the stream waits for [emit]. /// Events replayed on each send before the stream waits for [emit].
final List<ClaudeRelayEvent> script = []; final List<ClaudeRelayEvent> script = [];
/// Request ids passed to [cancel], oldest first.
final List<String> cancelled = [];
/// What [cancel] answers: true = withdrawn before any claim.
bool cancelResult = true;
StreamController<ClaudeRelayEvent>? _open; StreamController<ClaudeRelayEvent>? _open;
@override @override
@ -34,4 +40,10 @@ class FakeClaudeRelayClient implements ClaudeRelayClient {
controller.add(event); controller.add(event);
if (event is! ClaudeRelayQueued) unawaited(controller.close()); if (event is! ClaudeRelayQueued) unawaited(controller.close());
} }
@override
Future<bool> cancel(String requestId) async {
cancelled.add(requestId);
return cancelResult;
}
} }

View File

@ -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/<ULID>/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<void> Function(Duration)? delay,
this.claimWindow = const Duration(seconds: 3),
this.maxWait = const Duration(minutes: 15),
}) : _now = now ?? DateTime.now,
_delay = delay ?? Future<void>.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<FirebaseRestClient> 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<RelayNodes> Function() openNodes;
/// Opens the E2E cipher, throwing [SyncLockedException] when locked.
final Future<E2eCipher> 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<void> Function(Duration) _delay;
@override
Stream<ClaudeRelayEvent> 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<ClaudeRelayEvent> _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<void> _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<bool> 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;
}
}
}

View File

@ -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<Object?> get(String path);
/// The child keys of [path] (no values), empty when absent.
Future<Set<String>> keys(String path);
/// Replaces the node at [path] with [value].
Future<void> put(String path, Object value);
/// Deletes the node at [path].
Future<void> 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<bool> 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<String> Function() idToken;
final String _base;
final String _prefix;
final http.Client _http;
Future<Uri> _uri(String path, [Map<String, String> query = const {}]) async =>
Uri.parse(
'$_base/$_prefix$path.json',
).replace(queryParameters: {'auth': await idToken(), ...query});
Future<http.Response> _send(
String what,
Future<http.Response> Function(Uri uri) call,
String path, [
Map<String, String> 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<Object?> get(String path) async {
final res = await _send('reading', _http.get, path);
if (!_ok(res)) _refuse('reading', res);
return jsonDecode(res.body);
}
@override
Future<Set<String>> 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<String>().toSet() : {};
}
@override
Future<void> 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<void> delete(String path) async {
final res = await _send('deleting', _http.delete, path);
if (!_ok(res)) _refuse('deleting', res);
}
@override
Future<bool> 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;
}
}

View File

@ -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": <blob>, <clear siblings>}`; 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<String, Object?> 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<String, Object?> 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<Map<String, Object?>> 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<ClaudeRelayEvent> 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<String, dynamic>;
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');
}
}

View File

@ -65,6 +65,22 @@ Future<RemoteStore> 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<E2eCipher> 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 /// The encrypted wake-alarm store over [backend], or null when locked or
/// unreachable. /// unreachable.
/// ///

View File

@ -2,7 +2,7 @@ name: diet_guard_app
description: "Companion phone app for diet_guard: log meals on the go." description: "Companion phone app for diet_guard: log meals on the go."
publish_to: 'none' publish_to: 'none'
version: 1.0.170+1 version: 1.0.171+1
environment: environment:
sdk: ^3.12.2 sdk: ^3.12.2

View File

@ -118,8 +118,6 @@ void main() {
await tester.tap(byIconLabel('Remove photo')); await tester.tap(byIconLabel('Remove photo'));
await settle(tester); await settle(tester);
expect(sparkleEnabled(tester), isFalse); expect(sparkleEnabled(tester), isFalse);
}); });
}); });
@ -158,7 +156,7 @@ void main() {
await settle(tester); await settle(tester);
expect(byIconLabel('Waiting for the PC'), findsOneWidget); 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))); relay.emit(ClaudeRelayLogged(_claudeEntry(id)));
await settle(tester); await settle(tester);

View File

@ -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<void> Function() restore;
late FakeClaudeRelayClient relay;
setUp(() async {
restore = await isolateLogScreenState();
relay = FakeClaudeRelayClient();
});
tearDown(() => restore());
Future<void> 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));
});
});
}
}

View File

@ -116,7 +116,11 @@ void main() {
await tester.tap(controlByLabel('Claude failed')); await tester.tap(controlByLabel('Claude failed'));
await tester.pump(); await tester.pump();
relay.emit(ClaudeRelayLogged(claudeEntry(relay.sent.last.requestId))); relay.emit(
ClaudeRelayLogged(
claudeEntry(claudeEntryId(relay.sent.last.requestId)),
),
);
await settle(tester); await settle(tester);
expect(find.byIcon(Icons.undo), findsOneWidget); expect(find.byIcon(Icons.undo), findsOneWidget);
// Still due (12:00 is open): the screen stays in due mode. // Still due (12:00 is open): the screen stays in due mode.

View File

@ -9,7 +9,7 @@ import 'package:diet_guard_app/services/claude_relay_fake.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
const _request = ClaudeRelayRequest( const _request = ClaudeRelayRequest(
requestId: 'r1', requestId: '01JD5Z8K3M7Q2W9XH4TBN6VR0E',
slotMinute: 480, slotMinute: 480,
text: 'x', text: 'x',
); );
@ -27,8 +27,8 @@ void main() {
await Future<void>.delayed(Duration.zero); await Future<void>.delayed(Duration.zero);
expect(done.isCompleted, isFalse); expect(done.isCompleted, isFalse);
const entry = FoodEntry( final entry = FoodEntry(
id: 'r1', id: claudeEntryId(_request.requestId),
time: 't', time: 't',
desc: 'x', desc: 'x',
grams: 1, grams: 1,
@ -38,13 +38,16 @@ void main() {
fatG: 1, fatG: 1,
source: 'claude', source: 'claude',
); );
relay.emit(const ClaudeRelayLogged(entry)); relay.emit(ClaudeRelayLogged(entry));
await done.future; await done.future;
expect(events.map((e) => e.runtimeType), [ expect(events.map((e) => e.runtimeType), [
ClaudeRelayQueued, ClaudeRelayQueued,
ClaudeRelayLogged, ClaudeRelayLogged,
]); ]);
expect((events.last as ClaudeRelayLogged).entry.id, _request.requestId); expect(
(events.last as ClaudeRelayLogged).entry.id,
claudeEntryId(_request.requestId),
);
}, },
); );

View File

@ -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<String, dynamic> _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<String, dynamic>;
}
List<int> _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<String, dynamic>;
final node = request['node'] as Map<String, dynamic>;
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<String, dynamic>)['plain']
as Map<String, dynamic>;
final body = plain['body'] as Map<String, dynamic>;
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<E2eDecryptError>()),
);
});
test('the fixture logged result becomes a Claude entry', () async {
final logged =
(fx['results'] as Map<String, dynamic>)['logged']
as Map<String, dynamic>;
final event = await openResult(cipher, rid, logged['node']);
final entry = (event as ClaudeRelayLogged).entry;
final plain = logged['plain'] as Map<String, dynamic>;
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<String, dynamic>)[name] as Map<String, dynamic>;
final event = await openResult(cipher, rid, res['node']);
expect(
(event as ClaudeRelayFailed).reason,
(res['plain'] as Map<String, dynamic>)['error_code'],
);
});
}
test('a result for another request does not open', () async {
final logged =
(fx['results'] as Map<String, dynamic>)['logged']
as Map<String, dynamic>;
final event = await openResult(
cipher,
'01JD5Z8K3M7Q2W9XH4TBN6VR0F',
logged['node'],
);
expect(event, isA<ClaudeRelayFailed>());
});
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<String, dynamic>)['logged']
as Map<String, dynamic>;
expect(
await openResult(other, rid, logged['node']),
isA<ClaudeRelayFailed>(),
);
expect(await openResult(cipher, rid, null), isA<ClaudeRelayFailed>());
expect(
await openResult(cipher, rid, {'ok': true}),
isA<ClaudeRelayFailed>(),
);
});
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<ClaudeRelayFailed>());
});
group('body cases', () {
for (final c in (fx['body_cases'] as List).cast<Map<String, dynamic>>()) {
test('${c['name']} is ${c['valid'] == true ? 'valid' : 'refused'}', () {
final problem = relayBodyProblem(
(c['body'] as Map<String, dynamic>).cast<String, Object?>(),
);
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);
});
});
}

View File

@ -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<void> 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<ClaudeRelayLogged>(),
);
nodes.data.clear();
nodes.failReads = 3;
expect(
(await relay.send(request).toList()).single,
isA<ClaudeRelayFailed>(),
);
});
test('no answer within the wait fails closed, after queued', () async {
final events = await relay.send(request).toList();
expect(events.first, isA<ClaudeRelayQueued>());
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);
});
}

View File

@ -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<Map<String, Object?>> sealedResult(Map<String, Object?> plain) async =>
{
'_e2e': await cipher.seal(jsonEncode(plain), path: '$_node/result'),
'at': 1,
};
Future<void> 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<List<ClaudeRelayEvent>> 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<String, Object?>? unit;
tick = (_) {
unit ??= nodes.data['$_node/req']! as Map<String, Object?>;
workerLogs();
};
await run();
expect(unit!.keys.toSet(), {'_e2e', 'created'});
final plain =
jsonDecode(
await cipher.open(unit!['_e2e']! as String, path: '$_node/req'),
)
as Map<String, dynamic>;
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<ClaudeRelayLocked>());
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<ClaudeRelayFailed>());
expect(nodes.data, isEmpty);
});
test('a failed put is a visible failure', () async {
nodes.failPut = true;
expect((await run()).single, isA<ClaudeRelayFailed>());
});
}

View File

@ -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<http.Request> 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 <path>.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<RelayTransportError>().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<RelayTransportError>().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']);
});
});
}

View File

@ -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<String, Object?> data = {};
final List<String> deleted = [];
int failReads = 0;
bool failPut = false;
@override
Future<Object?> get(String path) async => data[path];
@override
Future<Set<String>> 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<void> put(String path, Object value) async {
if (failPut) throw const RelayTransportError('offline');
data[path] = value;
}
@override
Future<void> delete(String path) async {
deleted.add(path);
data.removeWhere((key, _) => key == path || key.startsWith('$path/'));
}
@override
Future<bool> deleteUnclaimed(String path) async {
if (data.containsKey('$path/claim') || data.containsKey('$path/result')) {
return false;
}
await delete(path);
return true;
}
}

View File

@ -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/<rid>/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/<rid>` 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.

View File

@ -238,5 +238,4 @@ model answer with a grilling round.
in `~/src/utils/crdt-sync`. in `~/src/utils/crdt-sync`.
3. `bash install.sh` (copies and enables `diet-guard-claude.service` once 3. `bash install.sh` (copies and enables `diet-guard-claude.service` once
the session file exists). the session file exists).
4. Phone side: the sender, hourglass state and result screen. They follow 4. Phone side: [DOCS-claude-relay-phone.md](DOCS-claude-relay-phone.md).
sections 1 to 3 and the fixture.

View File

@ -52,8 +52,11 @@ tombstone by id (several rows can be on screen, so not `undoLastToday`).
## Claude and photos ## Claude and photos
The sparkle talks to `ClaudeRelayClient` (`services/claude_relay_client.dart`), The sparkle talks to `ClaudeRelayClient` (`services/claude_relay_client.dart`),
injectable; `FakeClaudeRelayClient` drives the tests. The request id becomes the injectable; `FakeClaudeRelayClient` drives the tests and `RtdbClaudeRelay`
logged entry's id. A photo is **transient input**: `image_picker` scales it to (`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 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 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 `FoodEntry`, or synced; `repo_invariants_test.dart` asserts it structurally. The