Compare commits

...

12 Commits

Author SHA1 Message Date
c02d9b2ea4 Sync pubspec.lock with the resolver
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:50:10 +01:00
801a0b4bab Share the sync session in the Claude worker
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:47:47 +01:00
a936d07a7e Add a Claude button to the gate lock
A star button beside the log button sends the typed text to
estimate_meal and logs the result like a typed meal: the locked slot,
source "claude", food bank, unlock. Icon states only (idle star, spinner,
warning); no visible text. It is composed (ClaudeFlow), not a new MRO
class, since the gate chain is at pylint's max-parents cap.

Idle uses U+2726, not the sparkles emoji: U+2728 is only in FreeSerif and
Noto Color Emoji here, and a colour-emoji fallback can crash Tk 8.6.

Failure paths (all fail-closed: never unlock, block or freeze):
- estimator error, no login, bad JSON, any exception: warning icon,
  nothing logged, manual log path untouched.
- no answer in 45 s: the poll gives up (warning icon); a late answer is
  discarded.
- slot already logged by hand meanwhile: the result is dropped.
- empty description: error status, no call.
- seam: the estimator name is patched to a raising stub in conftest; a
  mistyped target errors every test at setup (verified once).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:42:35 +01:00
03b6a455cb Auto-log due catering before the lock
kuhy's 2026-11-17 override of "delivered is not eaten": before the lock
opens, the PC logs the due slots' dishes by id uuid5(kuchnia📅key),
shared with the phone (fixture-pinned).

Failure paths:
- fetch error, no credentials, > 5 s: fail-closed, nothing is logged,
  the lock opens as before, reason emitted and logged.
- log write error (OSError/ValueError): fail-closed, same.
- gate --check: never logs (a decision, not a write).
- an undone (tombstoned) entry counts as logged: fail-closed against
  resurrecting a meal kuhy removed.
- publish outage after a clearing auto-log: fail-open by design, the
  local entry stays and the reason is emitted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:42:34 +01:00
b0c556b745 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
2026-11-17 21:41:07 +01:00
26d6a68ac0 Due-mode log screen, Claude button, photos
Action row 1A, due mode, catering auto-log rows with undo, relay interface, photo input.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:26:13 +01:00
e6322f7f3e Serialise the relay's log writers
The narrow pull, the log write and the publish each read, merge and write
the food log. Run at once (a publish in flight while a second request
logs) they lose the append: the phone is told "logged" and the only copy
is gone. The new race test lost an entry before this change (1 of 2) and
keeps both after it; the shared temp-file name of the log writer also
collided between threads.

One asyncio lock now covers the pull, "resolve slot + log" and the
publish. A request arriving during a publish waits for it (up to one full
tick); the model call stays outside the lock.

Also: a test that the relay unlocks the header diet_guard's devices store
wrote (same key, a blob sealed by one opens on the other), the skill
returns grams 0 for nothing to estimate (parse fails closed, nothing is
logged), and the doc's session note is corrected: the pull and publish
refresh the gate's session file as the CLI's publish does.

Failure paths: a lost append is now impossible in-process (fail closed by
waiting); the pull failure, locked key, estimator and cleanup paths are
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:21:05 +01:00
642467dc1d Add the Claude relay worker
python -m diet_guard claude-worker serves the phone's meal requests from
RTDB (rtdb_relay RequestServer, one SSE stream, reconnects with backoff):
validate, estimate with Claude, log through the signed log with
source=claude under the oldest due slot (normal mode: nearest slot of the
phone's hint), write the sealed result, delete only the request payload,
then publish in the background. diet-guard-claude.service (Restart=on-failure,
WantedBy=default.target) is installed by install.sh and started once the
worker's own Firebase session exists. Nothing is deployed by this commit.

Failure paths:
- narrow peer pull fails (sync locked/unreachable): fail closed, no claim, no
  answer, no model call; the request stays pending, retried every 30 s
- e2e key locked, no passphrase, no session: fail closed, nothing read or
  written; the worker waits and retries every 60 s
- bad body, request older than 24 h (or no created): fail closed, an error
  result, nothing logged
- Claude failure/timeout/invalid JSON: fail closed, an error result with
  retry, nothing logged
- crash between log and result, or a duplicate event: idempotent, the entry
  id is uuid5 of the rid and is looked up (tombstones included) before the
  model call
- request payload delete, old-answer cleanup and the post-answer publish
  failing: fail open on purpose (logged only); the answer and the local
  entry are already durable
- due mode with nothing due: falls back to slot_for_log, not an error

New log helpers log_meal_as / find_entry; log_meal's body is split into
_entry_fields / _store_entry with the same output. The gate and CLI import
none of the worker's dependencies at load time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:15:08 +01:00
6cd3470502 Add the Claude meal estimator
estimate_meal(text, photo) -> Estimate runs Claude through
claude_agent_sdk in an isolated CLAUDE_CONFIG_DIR: a copy of the access
token (no refresh token, no MCP tokens) and the diet-food skill, never
kuhy's ~/.claude. The skill text is the system prompt; the closest curated
and derived food-bank rows ride in the user message; the photo is an image
block; the answer is constrained by a JSON schema and validated again.

Failure paths, all fail closed (an EstimateError code, nothing logged):
- no host login, CLI/API error, bad transport: estimate_failed
- more than 45 s: estimate_timeout
- no object, missing/mistyped field, NaN/inf/negative/absurd number,
  grams 0, blank or long desc: estimate_invalid
- neither text nor photo: ValueError before any model call
- failed token refresh is logged, the call then fails as estimate_failed

Live smoke (scratch HOME, nothing logged): "2 jajka sadzone i kromka
chleba" -> 315 kcal in 4.3 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:05:41 +01:00
3d8d358abd Add Claude relay seams and entry points
Dependencies (exact pins): claude-agent-sdk 0.2.183, rtdb-relay 0.1.1,
httpx 0.28.1, hypothesis 6.170.15 (dev). The pylint hook env gets the
same pins.

Entry points, each reachable only through one module attribute:
_claude_connect.connect_sealed (RTDB + e2e unlock), _claude_sdk.run_model
(the model call), _claude_sync.pull_peers / publish (narrow pull, full
tick). SDK and rtdb_relay are imported only by these modules, never by the
gate or CLI at load time.

Test isolation, all fail closed: connect_sealed and run_model are replaced
by a function that raises; pull/publish return None; the sandbox dir and
kuhy's real Claude login path point into tmp_path; _test_guard also
protects ~/.config/diet_guard_claude and ~/.cache/diet_guard. Each of the
six redirects was removed once and its canary went red (fail closed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:02:35 +01:00
a3d089fee3 Allow material_ui 1.11.0 behind sync_settings_ui
The freshness gate was red for every commit: the version-bump hook stages
app/pubspec.yaml, and material_ui 1.11.1 (released after the last green
run) cannot resolve because sync_settings_ui 0.8.2 pins 1.11.0 exactly
(flutter pub get fails on the conflict).

A transitive predicate entry: it clears itself when sync_settings_ui
moves. Added without asking because no commit could pass otherwise; drop
this commit if you prefer to fix it in utils first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:02:30 +01:00
3ce43b56df Add the Claude relay contract
Contract for the phone "send to Claude" button, written before any code:
docs/DOCS-claude-relay.md, the shared Python/Dart fixture and its
builder script. No code runs from this commit.

Failure paths named in the contract:
- locked sync / locked e2e key: fail closed, worker writes nothing, the
  request stays pending (phone keeps its hourglass)
- invalid body, request older than 24 h, Claude timeout/failure/invalid
  JSON: fail closed, an error result is written and nothing is logged
- duplicate event, expired lease or crash replay: idempotent by rid (entry
  id is uuid5 of the rid, checked before the Claude call)
- due mode with nothing due: not an error, falls back to slot_for_log

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 20:55:50 +01:00
149 changed files with 9517 additions and 1862 deletions

View File

@ -29,7 +29,7 @@ repos:
args: [--pytest-test-first]
# Shared fakes and fixtures, not test modules. Split out of conftest.py
# and test_sync.py only because those files passed the 250-line cap.
exclude: ^diet_guard/tests/_(tk_fakes(_containers|_canvas)?|gate_layout_probe|gate_focus_probe|gate_measurement|gate_keyboard_probe|gate_fixtures|sync_fakes|kuchnia_fakes|state_redirects)\.py$
exclude: ^diet_guard/tests/_(tk_fakes(_containers|_canvas)?|gate_layout_probe|gate_focus_probe|gate_measurement|gate_keyboard_probe|gate_fixtures|sync_fakes|kuchnia_fakes|state_redirects|claude_redirects|claude_fakes|claude_worker_fakes)\.py$
- id: check-ast
- id: mixed-line-ending
args: [--fix=lf]
@ -114,7 +114,10 @@ repos:
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.14.0#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.4#subdirectory=sickdays
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.5#subdirectory=sickdays
- rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.1.1#subdirectory=rtdb_relay
- claude-agent-sdk==0.2.183
- httpx==0.28.1
- mcp>=2,<3
- pydantic
- defusedxml==0.7.1

View File

@ -15,6 +15,7 @@ show adherence, streaks, a YTD tally and weekly/monthly averages, all derived fr
- One sync tick: `python -m diet_guard sync`
- Averages: `python -m diet_guard averages`; Body: `body`, `weight KG`, `profile`, `plan-week`
- Prune dead sync peers (dry run): `python -m diet_guard prune-peers`
- "Send to Claude" worker: `python -m diet_guard claude-worker` ([relay](docs/DOCS-claude-relay.md), [screen](docs/DOCS-log-screen.md))
- Install: `bash install.sh` (production); app: `cd app && bash install_arch.sh`; run app: `bash run.sh`; phone: `flutter build apk --release`
- run: `python -m diet_guard gate --demo`
- test: `python -m pytest -n auto -p no:sugar -q` (python, 100% branch bar from pyproject) then `cd app && flutter test --reporter=compact`
@ -215,18 +216,18 @@ only); the CLI, gate and phone show both.
(`2.5.round() == 3`), so a float path silently desyncs the two devices —
and a slot one device offers while the other does not is a checkpoint that
can never be satisfied, i.e. a permanent lock. Integer `//` and `~/` only.
- Don't re-add the meal builder, "repeat last meal", the reward prompt, or
**meal photos** — all removed deliberately, enforced by
`app/test/repo_invariants_test.dart`. Photos also took `image_picker`, the
blob stores, the `/blobs/` route and the `CAMERA` permission; re-adding them
means syncing image blobs too.
- Don't re-add the meal builder, "repeat last meal" or the reward prompt
(removed deliberately, `app/test/repo_invariants_test.dart`). A meal photo is
transient input to Claude only (2026-11-17): never stored, on a `FoodEntry`
or synced; the invariants test asserts no image bytes reach a record.
- Don't strip the `components` field: nothing writes it, but historical
composite entries and the food bank read it, and it is part of the sync wire
format.
- Don't let the catering import log unattended (delivered ≠ eaten), don't let
its Python and Dart halves drift (one shared fixture gates them), and don't
make the synced password machine-local — the phone could not then fetch.
[docs](docs/DOCS-kuchnia-wikinga.md), [phone](docs/DOCS-kuchnia-wikinga-phone.md).
- Catering logs itself since 2026-11-17 (kuhy overrode "delivered ≠ eaten":
"LOG EVEN WITHOUT TAP"): v5 ids `kuchnia:<date>:<dishId>`, undo tombstones.
Don't let its Python and Dart halves drift (shared fixtures) or make the
synced password machine-local. [docs](docs/DOCS-kuchnia-wikinga.md),
[phone](docs/DOCS-kuchnia-wikinga-phone.md).
- Don't add a dependency without the production install-path check above.
- Don't reintroduce a seal/`chattr +i` on the budget file.
- Don't re-add a Linux embedder target, and don't change the wrapper's port or

View File

@ -19,6 +19,12 @@
only, foreground only: no READ_HEALTH_DATA_IN_BACKGROUND, so the
WorkManager isolate never reads Health Connect. -->
<uses-permission android:name="android.permission.health.READ_STEPS"/>
<!-- Camera for the meal photo sent to Claude (meal_photo_source.dart); the
runtime permission is requested before the camera opens. A photo is
transient input: it is never stored or synced. Not every device has a
camera, and the gallery path works without one. -->
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<!-- Deliberately NOT requesting SCHEDULE_EXACT_ALARM: the background
check is a 15-minute WorkManager periodic task, not exact alarms
(more robust against OEM background-kill; +/-15 min is accepted, see

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/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<void> 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

View File

@ -20,6 +20,7 @@ class KuchniaDish {
required this.grams,
required this.priority,
required this.slotLabel,
this.dishId = '',
});
/// The dish itself (`menuMealName`), e.g. "Kaszotto grzybowe...".
@ -52,6 +53,17 @@ class KuchniaDish {
/// The caterer's slot label ("Śniadanie", "Obiad", ...), for display only.
final String slotLabel;
/// The panel's own id for this meal (`deliveryMealId`), as a string, or ''
/// when the payload carried none.
///
/// Never written to the bank record or the log: it only feeds [autologKey].
final String dishId;
/// The dish half of the auto-log entry id: [dishId], else [bankKey].
///
/// Mirrors the fixture `tests/fixtures/kuchnia_autolog_ids.json`.
String get autologKey => dishId.isNotEmpty ? dishId : bankKey;
/// The curated-bank record for this dish.
///
/// Mirrors `_kuchnia_import.dish_to_record`. `count` is 0: the bank's count

View File

@ -6,8 +6,7 @@ import 'package:material_ui/material_ui.dart';
/// Writes [suggestion]'s name and macros into the log form's controllers.
///
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap, mirroring
/// `log_meal_kuchnia_mixin.dart`'s `fillControllersFromDish`.
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap.
void fillControllersFromSuggestion(
FoodSuggestion suggestion,
TextEditingController desc,

View File

@ -0,0 +1,137 @@
/// The sparkle button: send the typed text and/or photo to Claude.
///
/// Its own file because `log_meal_screen.dart` is at the repo's 250-line
/// ceiling. The transport is behind [ClaudeRelayClient]; this only drives the
/// button's states and shows the meal Claude logged.
///
/// The photo lives in [photo] for one send and nowhere else.
library;
import 'dart:async';
import 'dart:typed_data';
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_logged_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
import 'package:diet_guard_app/services/claude_relay_client.dart';
import 'package:diet_guard_app/services/log_entry_lookup.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_photo_source.dart';
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';
/// Photo attach and the Claude send, for the log screen's state.
mixin LogMealClaudeMixin<T extends StatefulWidget>
on
LogMealSyncMixin<T>,
LogMealDueMixin<T>,
LogMealLoggedMixin<T>,
LogMealFutureMixin<T> {
/// The relay this screen sends through. Supplied by the screen.
ClaudeRelayClient get relay;
/// Where photos come from. Supplied by the screen.
MealPhotoSource get photoSource;
/// The food field. Supplied by the screen.
TextEditingController get claudeDesc;
/// The macro fields. Supplied by the screen.
MacroControllers get claudeMacros;
/// The sparkle button's state.
ClaudeButtonState claudeState = ClaudeButtonState.idle;
/// The attached photo's JPEG bytes, or null. Never stored or synced.
Uint8List? photo;
StreamSubscription<ClaudeRelayEvent>? _relaySub;
String? _pendingRid;
/// Whether there is something to send (a description or a photo).
bool get canSend =>
futureDate == null &&
(claudeDesc.text.trim().isNotEmpty || photo != null);
/// Attaches a photo from [origin]; backing out keeps the current one.
Future<void> attachPhoto(PhotoOrigin origin) async {
final bytes = await photoSource.pick(origin);
if (!mounted || bytes == null) return;
setState(() => photo = bytes);
}
/// Drops the attached photo.
void removePhoto() => setState(() => photo = null);
/// Sends the form to Claude and follows the request's events.
void sendToClaude() {
if (!canSend) return;
final request = ClaudeRelayRequest(
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)));
}
Future<void> _onEvent(ClaudeRelayEvent event) async {
if (!mounted) return;
switch (event) {
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);
if (!mounted) return;
claudeDesc.clear();
claudeMacros.clear();
setState(() {
claudeState = ClaudeButtonState.idle;
photo = null;
});
showLogged([LoggedMeal(stored, LoggedOrigin.claude)]);
await publishAfterLog();
await refreshSlots();
}
}
/// 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
/// queued on the PC reaches this phone through sync instead.
void disposeClaude() => unawaited(_relaySub?.cancel());
}

View File

@ -0,0 +1,89 @@
/// Due mode: some slot has elapsed with nothing logged.
///
/// The log screen then strips everything that is not "log this meal now" (the
/// app bar, sync banner, date row), hides the Android status bar, and targets
/// the oldest due slot with both the check and the sparkle. Its own file
/// because `log_meal_screen.dart` is at the repo's 250-line ceiling.
///
/// Slot arithmetic is not touched here: due slots come from `missingSlots`
/// and the nearest-slot rule from `slotForLog`, both in `models/slot.dart`.
library;
import 'dart:async';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:flutter/services.dart';
import 'package:material_ui/material_ui.dart';
/// The clock the log screen reads for "which slots are due".
///
/// A hook rather than a constructor argument so the whole screen suite can pin
/// it once (`flutter_test_config.dart` pins 07:00, before the first slot);
/// otherwise every nav and slot test would pass at night and fail by day, once
/// due mode hides the app bar.
@visibleForTesting
DateTime Function() logMealClock = DateTime.now;
/// Shows or hides the Android status bar.
///
/// `main.dart` sets no system-UI mode, so "visible" is the platform default:
/// both bars shown. [hidden] true is sticky-immersive; false puts both back.
@visibleForTesting
Future<void> Function({required bool hidden}) setStatusBarHidden = _setBars;
Future<void> _setBars({required bool hidden}) => hidden
? SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky)
: SystemChrome.setEnabledSystemUIMode(
SystemUiMode.manual,
overlays: SystemUiOverlay.values,
);
/// Due-mode state and slot targeting for the log screen's state.
mixin LogMealDueMixin<T extends StatefulWidget> on LogMealSyncMixin<T> {
/// Whether the first read of today's log has finished. Until then the
/// screen draws neither mode, so it never flashes the app bar and drops it.
bool slotsLoaded = false;
bool _statusBarHidden = false;
/// What the screen reads as "now" (see [logMealClock]).
DateTime get screenNow => logMealClock();
/// Elapsed slots with nothing logged, oldest first.
List<int> get dueSlots =>
missingSlots(screenNow, loggedSlots, MealScheduleService.current);
/// Whether the screen is in due mode.
bool get dueMode => slotsLoaded && dueSlots.isNotEmpty;
/// The slot a log or a send lands in: the oldest due slot, else the slot
/// nearest [screenNow] (`slotForLog`).
int get targetSlot => dueSlots.isNotEmpty
? dueSlots.first
: slotForLog(screenNow, MealScheduleService.current);
@override
Future<void> refreshSlots() async {
await super.refreshSlots();
if (!mounted) return;
setState(() => slotsLoaded = true);
await syncStatusBar();
}
/// Hides the status bar while in due mode and restores it on exit.
Future<void> syncStatusBar() async {
final hide = dueMode;
if (hide == _statusBarHidden) return;
_statusBarHidden = hide;
await setStatusBarHidden(hidden: hide);
}
/// Puts the status bar back; call from `dispose`.
void restoreStatusBar() {
if (!_statusBarHidden) return;
_statusBarHidden = false;
unawaited(setStatusBarHidden(hidden: false));
}
}

View File

@ -1,131 +0,0 @@
/// Wires "Fill all with catering" into the log form.
///
/// Its own file because `log_meal_screen.dart` and
/// `log_meal_kuchnia_mixin.dart` are both at the repo's 250-line ceiling. The
/// rule lives in `kuchnia_fill.dart` and the two-tap state in
/// `kuchnia_fill_flow.dart`; this only connects them to the screen.
library;
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_kuchnia_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
import 'package:diet_guard_app/services/kuchnia_fill_flow.dart';
import 'package:diet_guard_app/services/kuchnia_queue.dart';
import 'package:diet_guard_app/services/kuchnia_spread.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:material_ui/material_ui.dart';
/// One fill tap's status (see [CountCue]).
typedef FillCue = CountCue;
/// The cue for a tap's [outcome]: dishes logged (ok + N), a proposal of
/// [armed] dishes (info + N), or nothing done (warn + 0: no delivery, every
/// slot taken, or the fetch failed).
FillCue fillCue(FillOutcome outcome, {required int armed}) {
final written = outcome.written.length;
final label = outcome.message;
if (written > 0) return (label: label, kind: CueKind.ok, count: written);
if (armed > 0) return (label: label, kind: CueKind.info, count: armed);
return (label: label, kind: CueKind.warn, count: 0);
}
/// Drives the screen's [FillAllFlow] and tidies the screen after a fill.
mixin LogMealFillMixin<T extends StatefulWidget>
on LogMealSyncMixin<T>, LogMealKuchniaMixin<T>, LogMealFutureMixin<T> {
/// The flow behind the button. Per-screen, so leaving the screen drops an
/// armed proposal along with it.
FillAllFlow fillFlow = FillAllFlow();
/// Shows [cue] as a status cue (its label is only spoken). Supplied by the
/// screen.
void showFillStatus(FillCue cue);
/// A proposal belongs to the date it was fetched for; picking another (or
/// going back to today) must not leave "Confirm (N)" offering it.
@override
void onLogDateChanged() {
super.onLogDateChanged();
fillFlow.cancel();
}
/// Runs one tap: the first proposes, a second on the same day confirms.
/// Fills the "Log for later" date when one is picked, else today.
Future<void> onFillAll() async {
final day = futureDate;
final pending = fillFlow.tap(day: day);
setState(() {}); // show the busy label while the fetch/writes run
final FillOutcome? outcome;
try {
outcome = await pending;
} on Exception catch (error) {
if (!mounted) return;
setState(() {});
// A confirm can fail partway through its writes. Whatever did land is
// a real meal, so it is published like any other rather than waiting
// for the next tick, and the user is told the batch did not finish.
await publishAfterLog();
await refreshSlots();
if (mounted) {
showFillStatus((
label: 'Fill all failed: $error',
kind: CueKind.error,
count: null,
));
}
return;
}
if (!mounted) return;
setState(() {});
if (outcome == null) return;
if (outcome.written.isNotEmpty) {
await _afterFill(outcome.written, later: day != null);
}
if (!mounted) return;
showFillStatus(fillCue(outcome, armed: fillFlow.armedCount));
}
/// Disarms a proposal without writing anything.
void onFillCancel() {
fillFlow.cancel();
showFillStatus((
label: 'Fill all cancelled — nothing logged.',
kind: CueKind.info,
count: null,
));
}
/// Publishes the batch once and drops the filled dishes from the delivery
/// queue, so "Today's delivery (N more to go)" and the prefilled form do
/// not keep offering meals that were just logged.
///
/// A [later] fill logged another day's delivery: today's queue and form are
/// left alone, and the screen goes back to today, as after a manual
/// "Log for later" -- the picked day's slot row would otherwise be stale.
Future<void> _afterFill(
List<SlottedDish> written, {
required bool later,
}) async {
if (later) {
resetFutureLog();
await publishAfterLog();
await refreshSlots();
return;
}
if (KuchniaQueueService.isInitialized) {
for (final item in written) {
KuchniaQueueService.instance.markLogged(item.dish);
}
}
final offered = offeredDish;
if (offered != null &&
written.any((item) => item.dish.bankKey == offered.bankKey)) {
// The prefilled dish was just logged by the fill; leaving it in the
// form would invite a second, duplicate submit.
descController.clear();
macroControllers.clear();
}
prefillNextDish();
await publishAfterLog();
await refreshSlots();
}
}

View File

@ -3,10 +3,7 @@
/// Its own file because `log_meal_screen.dart` is at the repo's 250-line cap.
///
/// Scoped to dates strictly after today: the date picker's `firstDate` is
/// tomorrow. Today's own not-yet-due slots keep using the screen's existing
/// [SlotSelectorRow] (driven by the real `DateTime.now()`), so this mixin
/// never has to reproduce its "due" (red) coloring, which is meaningless for
/// a day that hasn't started.
/// tomorrow.
library;
import 'package:diet_guard_app/models/food_entry.dart';
@ -126,23 +123,14 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
);
}
/// The slot row to show: [futureDate]'s own (driven by that date's logged
/// slots) when a future date is picked, otherwise today's, built from the
/// screen's own state and [onTodaySlotSelected].
Widget buildSlotRow({
required Set<int> loggedSlots,
required int? selectedSlot,
required ValueChanged<int?> onTodaySlotSelected,
}) {
/// The slot row for a picked future date, else nothing.
///
/// Today has no slot row any more: the screen derives today's slot (the
/// oldest due one, else the nearest). A *future* date has no due slots to
/// derive from, so the row survives for exactly that case.
Widget buildSlotRow() {
final date = _futureDate;
if (date == null) {
return SlotSelectorRow(
now: DateTime.now(),
loggedSlots: loggedSlots,
selectedSlot: selectedSlot,
onSlotSelected: onTodaySlotSelected,
);
}
if (date == null) return const SizedBox.shrink();
return SlotSelectorRow(
now: DateTime(date.year, date.month, date.day),
schedule: _futureSchedule,

View File

@ -1,248 +0,0 @@
/// Offers the day's delivered catering dishes to the log form.
///
/// Its own file because `log_meal_screen.dart` is at the repo's 250-line
/// ceiling.
///
/// **A delivered meal is not an eaten meal.** This only ever *prefills* the
/// form -- the user still taps "Log" for each dish. Nothing here writes a log
/// entry, and nothing here may start doing so: the gate would then satisfy its
/// own checkpoint from a delivery note, and the log would record what the
/// courier dropped off rather than what was eaten.
///
/// [prefillNextDish] is called from **two** places: once when the delivery
/// first arrives, and again after every successful submit. That second caller
/// is the load-bearing one. On the PC it briefly did not exist, which made the
/// "(N more to go)" promise a dead letter -- every dish after the first stayed
/// queued behind another click. `kuchnia_queue_test.dart` asserts the state
/// transition rather than "a dish was offered", because the latter passes
/// while this misbehaves.
library;
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/kuchnia_import.dart';
import 'package:diet_guard_app/services/kuchnia_queue.dart';
import 'package:diet_guard_app/services/kuchnia_spread.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/widgets/macro_input_row.dart';
import 'package:material_ui/material_ui.dart';
CountCue _cue(String l, CueKind k, [int? n]) => (label: l, kind: k, count: n);
/// Writes [dish]'s name and macros into the log form's controllers.
///
/// Free function rather than a mixin method so the numeric formatting is
/// testable without pumping a widget.
///
/// Clears every macro field first, mirroring `_gatelock_delivery.py`'s
/// `self._clear_inputs()`. Dropping that step is what corrupted a real log
/// entry on 2026-08-23: a dish carries *per-portion* macros and leaves
/// [MacroControllers.perGrams] untouched, so a `100` left behind by an
/// earlier food-bank pick made `nutritionForPortion` read them as *per-100g*
/// and scale them by `grams / 100` -- 472 kcal logged as 1217.8.
///
/// The clear is a single call covering all six controllers rather than a
/// `perGrams.clear()` line here, so a seventh field added later cannot be
/// forgotten at this call site; `MacroControllers.clear()` is enumerated by
/// its own test.
void fillControllersFromDish(
KuchniaDish dish,
TextEditingController desc,
MacroControllers macros,
) {
macros.clear();
desc.text = dish.name;
final (grams, values) = dishFieldValues(dish);
macros.kcal.text = values.$1;
macros.protein.text = values.$2;
macros.carbs.text = values.$3;
macros.fat.text = values.$4;
macros.grams.text = grams;
}
/// Wires the catering queue into a log form.
mixin LogMealKuchniaMixin<T extends StatefulWidget> on State<T> {
/// The dish currently prefilled from the delivery, if any.
KuchniaDish? offeredDish;
/// How many delivered dishes still need logging, including the offered one.
///
/// The offered dish counts: it is prefilled, not logged, and the user has
/// still to tap for it. Excluding it made the line read "0 more" while a
/// real dish sat in the form.
int get dishesStillQueued => KuchniaQueueService.remaining;
/// The form's description field. Supplied by the screen.
TextEditingController get descController;
/// The form's macro fields. Supplied by the screen.
MacroControllers get macroControllers;
/// Called after the form is filled, so the screen can mark the source.
void onDishPrefilled() {}
/// Fills the form's fields from [dish].
///
/// Concrete here rather than an abstract hook: every implementation would be
/// the same three lines, and the screen file has no budget to spare.
void fillFormFromDish(KuchniaDish dish) {
fillControllersFromDish(dish, descController, macroControllers);
onDishPrefilled();
}
/// Loads today's delivery, guarded so it costs at most one walk per day.
///
/// Goes through [KuchniaQueueService.refreshOnce] rather than
/// `refreshDelivery`: this is an *automatic* trigger and can fire after
/// every meal, and each unguarded refresh is a login plus three requests
/// against a third party. The settings button is the explicit ask that
/// always goes and looks.
Future<void> loadDeliveryOnce({Set<String> alreadyLogged = const {}}) async {
if (!KuchniaQueueService.isInitialized) return;
final result = await KuchniaQueueService.refreshOnce(DateTime.now());
if (!mounted || result.dishes.isEmpty) return;
// Ordered by the caterer's own meal priority, against the *user's*
// schedule -- not a hardcoded four slots. A dish offered for a slot the
// user's schedule does not have is a checkpoint that can never be met.
final ordered = dishesInSlotOrder(
result.dishes,
daySlots(MealScheduleService.current),
);
KuchniaQueueService.instance.offer(ordered, alreadyLogged: alreadyLogged);
prefillNextDish();
}
/// Loads today's delivery, skipping dishes already logged today.
///
/// The skip matters across devices: a dish logged on the PC must not be
/// offered again here, and the food log is the only record of that.
Future<void> loadTodaysDelivery() async {
final logged = await LogStorageService.instance.todayEntries();
if (!mounted) return;
await loadDeliveryOnce(
alreadyLogged: {
for (final entry in logged) entry.desc.trim().toLowerCase(),
},
);
}
/// Loads today's delivery on an **explicit** user tap, unguarded.
///
/// Deliberately [refreshDelivery], not [KuchniaQueueService.refreshOnce]:
/// per `docs/kuchnia-wikinga.md`'s Triggers table, a user who asks gets a
/// look, the same as the CLI and the settings button. The guard exists to
/// rate-limit *automatic* triggers, and applying it here would make the
/// button silently do nothing for the rest of the day after the startup
/// load — the failure that has nothing to tap in the kitchen.
///
/// Still skips dishes already logged today (a dish logged on the PC must
/// not be re-offered) and still records the fetch, so a successful tap
/// also spares the automatic path a second walk.
///
/// Returns the cue to show (a spoken line, a glyph kind and a dish count),
/// or null when a dish was prefilled and the form speaks for itself.
Future<CountCue?> loadDeliveryOnTap() async {
if (!KuchniaQueueService.isInitialized) {
return _cue('Catering is not ready yet.', CueKind.warn);
}
final logged = await LogStorageService.instance.todayEntries();
if (!mounted) return null;
final result = await refreshDelivery(DateTime.now());
if (!mounted) return null;
if (!result.ok) return _cue(result.reason!, CueKind.error);
if (result.dishes.isEmpty) {
return _cue('No delivery today.', CueKind.warn, 0);
}
await KuchniaQueueService.instance.recordFetched(DateTime.now());
if (!mounted) return null;
final ordered = dishesInSlotOrder(
result.dishes,
daySlots(MealScheduleService.current),
);
KuchniaQueueService.instance.offer(
ordered,
alreadyLogged: {
for (final entry in logged) entry.desc.trim().toLowerCase(),
},
);
if (KuchniaQueueService.next == null) {
return _cue('All delivered dishes are already logged.', CueKind.ok, 0);
}
prefillNextDish();
return null;
}
/// Whether an explicit delivery fetch is in flight.
///
/// Only guards against a double tap opening two logins at once -- it is not
/// the daily guard, which an explicit tap deliberately bypasses.
bool deliveryBusy = false;
/// Runs [loadDeliveryOnTap] and shows its outcome as a SnackBar.
///
/// Lives here rather than on the screen because `log_meal_screen.dart` is at
/// the 250-line cap, and this is the mixin's own behaviour anyway.
Future<void> loadDeliveryAndReport() async {
setState(() => deliveryBusy = true);
CountCue? cue;
try {
cue = await loadDeliveryOnTap();
} finally {
if (mounted) setState(() => deliveryBusy = false);
}
if (!mounted || cue == null) return;
// The outcome sentence stays as the spoken label; the snackbar paints
// the dish glyph in the kind's tint plus the count (0 = none to log).
showCueSnack(
context,
kind: cue.kind,
semanticLabel: cue.label,
icon: Icons.restaurant,
count: cue.count,
);
}
/// Prefills the form with the next queued dish, if there is one.
///
/// Safe to call when the queue is empty: it simply clears the offer.
void prefillNextDish() {
final dish = KuchniaQueueService.next;
if (dish == null) {
if (offeredDish != null) setState(() => offeredDish = null);
return;
}
setState(() => offeredDish = dish);
fillFormFromDish(dish);
}
/// Drops the just-logged dish and immediately offers the next one.
///
/// Call this from the submit handler *after* the entry is written. This is
/// the second caller that keeps the queue alive across a submit.
void advanceQueueAfterLog(String loggedDesc) {
final dish = offeredDish;
if (dish == null) return;
if (dish.name.trim().toLowerCase() != loggedDesc.trim().toLowerCase()) {
// The user edited the description into something else, so the offered
// dish was not what they logged. Leave it queued rather than silently
// marking a dish eaten that never was.
return;
}
KuchniaQueueService.instance.markLogged(dish);
offeredDish = null;
prefillNextDish();
}
/// A short line naming what is still queued, or null when nothing is.
///
/// The leftover matters: the caterer's five meals against four default slots
/// means at least one dish is still queued when the last slot is logged. It
/// is already banked, so it is named rather than dropped silently.
String? get queueStatusLine {
final left = dishesStillQueued;
if (left <= 0) return null;
return '$left more delivered ${left == 1 ? 'dish' : 'dishes'} to log.';
}
}

View File

@ -0,0 +1,74 @@
/// The meals the screen logged for the user, shown below the action row with
/// an undo, plus the catering auto-log that fills the first of them.
///
/// The rows stay until the next meal is logged. Undo tombstones that one entry
/// by id (`deleteEntry`, never `undoLastToday`: several rows can be on screen,
/// and an auto-logged dish is not necessarily the newest entry), so the
/// deterministic catering id keeps blocking a re-log on the next open.
library;
import 'dart:async';
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
import 'package:diet_guard_app/services/kuchnia_autolog.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/widgets/logged_meal_row.dart';
import 'package:material_ui/material_ui.dart';
/// Logged-meal rows, undo and the catering auto-log.
mixin LogMealLoggedMixin<T extends StatefulWidget>
on LogMealSyncMixin<T>, LogMealDueMixin<T> {
/// The rows under the action row, oldest first.
List<LoggedMeal> loggedRows = const [];
/// Replaces the rows with [meals]: a new log retires the previous ones.
void showLogged(List<LoggedMeal> meals) {
if (mounted) setState(() => loggedRows = meals);
}
/// Tombstones [meal]'s entry, drops its row and republishes.
Future<void> undoLogged(LoggedMeal meal) async {
final id = meal.entry.id;
if (id == null) return;
setState(() => loggedRows = [...loggedRows]..remove(meal));
await LogStorageService.instance.deleteEntry(id);
await publishAfterLog();
await refreshSlots();
}
/// Logs the delivered dishes of the due slots, no tap needed.
///
/// The old rule "a delivered meal is not an eaten meal" was overridden by
/// kuhy on 2026-11-17 ("LOG EVEN WITHOUT TAP"). Safe to call repeatedly: the
/// ids are deterministic (see `kuchnia_autolog.dart`).
Future<void> autoLogCatering() async {
if (!dueMode) return;
final entries = await KuchniaAutoLog.instance.logDue(dueSlots);
if (!mounted || entries.isEmpty) return;
showLogged([for (final e in entries) LoggedMeal(e, LoggedOrigin.catering)]);
await publishAfterLog();
await refreshSlots();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// A resume does what an open does, with one sync (autoSync is
// single-flight, so calling super too would let the auto-log run before
// the pull finished). Pause still pushes through the sync mixin.
if (state == AppLifecycleState.resumed) {
unawaited(onOpenedOrResumed());
return;
}
super.didChangeAppLifecycleState(state);
}
/// What a fresh open or a resume does: show the screen from the local log,
/// pull what other devices logged, then auto-log what is still due.
Future<void> onOpenedOrResumed() async {
unawaited(refreshSlots());
await autoSync();
await refreshSlots();
await autoLogCatering();
}
}

View File

@ -1,44 +1,54 @@
/// Single-food meal logging screen -- the app's primary, done-criterion
/// screen: "I can open the diet app on my phone and fill meal I ate."
///
/// Two modes. **Due mode** (a slot elapsed with nothing logged) shows only
/// what logging needs: the food field, suggestions, macros and the action row,
/// with the status bar hidden. **Normal mode** adds the app bar, the sync
/// banner and the date row. Either way the action row is photo / Claude /
/// log, and the field never moves between states.
library;
import 'dart:async';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/food_suggestion.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/screens/log_meal_actions.dart';
import 'package:diet_guard_app/screens/log_meal_fill_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_claude_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_kuchnia_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_logged_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_nav_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_progress.dart';
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
import 'package:diet_guard_app/services/claude_relay_client.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_feedback.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/services/meal_photo_source.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
import 'package:diet_guard_app/widgets/fill_all_row.dart';
import 'package:diet_guard_app/widgets/log_meal_actions_row.dart';
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:diet_guard_app/widgets/sync_health_banner.dart';
import 'package:diet_guard_app/widgets/today_progress_card.dart';
import 'package:http/http.dart' as http;
import 'package:material_ui/material_ui.dart';
/// Lets the user log one food item, with food-bank autocomplete and
/// today's slot status.
/// Lets the user log one food item, with food-bank autocomplete.
class LogMealScreen extends StatefulWidget {
/// Creates a [LogMealScreen].
const LogMealScreen({super.key, this.httpClient});
const LogMealScreen({super.key, this.httpClient, this.relay, this.photos});
/// Injectable HTTP client for auto-sync; tests pass a [MockClient].
/// Production leaves this null so [GitHubClient] builds a real one.
final http.Client? httpClient;
/// Where the sparkle button sends; the app-wide [claudeRelay] when null.
final ClaudeRelayClient? relay;
/// Where photos come from; the camera/gallery picker when null.
final MealPhotoSource? photos;
@override
State<LogMealScreen> createState() => _LogMealScreenState();
}
@ -47,66 +57,59 @@ class _LogMealScreenState extends State<LogMealScreen>
with
WidgetsBindingObserver,
LogMealSyncMixin<LogMealScreen>,
LogMealDueMixin<LogMealScreen>,
LogMealLoggedMixin<LogMealScreen>,
LogMealNavMixin<LogMealScreen>,
LogMealKuchniaMixin<LogMealScreen>,
LogMealFutureMixin<LogMealScreen>,
LogMealFillMixin<LogMealScreen> {
LogMealClaudeMixin<LogMealScreen> {
@override
http.Client? get syncHttpClient => widget.httpClient;
@override
ClaudeRelayClient get relay => widget.relay ?? claudeRelay;
@override
late final MealPhotoSource photoSource =
widget.photos ?? ImagePickerPhotoSource();
final TextEditingController _descController = TextEditingController();
final MacroControllers _macros = MacroControllers();
List<FoodSuggestion> _suggestions = const [];
@override
int? selectedSlot;
TextEditingController get claudeDesc => _descController;
@override
MacroControllers get claudeMacros => _macros;
List<FoodSuggestion> _suggestions = const [];
String _source = 'manual';
CueState? _cue; // painted as a tinted icon, never as text
TodayProgress? _progress;
void _setCue(CueKind kind, String? label, [int? count]) {
_cue = label == null ? null : CueState.next(_cue, kind, label, count);
_progress = null;
}
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_descController.addListener(_onDescChanged);
_macros.addListenerToAll(_onMacroEdited);
selectedSlot = slotForLog(DateTime.now(), MealScheduleService.current);
unawaited(refreshSlots());
unawaited(_onDescChanged());
// Read health before the first sync finishes, so a device that stalled in
// a previous session says so immediately rather than only after a tick.
// Health first, so a device that stalled earlier says so before a tick.
unawaited(refreshSyncHealth());
unawaited(autoSync());
// After autoSync so a dish already logged on the PC is known before the
// queue is built, and guarded so this costs at most one walk per day.
unawaited(loadTodaysDelivery());
unawaited(onOpenedOrResumed());
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
disposeClaude();
restoreStatusBar();
_descController.dispose();
_macros.dispose();
super.dispose();
}
void _onMacroEdited() {
if (_source == 'food bank') {
setState(() => _source = 'manual');
}
if (_source == 'food bank') setState(() => _source = 'manual');
}
/// Re-runs the food-bank search and dismisses the previous progress card.
///
/// The card is cleared only when the field is non-empty because
/// [_onLogMeal]'s own `clear()` fires this listener too: without the guard
/// the two async chains race and the clear can null the card right after
/// [_onLogMeal] set it, so it never appears on device (in-memory test
/// stores resolve fast enough to hide this).
/// Re-runs the food-bank search and dismisses the previous progress card,
/// only while the field is non-empty: [_onLogMeal]'s own `clear()` fires
/// this listener too, and would otherwise race it and null the new card.
Future<void> _onDescChanged() async {
final matches = await FoodBankService.instance.search(_descController.text);
if (!mounted) return;
@ -116,16 +119,6 @@ class _LogMealScreenState extends State<LogMealScreen>
});
}
@override
TextEditingController get descController => _descController;
@override
MacroControllers get macroControllers => _macros;
@override
void onDishPrefilled() => setState(() => _source = 'catering');
@override
void showFillStatus(FillCue cue) =>
setState(() => _setCue(cue.kind, cue.label, cue.count));
void _onSuggestionSelected(FoodSuggestion suggestion) {
fillControllersFromSuggestion(suggestion, _descController, _macros);
setState(() {
@ -136,17 +129,14 @@ class _LogMealScreenState extends State<LogMealScreen>
Future<void> _onLogMeal() async {
final desc = _descController.text.trim();
if (desc.isEmpty) {
setState(() => _setCue(CueKind.error, 'Type what you ate first.'));
return;
}
final target = resolveLogTarget(selectedSlot);
if (desc.isEmpty) return;
final target = resolveLogTarget(targetSlot);
if (target.error != null) {
setState(() => _setCue(CueKind.error, target.error));
setState(() => _cue = CueState.next(_cue, CueKind.error, target.error!));
return;
}
// On the tap, before the write/sync: waiting for them is just latency.
LogFeedback.mealLogged();
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),
@ -160,89 +150,99 @@ class _LogMealScreenState extends State<LogMealScreen>
_macros.clear();
setState(() {
_source = 'manual';
selectedSlot = slotForLog(DateTime.now(), MealScheduleService.current);
photo = null; // else a stale photo keeps the sparkle lit
claudeState = ClaudeButtonState.idle;
});
await refreshSlots();
if (!mounted) return;
// The second `prefillNextDish` caller. Without it every dish after the
// first stays queued behind another tap and the "N more to log" line
// becomes a dead letter -- the exact regression the PC gate once shipped.
advanceQueueAfterLog(desc);
showLogged([LoggedMeal(entry, LoggedOrigin.local)]);
setState(() {
_setCue(CueKind.info, queueStatusLine);
_cue = null;
_progress = buildTodayProgress(log, logged: entry);
});
}
@override
Widget build(BuildContext context) {
if (!slotsLoaded) return const Scaffold();
final due = dueMode;
// Dimmed while Claude works, but never moved: nothing is added around it.
final busy = claudeState == ClaudeButtonState.sending;
final dim = busy || claudeState == ClaudeButtonState.queued;
return Scaffold(
appBar: AppBar(
// No title: the app's identity is the launcher icon, and the five
// destination glyphs fill the bar.
actions: [
...logMealAppBarActions(
onFoodBank: onOpenFoodBank,
onHistory: onOpenHistory,
onCalendar: onOpenCalendar,
onSettings: onOpenSettings,
onBody: onOpenBody,
appBar: due
? null
: AppBar(
actions: logMealAppBarActions(
onFoodBank: onOpenFoodBank,
onHistory: onOpenHistory,
onCalendar: onOpenCalendar,
onSettings: onOpenSettings,
onBody: onOpenBody,
),
),
body: SafeArea(
child: SingleChildScrollView(
padding: const EdgeInsets.all(AppSpacing.md),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (!due) ...[
SyncHealthBanner(status: syncHealth),
buildWhenRow(context),
const SizedBox(height: AppSpacing.sm),
],
buildSlotRow(),
Opacity(
opacity: dim ? 0.5 : 1,
child: IgnorePointer(
ignoring: busy,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
IconField(
controller: _descController,
icon: Icons.fastfood,
semanticLabel: 'What did you eat?',
onChanged: (_) => setState(() {}),
),
AutocompleteSuggestionList(
suggestions: _suggestions,
onSelected: _onSuggestionSelected,
compact: true,
compactLimit: due ? 2 : 3,
reserveHeight: due,
),
const SizedBox(height: AppSpacing.sm),
MacroInputRow(controllers: _macros, compact: true),
],
),
),
),
const SizedBox(height: AppSpacing.sm),
MealActionRow(
claude: claudeState,
photoAttached: photo != null,
canSend: canSend,
canLog: _descController.text.trim().isNotEmpty,
onPhoto: () => unawaited(attachPhoto(PhotoOrigin.camera)),
onGallery: () => unawaited(attachPhoto(PhotoOrigin.gallery)),
onRemovePhoto: removePhoto,
onSend: sendToClaude,
onLog: _onLogMeal,
),
for (final meal in loggedRows)
LoggedMealRow(meal: meal, onUndo: () => undoLogged(meal)),
if (_cue != null) ...[
const SizedBox(height: AppSpacing.sm),
_cue!.widget,
],
if (_progress != null && !due) ...[
const SizedBox(height: AppSpacing.sm),
TodayProgressCard(progress: _progress!),
],
],
),
],
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(AppSpacing.md),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SyncHealthBanner(status: syncHealth),
buildWhenRow(context),
const SizedBox(height: 8),
buildSlotRow(
loggedSlots: loggedSlots,
selectedSlot: selectedSlot,
onTodaySlotSelected: (slot) =>
setState(() => selectedSlot = slot),
),
const SizedBox(height: 8),
IconField(
controller: _descController,
icon: Icons.fastfood,
semanticLabel: 'What did you eat?',
),
AutocompleteSuggestionList(
suggestions: _suggestions,
onSelected: _onSuggestionSelected,
compact: true,
),
const SizedBox(height: 8),
MacroInputRow(controllers: _macros, compact: true),
const SizedBox(height: 8),
LogMealActionsRow(
onLoadDelivery: loadDeliveryAndReport,
onLog: _onLogMeal,
deliveryBusy: deliveryBusy,
dishesQueued: dishesStillQueued,
),
const SizedBox(height: AppSpacing.sm),
FillAllRow(
onFill: onFillAll,
onCancel: onFillCancel,
busy: fillFlow.busy || deliveryBusy,
armedCount: fillFlow.armedCount,
),
// Mutually exclusive: _cue carries a validation complaint or
// queue note, _progress the post-log summary; the two may stack
// only after a log that leaves dishes queued.
if (_cue != null) ...[
const SizedBox(height: AppSpacing.sm),
_cue!.widget,
],
if (_progress != null) ...[
const SizedBox(height: AppSpacing.sm),
TodayProgressCard(progress: _progress!),
],
],
),
),
);

View File

@ -1,7 +1,6 @@
import 'dart:async';
import 'dart:developer';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/background_tasks.dart';
import 'package:diet_guard_app/services/due_slot_check.dart';
import 'package:diet_guard_app/services/firebase_client.dart';
@ -9,7 +8,6 @@ import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/health_steps.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/services/sync_health.dart';
import 'package:diet_guard_app/services/sync_service.dart';
import 'package:diet_guard_app/services/sync_settings.dart';
@ -35,12 +33,6 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
/// The slots that already carry a logged meal today.
Set<int> loggedSlots = {};
/// The slot the screen is currently logging for.
///
/// Owned by the screen's own state; declared here so
/// [onScheduleMayHaveChanged] can re-derive it when the schedule changes.
abstract int? selectedSlot;
/// The screen's injected HTTP client, or null to use the default.
///
/// Declared abstract so the mixin stays independent of the widget's own
@ -174,21 +166,12 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
setState(() => loggedSlots = logged);
}
/// Rebuilds the slot row after the settings screen pops.
/// Re-derives the due slots after the settings screen pops.
///
/// The meal-schedule editor lives in settings, and [SlotSelectorRow] reads
/// `MealScheduleService.current` at build time, so refreshing is enough to
/// re-derive the row -- but the selected slot also has to be recomputed,
/// since the minute it referred to may no longer be a checkpoint at all.
///
/// Found on the phone: without this the settings preview and the overdue
/// reminder both updated while the row behind them kept the old four
/// checkpoints until the app was restarted.
Future<void> onScheduleMayHaveChanged() async {
await refreshSlots();
if (!mounted) return;
setState(() {
selectedSlot = slotForLog(DateTime.now(), MealScheduleService.current);
});
}
/// The meal-schedule editor lives in settings, and which slots are due (and
/// so whether the screen is in due mode) reads `MealScheduleService.current`
/// at refresh time. Found on the phone: without this the settings preview
/// and the overdue reminder both updated while the screen behind them kept
/// the old checkpoints until the app was restarted.
Future<void> onScheduleMayHaveChanged() => refreshSlots();
}

View File

@ -40,9 +40,9 @@ class FetchOutcome {
/// Fetches today's delivery and reports what was banked.
///
/// Deliberately "banked", not "logged": a delivered meal is not an eaten
/// meal, so the dishes land in the food bank and the user still taps to log
/// each one. Top-level so the settings screen can pass it without growing.
/// Deliberately "banked", not "logged": the explicit fetch only fills the
/// food bank; logging is the log screen's auto-log (`kuchnia_autolog.dart`).
/// Top-level so the settings screen can pass it without growing.
Future<FetchOutcome> fetchTodaysDelivery() async {
final result = await refreshDelivery(DateTime.now());
if (!result.ok) return FetchOutcome(CueKind.error, result.reason!);

View File

@ -0,0 +1,156 @@
/// The phone's side of the Claude relay: what the sparkle button sends and
/// what comes back.
///
/// 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 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_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<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.
class ClaudeRelayRequest {
/// Creates a request; at least one of [text] and [photoJpeg] is non-empty.
const ClaudeRelayRequest({
required this.requestId,
required this.slotMinute,
this.mode = ClaudeRelayMode.normal,
this.text = '',
this.photoJpeg,
});
/// A ULID (see [newRequestId]); the entry id is [claudeEntryId] of it.
final String requestId;
/// 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;
/// The photo as a JPEG of at most 1024 px, or null.
final Uint8List? photoJpeg;
}
/// What the relay reports about one [ClaudeRelayRequest].
sealed class ClaudeRelayEvent {
const ClaudeRelayEvent();
}
/// The PC is offline; the request is stored and will run later (not terminal).
final class ClaudeRelayQueued extends ClaudeRelayEvent {
/// Creates the event.
const ClaudeRelayQueued();
}
/// Claude logged the meal (terminal). `entry.id == claudeEntryId(rid)`.
final class ClaudeRelayLogged extends ClaudeRelayEvent {
/// Creates the event for [entry].
const ClaudeRelayLogged(this.entry);
/// The entry the worker wrote.
final FoodEntry entry;
}
/// Sync is locked (no passphrase), so nothing can be sent (terminal).
final class ClaudeRelayLocked extends ClaudeRelayEvent {
/// Creates the event.
const ClaudeRelayLocked();
}
/// The send failed (terminal); [reason] is for logs, never painted.
final class ClaudeRelayFailed extends ClaudeRelayEvent {
/// Creates the event.
const ClaudeRelayFailed(this.reason);
/// Why it failed.
final String reason;
}
/// Sends a meal to Claude through the relay.
abstract interface class ClaudeRelayClient {
/// Sends [request]; the stream carries zero or more [ClaudeRelayQueued]
/// then one terminal event, and never throws (failures are events).
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.
class UnconfiguredClaudeRelayClient implements ClaudeRelayClient {
/// Creates the stand-in.
const UnconfiguredClaudeRelayClient();
@override
Stream<ClaudeRelayEvent> send(ClaudeRelayRequest request) =>
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
/// real transport.
ClaudeRelayClient claudeRelay = const UnconfiguredClaudeRelayClient();

View File

@ -0,0 +1,49 @@
/// A controllable [ClaudeRelayClient] for tests and the unwired app.
library;
import 'dart:async';
import 'package:diet_guard_app/services/claude_relay_client.dart';
/// Records every request and lets the test emit the events by hand.
///
/// [emit] pushes to the most recent send's stream; a terminal event closes it,
/// as a real client's would.
class FakeClaudeRelayClient implements ClaudeRelayClient {
/// Every request sent, oldest first.
final List<ClaudeRelayRequest> sent = [];
/// Events replayed on each send before the stream waits for [emit].
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;
@override
Stream<ClaudeRelayEvent> send(ClaudeRelayRequest request) {
sent.add(request);
final controller = StreamController<ClaudeRelayEvent>();
_open = controller;
script.forEach(emit);
return controller.stream;
}
/// Delivers [event] to the open stream; a terminal one closes it.
void emit(ClaudeRelayEvent event) {
final controller = _open;
if (controller == null || controller.isClosed) return;
controller.add(event);
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

@ -0,0 +1,107 @@
/// Logs the delivered catering dishes of the due slots, without a tap.
///
/// kuhy overrode the old "delivered is not eaten, so never log unattended"
/// rule on 2026-11-17 ("LOG EVEN WITHOUT TAP"). The screen calls [logDue] when
/// it opens or resumes with a slot due; the plan is the fill-all plan
/// (`assignSlots` by the caterer's `mealPriority`, `fillPlan` over occupied
/// slots) minus the confirm tap, restricted to the due slots.
///
/// **Ids are deterministic** so a repeat open and every other device collapse
/// to one entry on merge: UUID v5 over the RFC 4122 URL namespace of
/// `kuchnia:<delivery date YYYY-MM-DD>:<dish key>`. The shared fixture
/// `tests/fixtures/kuchnia_autolog_ids.json` pins them for both languages.
/// An undone dish keeps its tombstone, so it is never logged a second time.
///
/// The fetch is a third-party login, so the day's dishes are cached in memory
/// and a failed or empty fetch is retried at most every [retryAfter].
/// `KuchniaQueueService.refreshOnce` cannot serve here: after the first clean
/// fetch of the day it returns nothing, and slots that fall due later would
/// never see their dish.
library;
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/kuchnia_fill.dart';
import 'package:diet_guard_app/services/kuchnia_fill_flow.dart';
import 'package:diet_guard_app/services/kuchnia_import.dart';
import 'package:diet_guard_app/services/kuchnia_spread.dart';
import 'package:diet_guard_app/services/log_entry_lookup.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:uuid/uuid.dart';
/// The id of the entry that logs [dish] for [deliveryDate] (`YYYY-MM-DD`).
String kuchniaAutologId(String deliveryDate, KuchniaDish dish) => const Uuid()
.v5(Namespace.url.value, 'kuchnia:$deliveryDate:${dish.autologKey}');
/// Logs delivered dishes for due slots. One per process is plenty.
class KuchniaAutoLog {
/// Creates the service; every dependency is injectable for tests.
KuchniaAutoLog({
DeliveryFetch? fetch,
DateTime Function()? now,
this.retryAfter = const Duration(minutes: 10),
}) : _fetch = fetch ?? refreshDelivery,
_now = now ?? DateTime.now;
/// The process-wide instance the screen uses.
static KuchniaAutoLog instance = KuchniaAutoLog();
/// Minimum gap between fetches that found nothing or failed.
final Duration retryAfter;
final DeliveryFetch _fetch;
final DateTime Function() _now;
String? _cachedDay;
List<KuchniaDish> _cachedDishes = const [];
DateTime? _lastEmptyFetch;
Future<List<FoodEntry>>? _inFlight;
/// Forgets the cache, so the next call fetches again (tests, day change).
@visibleForTesting
void reset() {
_cachedDay = null;
_cachedDishes = const [];
_lastEmptyFetch = null;
}
/// Logs the dishes assigned to [dueSlots]; returns the entries it wrote.
///
/// Single-flight: a second call while one runs joins it, so an open and a
/// resume racing each other cannot interleave two read-modify-writes.
Future<List<FoodEntry>> logDue(List<int> dueSlots) =>
_inFlight ??= _run(dueSlots).whenComplete(() => _inFlight = null);
Future<List<FoodEntry>> _run(List<int> dueSlots) async {
if (dueSlots.isEmpty) return const [];
final today = _now();
final dayKey = localDateKey(today);
final dishes = await _dishesFor(today, dayKey);
if (dishes.isEmpty) return const [];
final store = LogStorageService.instance;
final slots = daySlots(MealScheduleService.history.forDay(dayKey));
final plan = fillPlan(
assignSlots(dishes, slots),
await loggedSlotsOn(store, today),
).where((item) => dueSlots.contains(item.slot)).toList();
String idFor(SlottedDish item) => kuchniaAutologId(dayKey, item.dish);
final written = await logDishes(plan, storage: store, idFor: idFor);
return [for (final item in written) ?await store.findEntry(idFor(item))];
}
Future<List<KuchniaDish>> _dishesFor(DateTime today, String dayKey) async {
if (_cachedDay == dayKey) return _cachedDishes;
final last = _lastEmptyFetch;
if (last != null && _now().difference(last) < retryAfter) return const [];
final result = await _fetch(today);
if (result.ok && result.dishes.isNotEmpty) {
_cachedDay = dayKey;
return _cachedDishes = result.dishes;
}
_lastEmptyFetch = _now();
return const [];
}
}

View File

@ -3,10 +3,12 @@
/// The Dart mirror of `diet_guard/_kuchnia_log.py`'s `fill_plan` and
/// `log_dishes`. KEEP IN SYNC, gated by the shared parity fixture.
///
/// **Nothing here runs without an explicit confirm tap.** A delivered meal is
/// not an eaten meal: logging unattended would let the delivery note satisfy
/// the very checkpoints the gate exists to enforce. [logDishes] is only ever
/// reached from the second tap of `FillAllFlow`.
/// **Delivered counts as eaten (override, 2026-11-17).** The old rule was "a
/// delivered meal is not an eaten meal, so nothing logs without a confirm
/// tap". kuhy overrode it ("LOG EVEN WITHOUT TAP"): [logDishes] is now also
/// reached unattended from `kuchnia_autolog.dart`, which logs the dishes of the
/// slots that are due when the app opens. Every such entry has a deterministic
/// id and shows an undo row, so a skipped or binned meal is one tap to remove.
library;
import 'package:diet_guard_app/models/food_entry.dart';
@ -15,6 +17,7 @@ import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/kuchnia_spread.dart';
import 'package:diet_guard_app/services/log_entry_lookup.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
@ -98,25 +101,34 @@ Future<Set<int>> loggedSlotsOn(LogStorageService store, DateTime day) async {
/// (a "Log for later" date, strictly after today) each dish is stamped at its
/// slot's time on that day; without it, now -- as a manual log is.
///
/// [idFor] gives each dish a deterministic entry id (see
/// `kuchniaAutologId`); a dish whose id is already in the log is skipped.
///
/// Returns the dishes actually written, in order.
Future<List<SlottedDish>> logDishes(
List<SlottedDish> chosen, {
LogStorageService? storage,
DateTime? day,
String Function(SlottedDish item)? idFor,
}) async {
final store = storage ?? LogStorageService.instance;
final seen = {
for (final entry in await dayEntries(store, day))
_dedupKey(entry.desc, entry.slotMinute),
};
// Tombstones included: an undone auto-logged dish must stay undone.
final knownIds = idFor == null ? const <String>{} : await store.allEntryIds();
final written = <SlottedDish>[];
for (final item in chosen) {
final id = idFor?.call(item);
if (id != null && knownIds.contains(id)) continue;
final key = _dedupKey(item.dish.name, item.slot);
if (!seen.add(key)) continue;
await store.logMeal(
item.dish.name,
dishNutrition(item.dish),
slotMinute: item.slot,
id: id,
when: day == null
? null
: DateTime(

View File

@ -4,12 +4,10 @@
/// fail-closed boundary: every [KuchniaError] is turned into a reason string
/// here, so no caller can be broken by a catering outage.
///
/// **Nothing is ever logged from here.** A delivered meal is not an eaten
/// meal: dishes land in the *curated* bank and the user still taps to log
/// each one. If the import logged automatically, the gate would satisfy its
/// own checkpoint from a delivery note, and the log would record what the
/// courier dropped off rather than what was eaten -- skipped, shared and
/// binned meals included.
/// **Nothing is logged from here: this only banks.** Dishes land in the
/// *curated* bank. Logging them is `kuchnia_autolog.dart`'s job, which kuhy
/// allowed without a tap on 2026-11-17 ("LOG EVEN WITHOUT TAP"; it was
/// "delivered is not eaten" before), under deterministic ids with an undo.
///
/// Imports go **only** to the curated bank. The derived bank is rebuilt from
/// the log on every meal, so anything written there would vanish at the next

View File

@ -74,6 +74,15 @@ bool energyIsConsistent(double kcal, double protein, double carbs, double fat) {
return (derived - kcal).abs() <= kuchniaEnergyTolerance * kcal;
}
/// The panel's meal id as a string, or '' when absent or not a string/int.
///
/// A bool is not an id; Dart's `is int` already excludes it, matching Python.
String _mealId(Object? raw) {
if (raw is int) return raw.toString();
if (raw is String) return raw.trim();
return '';
}
/// Builds one dish, or null when the entry is unusable.
///
/// [fallbackPriority] is the 1-based payload position, used when
@ -113,6 +122,7 @@ KuchniaDish? parseMeal(Object? meal, int fallbackPriority) {
grams: grams,
priority: priority,
slotLabel: rawLabel is String ? rawLabel.trim() : '',
dishId: _mealId(meal['deliveryMealId']),
);
}

View File

@ -1,10 +1,10 @@
/// The day's delivered dishes, offered to the log form one at a time.
///
/// **A delivered meal is not an eaten meal.** This queue only ever *prefills*
/// the form; the user still taps to log each dish. Nothing here writes a log
/// entry, and nothing here may start doing so -- the gate would then satisfy
/// its own checkpoint from a delivery note, and the log would record what the
/// courier dropped off rather than what was eaten.
/// **Since 2026-11-17 the log screen no longer prefills from this queue**: a
/// delivered dish logs itself when its slot is due (`kuchnia_autolog.dart`;
/// kuhy overrode "delivered is not eaten", "LOG EVEN WITHOUT TAP"). What
/// remains here is the offer/mark bookkeeping and the fetched-today marker.
/// The queue itself still writes no log entry.
///
/// Two things are load-bearing:
///

View File

@ -0,0 +1,55 @@
/// Id lookups over the food log, tombstones included.
///
/// Split out of `log_storage_service.dart` for the repo's 250-line cap.
library;
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
/// Returns the entry with [id] anywhere in [log], deleted or not, else null.
///
/// Tombstones count on purpose: an entry the user undid must keep blocking
/// its own id, or a repeat open would log it again.
FoodEntry? findEntryById(DayLog log, String id) {
for (final entries in log.values) {
for (final entry in entries) {
if (entry.id == id) return entry;
}
}
return null;
}
/// Id-keyed writes and reads on [LogStorageService].
extension LogEntryLookup on LogStorageService {
/// The entry with [id], deleted or not, else null.
Future<FoodEntry?> findEntry(String id) async =>
findEntryById(await readLog(), id);
/// Every id in the log, tombstones included.
Future<Set<String>> allEntryIds() async => {
for (final entries in (await readLog()).values)
for (final entry in entries) ?entry.id,
};
/// Adds [entry] unless one with its id exists (live or tombstoned), and
/// returns whichever copy the log holds.
///
/// For an entry another device wrote under an id chosen here, such as a
/// Claude-logged meal: the sync merge delivers the same record, so this only
/// shows it a tick earlier and can never double it.
Future<FoodEntry> addIfAbsent(FoodEntry entry) async {
final log = await readLog();
final id = entry.id;
if (id != null) {
final existing = findEntryById(log, id);
if (existing != null) return existing;
}
final dayKey = entry.time.length >= 10
? entry.time.substring(0, 10)
: localDateKey(DateTime.now());
log.putIfAbsent(dayKey, () => []).add(entry);
await writeLog(log);
return entry;
}
}

View File

@ -10,6 +10,7 @@ import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/document_store_factory.dart';
import 'package:diet_guard_app/services/log_entry_lookup.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:flutter/foundation.dart';
import 'package:uuid/uuid.dart';
@ -39,10 +40,8 @@ class LogStorageService {
final DocumentStore _store;
/// Initializes the singleton against the platform document store: files in
/// the app's documents directory on Android (phone-sandboxed; no
/// external-storage permission needed), IndexedDB in the browser-hosted
/// desktop app.
/// Initializes the singleton against the platform document store (files on
/// Android, IndexedDB in the browser-hosted desktop app).
static Future<LogStorageService> init() async {
if (_instance != null) return _instance!;
final svc = LogStorageService._(await openDocumentStore());
@ -88,8 +87,7 @@ class LogStorageService {
/// Persists the full log to the store, mirroring `_state._write_log`.
///
/// Atomicity against a concurrent reader is the store's job (see
/// `FileDocumentStore.write`'s temp-file-and-rename), not this method's.
/// Atomicity against a concurrent reader is the store's job.
Future<void> writeLog(DayLog log) async {
final encoded = <String, Object?>{
for (final mapEntry in log.entries)
@ -98,27 +96,34 @@ class LogStorageService {
await _store.write(documentName, jsonEncode(encoded));
}
/// Appends a signed-on-PC-eventually entry for [desc] to [when]'s day (or
/// today's, when [when] is null).
/// Appends an entry for [desc] to [when]'s day (today's when null).
///
/// Mirrors `_state.log_meal`: always assigns a fresh `id`, never computes
/// an `hmac` (the phone never holds the shared key -- the PC re-signs on
/// merge, see Milestone 3). [when] lets a caller pre-log a meal against a
/// future date/slot; must not be in the past. [slotMinute] is the slot's
/// minute of day (`slotForLog`'s result), never an hour.
/// Mirrors `_state.log_meal`: never computes an `hmac` (the phone never
/// holds the key; the PC re-signs on merge). [when] pre-logs a future
/// date/slot and must not be in the past. [slotMinute] is a minute of day
/// (`slotForLog`'s result), never an hour.
///
/// A caller-chosen [id] makes the write idempotent: an entry already
/// carrying it (live or tombstoned) is returned and nothing is written.
Future<FoodEntry> logMeal(
String desc,
Nutrition nutrition, {
int? slotMinute,
List<MealComponent>? components,
DateTime? when,
String? id,
}) async {
if (when != null && when.isBefore(DateTime.now())) {
throw ArgumentError.value(when, 'when', 'cannot log a meal in the past');
}
final now = when ?? DateTime.now();
final log = await readLog();
if (id != null) {
final existing = findEntryById(log, id);
if (existing != null) return existing;
}
final entry = FoodEntry(
id: const Uuid().v4(),
id: id ?? const Uuid().v4(),
time: isoLocalSeconds(now),
desc: desc,
grams: nutrition.grams,
@ -130,7 +135,6 @@ class LogStorageService {
slotMinute: slotMinute,
components: components,
);
final log = await readLog();
log.putIfAbsent(localDateKey(now), () => []).add(entry);
await writeLog(log);
return entry;
@ -165,9 +169,6 @@ class LogStorageService {
}
/// Returns every non-tombstoned entry across all days, newest first.
///
/// Backs the history screen -- the only place that needs to see more than
/// "today".
Future<List<FoodEntry>> allEntriesNewestFirst() async {
final log = await readLog();
final entries =
@ -183,7 +184,7 @@ class LogStorageService {
return entries;
}
/// Returns today's total calories, mirrors `_state.today_total_kcal`.
/// Today's total calories, mirrors `_state.today_total_kcal`.
Future<double> todayTotalKcal() async {
final entries = await todayEntries();
var total = 0.0;

View File

@ -0,0 +1,8 @@
/// Deletes the cache file `image_picker` leaves behind.
///
/// `dart:io` stays behind the platform seam (see `repo_invariants_test.dart`):
/// the io half deletes, the web half has no file to delete.
library;
export 'meal_photo_cleanup_io.dart'
if (dart.library.js_interop) 'meal_photo_cleanup_web.dart';

View File

@ -0,0 +1,11 @@
import 'dart:io';
/// Deletes the picked file at [path]; a failure is not worth a crash.
Future<void> discardPickedFile(String path) async {
try {
await File(path).delete();
} on FileSystemException {
// Already gone, or not ours to delete: the bytes were read, which is all
// that mattered.
}
}

View File

@ -0,0 +1,2 @@
/// Web has no cache file: the picker returns an in-memory blob.
Future<void> discardPickedFile(String path) async {}

View File

@ -0,0 +1,76 @@
/// Where a meal photo comes from. A photo is transient input to Claude: the
/// bytes live in memory for one send and are never stored, put on a
/// `FoodEntry` or synced.
library;
import 'dart:typed_data';
import 'package:diet_guard_app/services/meal_photo_cleanup.dart';
import 'package:flutter/foundation.dart' show kIsWeb, visibleForTesting;
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
/// Which picker the user asked for.
enum PhotoOrigin {
/// Take a new photo (a tap on the photo button).
camera,
/// Choose an existing one (a long press).
gallery,
}
/// Hands back a photo as JPEG bytes, or null when the user backed out.
abstract interface class MealPhotoSource {
/// Picks one photo from [origin].
Future<Uint8List?> pick(PhotoOrigin origin);
}
/// The longest edge the photo is scaled to before it leaves the phone.
const mealPhotoMaxEdge = 1024.0;
/// [MealPhotoSource] on `image_picker`.
class ImagePickerPhotoSource implements MealPhotoSource {
/// Creates the source; the three seams default to the real plugins.
ImagePickerPhotoSource({
@visibleForTesting Future<XFile?> Function(ImageSource source)? pickFile,
@visibleForTesting Future<bool> Function()? requestCamera,
@visibleForTesting Future<void> Function(String path)? discard,
}) : _pickFile = pickFile ?? _pickWithPlugin,
_requestCamera = requestCamera ?? _requestCameraPermission,
_discard = discard ?? discardPickedFile;
final Future<XFile?> Function(ImageSource source) _pickFile;
final Future<bool> Function() _requestCamera;
final Future<void> Function(String path) _discard;
static Future<XFile?> _pickWithPlugin(ImageSource source) =>
ImagePicker().pickImage(
source: source,
maxWidth: mealPhotoMaxEdge,
maxHeight: mealPhotoMaxEdge,
imageQuality: 85,
);
/// `permission_handler` has no web implementation; the browser asks for
/// the camera itself when the picker opens.
static Future<bool> _requestCameraPermission() async {
if (kIsWeb) return true;
return (await Permission.camera.request()).isGranted;
}
@override
Future<Uint8List?> pick(PhotoOrigin origin) async {
// The runtime permission comes first: launching the camera intent without
// it fails on Android, and the failure names nothing.
if (origin == PhotoOrigin.camera && !await _requestCamera()) return null;
final file = await _pickFile(
origin == PhotoOrigin.camera ? ImageSource.camera : ImageSource.gallery,
);
if (file == null) return null;
final bytes = await file.readAsBytes();
// The plugin leaves the scaled JPEG in the app cache; the bytes are all
// that is needed, so the file goes the moment they are read.
await _discard(file.path);
return bytes;
}
}

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
/// unreachable.
///

View File

@ -26,6 +26,7 @@ class IconField extends StatelessWidget {
this.onSubmitted,
this.autofocus = false,
this.autocorrect = true,
this.fontSize,
super.key,
});
@ -41,6 +42,9 @@ class IconField extends StatelessWidget {
/// Whether the keyboard may autocorrect (false for e-mails and secrets).
final bool autocorrect;
/// Text size of the typed value; the theme's when null.
final double? fontSize;
/// Painted caption.
final IconData icon;
@ -89,6 +93,7 @@ class IconField extends StatelessWidget {
inputFormatters: inputFormatters,
autofocus: autofocus,
autocorrect: autocorrect,
style: fontSize == null ? null : TextStyle(fontSize: fontSize),
enableSuggestions: autocorrect,
decoration: InputDecoration(
prefixIcon: ExcludeSemantics(child: Icon(icon, color: iconColor)),

View File

@ -7,8 +7,8 @@ import 'package:material_ui/material_ui.dart';
/// A tappable list of [FoodSuggestion]s, each filling the form on tap.
///
/// When [compact] is true, only the top 3 suggestions render as compact
/// single-line rows, with a "N more" button opening the full list in a
/// When [compact] is true, only the top [compactLimit] suggestions render as
/// compact single-line rows, with a "N more" button opening the full list in a
/// bottom sheet so nothing becomes unreachable.
class AutocompleteSuggestionList extends StatelessWidget {
/// Creates an [AutocompleteSuggestionList] for [suggestions].
@ -16,6 +16,8 @@ class AutocompleteSuggestionList extends StatelessWidget {
required this.suggestions,
required this.onSelected,
this.compact = false,
this.compactLimit = 3,
this.reserveHeight = false,
super.key,
});
@ -29,7 +31,16 @@ class AutocompleteSuggestionList extends StatelessWidget {
/// of the full unbounded list.
final bool compact;
static const int _compactLimit = 3;
/// How many rows a compact list shows before its "more" button.
final int compactLimit;
/// Whether a compact list always occupies [dueBlockHeight], empty or full,
/// so nothing below it shifts as suggestions come and go (due mode).
final bool reserveHeight;
/// Height of the block that holds a compact list of two rows plus the
/// "more" button; due mode reserves it so nothing below shifts.
static const double dueBlockHeight = 120;
Future<void> _showMore(BuildContext context) async {
await showModalBottomSheet<void>(
@ -48,6 +59,15 @@ class AutocompleteSuggestionList extends StatelessWidget {
@override
Widget build(BuildContext context) {
final list = _list(context);
if (!reserveHeight) return list;
return SizedBox(
height: dueBlockHeight,
child: Align(alignment: Alignment.topLeft, child: list),
);
}
Widget _list(BuildContext context) {
if (suggestions.isEmpty) return const SizedBox.shrink();
if (!compact) {
return ListView.builder(
@ -70,7 +90,7 @@ class AutocompleteSuggestionList extends StatelessWidget {
},
);
}
final shown = suggestions.take(_compactLimit).toList();
final shown = suggestions.take(compactLimit).toList();
final remaining = suggestions.length - shown.length;
return Column(
mainAxisSize: MainAxisSize.min,

View File

@ -1,93 +0,0 @@
/// The log form's "Fill all with catering" row: one button, plus Cancel while
/// a proposal is armed.
///
/// Its own row rather than a third control in [LogMealActionsRow]: that row is
/// already full on a narrow phone, and "✓ Confirm (N)" must stay legible.
library;
import 'package:diet_guard_app/services/kuchnia_client.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:material_ui/material_ui.dart';
/// Spoken name of the resting button (never painted).
const fillAllLabel = 'Fill all with catering';
/// Fill-all button; relabels to "✓ Confirm (N)" once a proposal is armed.
class FillAllRow extends StatelessWidget {
/// Creates the row.
const FillAllRow({
required this.onFill,
required this.onCancel,
this.busy = false,
this.armedCount = 0,
this.canFetchDelivery,
super.key,
});
/// First tap proposes, second tap confirms.
final Future<void> Function() onFill;
/// Disarms a proposal without writing anything.
final VoidCallback onCancel;
/// Disables both controls while a fetch or the confirm's writes run.
final bool busy;
/// How many dishes the armed proposal would log; 0 when none is armed.
final int armedCount;
/// Whether the platform can fetch at all. Defaults to
/// [kuchniaFetchSupported] -- false on web, where the caterer's panel blocks
/// browser requests -- so the row is hidden there, like the delivery button.
final bool? canFetchDelivery;
@override
Widget build(BuildContext context) {
if (!(canFetchDelivery ?? kuchniaFetchSupported)) {
return const SizedBox.shrink();
}
final armed = armedCount > 0;
return Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: busy ? null : onFill,
child: _face(context, armed),
),
),
if (armed) ...[
const SizedBox(width: AppSpacing.sm),
IconButton(
onPressed: busy ? null : onCancel,
icon: const Icon(Icons.close, semanticLabel: 'Cancel'),
),
],
],
);
}
/// Resting glyph; spinner while busy; double check + count once armed.
Widget _face(BuildContext context, bool armed) {
if (busy) {
return const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
);
}
if (!armed) {
return const Icon(Icons.playlist_add_check, semanticLabel: fillAllLabel);
}
final success =
(Theme.of(context).extension<AppStatusColors>() ?? AppStatusColors.dark)
.success;
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.done_all, color: success, semanticLabel: 'Confirm'),
const SizedBox(width: AppSpacing.xs),
Text('$armedCount'),
],
);
}
}

View File

@ -1,95 +0,0 @@
/// The log form's action row: load today's delivery, then log the meal.
///
/// Its own file because `log_meal_screen.dart` sits at the repo's 250-line
/// ceiling; lifting the whole row rather than just the delivery button keeps
/// both controls' layout in one place and returns budget to the screen.
library;
import 'package:diet_guard_app/services/kuchnia_client.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:material_ui/material_ui.dart';
/// A delivery button beside the log button.
///
/// The delivery control mirrors the PC lock screen's "🍱 Today's delivery":
/// standing in the kitchen, there must be something to tap. It stays visible
/// and enabled even when there is nothing to load — the outcome arrives as a
/// message rather than as a disabled button, because a disabled control gives
/// no way to retry after a late delivery and a hidden one reads as broken.
class LogMealActionsRow extends StatelessWidget {
/// Creates the action row.
const LogMealActionsRow({
required this.onLoadDelivery,
required this.onLog,
this.deliveryBusy = false,
this.dishesQueued = 0,
this.canFetchDelivery,
super.key,
});
/// Loads today's delivery and prefills the first/next dish.
final Future<void> Function() onLoadDelivery;
/// Writes the current form as a log entry.
final VoidCallback onLog;
/// Whether a delivery fetch is in flight; disables the button meanwhile so
/// a second tap cannot start a concurrent login against the caterer.
final bool deliveryBusy;
/// How many delivered dishes are still queued, shown as the PC's
/// "(N more to go)" so the user knows the walk is not finished.
final int dishesQueued;
/// Whether the platform can fetch at all. Defaults to
/// [kuchniaFetchSupported] — false on web, where the desktop build runs and
/// the caterer's panel blocks browser requests, so the control is hidden
/// rather than shipped dead.
final bool? canFetchDelivery;
@override
Widget build(BuildContext context) {
final canFetch = canFetchDelivery ?? kuchniaFetchSupported;
return Row(
children: [
// Expanded so the delivery button takes the slack and pushes the log
// button right; the queue is a numeral next to the icon, so there is
// no wide label to clip. While fetching the icon becomes a spinner.
if (canFetch)
Expanded(
child: OutlinedButton(
onPressed: deliveryBusy ? null : onLoadDelivery,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (deliveryBusy)
const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
else
const Icon(
Icons.restaurant,
semanticLabel: "Load today's catering delivery",
),
if (dishesQueued > 0) ...[
const SizedBox(width: AppSpacing.xs),
Text('$dishesQueued'),
],
],
),
),
),
// No Spacer when the delivery button is present: it is a flex child
// too and would split the free space with the Expanded above.
if (!canFetch) const Spacer(),
const SizedBox(width: AppSpacing.sm),
FilledButton(
onPressed: onLog,
child: const Icon(Icons.check_circle, semanticLabel: 'Log meal'),
),
],
);
}
}

View File

@ -0,0 +1,101 @@
/// One meal the screen logged for the user: where it came from, what it is,
/// and a plain round undo.
library;
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/ui/macro_kind.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:material_ui/material_ui.dart';
/// How the entry got logged; picks the leading glyph.
enum LoggedOrigin {
/// Claude read the text and/or photo (sparkle).
claude,
/// The delivered catering dish logged itself (restaurant).
catering,
/// The check button (check).
local,
}
/// A logged meal and the way it got logged.
@immutable
class LoggedMeal {
/// Creates the pair.
const LoggedMeal(this.entry, this.origin);
/// The entry that was written.
final FoodEntry entry;
/// How it got logged.
final LoggedOrigin origin;
}
/// Name, kcal and macro figures, and an undo button (no countdown).
class LoggedMealRow extends StatelessWidget {
/// Creates the row.
const LoggedMealRow({required this.meal, required this.onUndo, super.key});
/// The meal shown.
final LoggedMeal meal;
/// Tombstones the entry.
final VoidCallback onUndo;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final entry = meal.entry;
final (icon, color) = switch (meal.origin) {
LoggedOrigin.claude => (Icons.auto_awesome, theme.colorScheme.primary),
LoggedOrigin.catering => (
Icons.restaurant,
theme.colorScheme.onSurfaceVariant,
),
LoggedOrigin.local => (
Icons.check_circle,
(theme.extension<AppStatusColors>() ?? AppStatusColors.dark).success,
),
};
String n(double v) => v.round().toString();
return Padding(
padding: const EdgeInsets.only(top: AppSpacing.sm),
child: Row(
children: [
Icon(icon, color: color),
const SizedBox(width: AppSpacing.sm),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(entry.desc, maxLines: 1, overflow: TextOverflow.ellipsis),
Wrap(
spacing: AppSpacing.sm,
children: [
MacroFigure(
kind: MacroKind.kcal,
value: n(entry.kcal),
size: 16,
),
MacroFigure(
kind: MacroKind.protein,
value: n(entry.proteinG),
),
MacroFigure(kind: MacroKind.carbs, value: n(entry.carbsG)),
MacroFigure(kind: MacroKind.fat, value: n(entry.fatG)),
],
),
],
),
),
IconButton.filledTonal(
constraints: const BoxConstraints.tightFor(width: 48, height: 48),
onPressed: onUndo,
icon: const Icon(Icons.undo, semanticLabel: 'Undo'),
),
],
),
);
}
}

View File

@ -5,7 +5,9 @@ library;
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/icon_field.dart';
import 'package:diet_guard_app/ui/macro_kind.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:material_ui/material_ui.dart';
/// Text controllers for one macro-entry row, owned by the calling screen so
@ -128,12 +130,14 @@ class MacroInputRow extends StatelessWidget {
_macroField(MacroKind.eaten, controllers.grams),
];
if (compact) {
return Row(
// Two rows of three, never six in one: a Row of Expanded fields clips a
// four-digit value silently (1250 g, 2400 kcal), and the digits must stay
// whole at body size. A field is 1/3 of the width, not 1/6.
return Column(
children: [
for (final (i, field) in fields.indexed) ...[
if (i > 0) const SizedBox(width: 4),
Expanded(child: field),
],
_threeAcross(fields.sublist(0, 3)),
const SizedBox(height: AppSpacing.sm),
_threeAcross(fields.sublist(3)),
],
);
}
@ -164,6 +168,15 @@ class MacroInputRow extends StatelessWidget {
);
}
Widget _threeAcross(List<Widget> three) => Row(
children: [
for (final (i, field) in three.indexed) ...[
if (i > 0) const SizedBox(width: AppSpacing.sm),
Expanded(child: field),
],
],
);
Widget _macroField(MacroKind kind, TextEditingController controller) {
return IconField(
icon: kind.icon,
@ -172,6 +185,7 @@ class MacroInputRow extends StatelessWidget {
controller: controller,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
dense: true,
fontSize: AppTextSize.body,
);
}
}

View File

@ -0,0 +1,216 @@
/// The log form's action row (variant 1A): photo, send to Claude, log here.
///
/// Three solid icon buttons and no words. The photo button is blue (tap =
/// camera, long press = gallery); an attached photo turns it into a tinted
/// button with a check badge and a small remove badge, and never shows the
/// picture. The gold sparkle sends the text and/or photo to Claude; the green
/// check logs what is typed. Both are greyed until there is something to
/// send or log.
library;
import 'package:diet_guard_app/ui/theme.dart';
import 'package:material_ui/material_ui.dart';
/// What the sparkle button shows.
enum ClaudeButtonState {
/// Ready (sparkle), or greyed when [MealActionRow.canSend] is false.
idle,
/// A request is in flight (spinner).
sending,
/// The PC is offline; the request waits (hourglass).
queued,
/// Sync is locked, nothing can be sent (lock).
locked,
/// The last send failed (error glyph); a tap retries.
error,
}
/// The photo button's blue, the same hue as the fat figure.
const photoButtonColor = Color(0xFF6C9BD1);
/// Photo, Claude and log buttons side by side.
class MealActionRow extends StatelessWidget {
/// Creates the row.
const MealActionRow({
required this.claude,
required this.photoAttached,
required this.canSend,
required this.canLog,
required this.onPhoto,
required this.onGallery,
required this.onRemovePhoto,
required this.onSend,
required this.onLog,
super.key,
});
/// State of the sparkle button.
final ClaudeButtonState claude;
/// Whether a photo is attached.
final bool photoAttached;
/// Whether there is text or a photo to send.
final bool canSend;
/// Whether there is a description to log.
final bool canLog;
/// Tap on the photo button: the camera.
final VoidCallback onPhoto;
/// Long press on the photo button: the gallery.
final VoidCallback onGallery;
/// The remove badge.
final VoidCallback onRemovePhoto;
/// The sparkle button.
final VoidCallback onSend;
/// The check button.
final VoidCallback onLog;
static const double _height = 56;
@override
Widget build(BuildContext context) {
final status =
Theme.of(context).extension<AppStatusColors>() ?? AppStatusColors.dark;
final gold = Theme.of(context).colorScheme.primary;
final sendable =
canSend &&
claude != ClaudeButtonState.sending &&
claude != ClaudeButtonState.queued;
return Row(
children: [
Expanded(child: _photo(status.success)),
const SizedBox(width: AppSpacing.sm),
Expanded(
child: _solid(
color: gold,
onPressed: sendable ? onSend : null,
child: _claudeFace(),
),
),
const SizedBox(width: AppSpacing.sm),
Expanded(
child: _solid(
color: status.success,
onPressed: canLog ? onLog : null,
child: const Icon(Icons.check_circle, semanticLabel: 'Log meal'),
),
),
],
);
}
Widget _solid({
required Color color,
required VoidCallback? onPressed,
required Widget child,
VoidCallback? onLongPress,
Color? foreground,
}) => FilledButton(
onPressed: onPressed,
onLongPress: onLongPress,
style: FilledButton.styleFrom(
backgroundColor: color,
foregroundColor: foreground ?? const Color(0xFF211D1B),
minimumSize: const Size.fromHeight(_height),
),
child: child,
);
Widget _claudeFace() => switch (claude) {
ClaudeButtonState.sending => const SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(strokeWidth: 3),
),
ClaudeButtonState.queued => const Icon(
Icons.hourglass_top,
semanticLabel: 'Waiting for the PC',
),
ClaudeButtonState.locked => const Icon(
Icons.lock,
semanticLabel: 'Sync is locked',
),
ClaudeButtonState.error => const Icon(
Icons.error_outline,
semanticLabel: 'Claude failed',
),
ClaudeButtonState.idle => const Icon(
Icons.auto_awesome,
semanticLabel: 'Ask Claude',
),
};
Widget _photo(Color success) {
final button = _solid(
color: photoAttached
? photoButtonColor.withValues(alpha: 0.25)
: photoButtonColor,
foreground: photoAttached ? photoButtonColor : null,
onPressed: onPhoto,
onLongPress: onGallery,
child: const Icon(Icons.add_a_photo, semanticLabel: 'Photo'),
);
if (!photoAttached) return button;
return Stack(
clipBehavior: Clip.none,
children: [
button,
Positioned(
top: -6,
left: -6,
child: _badge(Icons.check, success, null, 'Photo attached'),
),
Positioned(
top: -6,
right: -6,
child: _badge(
Icons.close,
photoButtonColor,
onRemovePhoto,
'Remove photo',
),
),
],
);
}
/// A 24 dp badge inside a 32 dp hit area, so the remove target is usable.
Widget _badge(
IconData icon,
Color color,
VoidCallback? onTap,
String label,
) => GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: SizedBox(
width: 32,
height: 32,
child: Center(
child: DecoratedBox(
decoration: BoxDecoration(color: color, shape: BoxShape.circle),
child: SizedBox(
width: 22,
height: 22,
child: Icon(
icon,
size: 16,
color: const Color(0xFF211D1B),
semanticLabel: label,
),
),
),
),
),
);
}

View File

@ -454,6 +454,14 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
flutter_plugin_android_lifecycle:
dependency: transitive
description:
name: flutter_plugin_android_lifecycle
sha256: "3854fe5e3bff0b113c658f260b90c95dea17c92db0f2addeac2e343dd9969785"
url: "https://pub.dev"
source: hosted
version: "2.0.35"
flutter_secure_storage:
dependency: "direct main"
description:
@ -578,6 +586,70 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.9.1"
image_picker:
dependency: "direct main"
description:
name: image_picker
sha256: e71b1bd9e40124041128d60fc3034c7b1598e1bba4e570bba0c70301c817013a
url: "https://pub.dev"
source: hosted
version: "1.2.4"
image_picker_android:
dependency: transitive
description:
name: image_picker_android
sha256: "8a7823d5d3e884f7780829d85d92110d072bdcd9ed48e2be158d2abe91a912d4"
url: "https://pub.dev"
source: hosted
version: "0.8.13+25"
image_picker_for_web:
dependency: transitive
description:
name: image_picker_for_web
sha256: "66257a3191ab360d23a55c8241c91a6e329d31e94efa7be9cf7a212e65850214"
url: "https://pub.dev"
source: hosted
version: "3.1.1"
image_picker_ios:
dependency: transitive
description:
name: image_picker_ios
sha256: f4e5650a81b268af3886bc789216ff6d56bdfa79934f93f1a5a8a303b8f60f77
url: "https://pub.dev"
source: hosted
version: "0.8.13+15"
image_picker_linux:
dependency: transitive
description:
name: image_picker_linux
sha256: "1f81c5f2046b9ab724f85523e4af65be1d47b038160a8c8deed909762c308ed4"
url: "https://pub.dev"
source: hosted
version: "0.2.2"
image_picker_macos:
dependency: transitive
description:
name: image_picker_macos
sha256: "86f0f15a309de7e1a552c12df9ce5b59fe927e71385329355aec4776c6a8ec91"
url: "https://pub.dev"
source: hosted
version: "0.2.2+1"
image_picker_platform_interface:
dependency: transitive
description:
name: image_picker_platform_interface
sha256: "2dee4b4e3be429db71472c9c559c981498070a61af1ba82e0e4986fc5dadc042"
url: "https://pub.dev"
source: hosted
version: "2.11.2"
image_picker_windows:
dependency: transitive
description:
name: image_picker_windows
sha256: d248c86554a72b5495a31c56f060cf73a41c7ff541689327b1a7dbccc33adfae
url: "https://pub.dev"
source: hosted
version: "0.2.2"
intl:
dependency: transitive
description:

View File

@ -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.163+1
version: 1.0.173+1
environment:
sdk: ^3.12.2
@ -51,6 +51,8 @@ dependencies:
health: 13.3.2
http: 1.6.0
idb_shim: 2.11.3
# Camera/gallery photo as transient input to Claude (never stored or synced).
image_picker: 1.2.4
material_ui: 1.11.0
path: 1.9.1
path_provider: 2.1.6

View File

@ -1,97 +0,0 @@
/// The "Fill all with catering" row: glyph per state, Cancel only when armed.
library;
import 'package:diet_guard_app/widgets/fill_all_row.dart';
import 'package:material_ui/material_ui.dart';
import 'package:flutter_test/flutter_test.dart';
import 'label_finders.dart';
Future<void> _pump(
WidgetTester tester, {
bool canFetch = true,
bool busy = false,
int armed = 0,
Future<void> Function()? onFill,
VoidCallback? onCancel,
}) => tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: FillAllRow(
onFill: onFill ?? () async {},
onCancel: onCancel ?? () {},
busy: busy,
armedCount: armed,
canFetchDelivery: canFetch,
),
),
),
);
void main() {
testWidgets('is hidden where delivery cannot be fetched (web)', (t) async {
await _pump(t, canFetch: false, armed: 3);
expect(find.byType(OutlinedButton), findsNothing);
expect(byIconLabel(fillAllLabel), findsNothing);
expect(byIconLabel('Cancel'), findsNothing);
});
testWidgets('resting: the fill glyph and no Cancel', (t) async {
await _pump(t);
expect(byIconLabel(fillAllLabel), findsOneWidget);
expect(find.byIcon(Icons.playlist_add_check), findsOneWidget);
expect(byIconLabel('Cancel'), findsNothing);
});
testWidgets('armed: double check with the count, and a Cancel button', (
t,
) async {
await _pump(t, armed: 3);
expect(byIconLabel('Confirm'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(byIconLabel(fillAllLabel), findsNothing);
expect(byIconLabel('Cancel'), findsOneWidget);
});
testWidgets('busy: spinner and both controls disabled', (t) async {
var fills = 0;
var cancels = 0;
await _pump(
t,
busy: true,
armed: 3,
onFill: () async => fills++,
onCancel: () => cancels++,
);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
expect(byIconLabel('Confirm'), findsNothing);
expect(
t.widget<OutlinedButton>(find.byType(OutlinedButton)).onPressed,
isNull,
);
expect(t.widget<IconButton>(find.byType(IconButton)).onPressed, isNull);
await t.tap(find.byType(OutlinedButton), warnIfMissed: false);
await t.tap(find.byType(IconButton), warnIfMissed: false);
expect(fills + cancels, 0);
});
testWidgets('taps reach the callbacks when idle', (t) async {
var fills = 0;
var cancels = 0;
await _pump(
t,
armed: 2,
onFill: () async => fills++,
onCancel: () => cancels++,
);
await t.tap(byIconLabel('Confirm'));
await t.tap(byIconLabel('Cancel'));
expect([fills, cancels], [1, 1]);
});
}

View File

@ -1,10 +1,24 @@
import 'dart:async';
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
import 'package:diet_guard_app/services/log_feedback.dart';
/// Mutes the log cue suite-wide: audioplayers has no platform side under
/// `flutter test`, so a real play would fail any test that logs a meal.
/// Suite-wide test defaults.
///
/// * The log cue is muted: audioplayers has no platform side under
/// `flutter test`, so a real play would fail any test that logs a meal.
/// * The log screen's clock is pinned to 07:00 today, before the first slot,
/// so no slot is due and the screen is in normal mode whatever the wall
/// clock says. Without the pin every nav and slot test would pass at night
/// and fail by day, once due mode hides the app bar. A test that needs due
/// mode sets [logMealClock] itself.
/// * The status bar call goes nowhere; a test that checks it replaces the hook.
Future<void> testExecutable(FutureOr<void> Function() testMain) async {
LogFeedback.playConfirmCue = () async {};
logMealClock = () {
final now = DateTime.now();
return DateTime(now.year, now.month, now.day, 7);
};
setStatusBarHidden = ({required hidden}) async {};
await testMain();
}

View File

@ -1,8 +1,6 @@
// Guard: a catering fetch / fill reports with a glyph and a dish count; its
// Guard: a catering fetch reports with a glyph and a dish count; its
// sentence is only the spoken label.
import 'package:diet_guard_app/screens/log_meal_fill_mixin.dart';
import 'package:diet_guard_app/services/kuchnia_spread.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:material_ui/material_ui.dart';
import 'package:flutter_test/flutter_test.dart';
@ -11,26 +9,6 @@ import 'label_finders.dart';
import 'no_words_support.dart';
void main() {
group('fillCue', () {
test('nothing to fill paints a warning and 0', () {
final cue = fillCue((
message: 'No catering delivery today.',
written: const <SlottedDish>[],
), armed: 0);
expect(cue.kind, CueKind.warn);
expect(cue.count, 0);
expect(cue.label, 'No catering delivery today.');
});
test('a proposal paints its armed count', () {
final cue = fillCue((
message: 'Will log 3',
written: const <SlottedDish>[],
), armed: 3);
expect((cue.kind, cue.count), (CueKind.info, 3));
});
});
testWidgets('a counted cue paints only the glyph and the number', (
tester,
) async {

View File

@ -9,6 +9,7 @@ import 'dart:io';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/screens/calendar_screen.dart';
import 'package:diet_guard_app/screens/history_screen.dart';
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_screen.dart';
import 'package:diet_guard_app/screens/settings_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
@ -24,6 +25,7 @@ import 'package:shared_preferences/shared_preferences.dart';
import 'fake_secure_storage.dart';
import 'label_finders.dart';
import 'no_words_support.dart';
import 'screens/log_meal_test_support.dart' show pinLogMealClock;
/// The one meal logged in setUp: user content, allowed.
const _food = 'porridge';
@ -88,16 +90,41 @@ void main() {
});
}
testWidgets('a rejected log paints a cue, not a sentence', (tester) async {
testWidgets('a future date with no slot paints a cue, not a sentence', (
tester,
) async {
await tester.runAsync(() async {
await show(tester, const LogMealScreen());
final state = tester.state<State<LogMealScreen>>(
find.byType(LogMealScreen),
);
final tomorrow = DateTime.now().add(const Duration(days: 1));
await (state as LogMealFutureMixin<LogMealScreen>).selectLogDate(
tomorrow,
);
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField).first, _food);
await tester.pump();
final log = controlByLabel('Log meal');
await tester.ensureVisible(log);
await tester.tap(log);
await Future<void>.delayed(const Duration(milliseconds: 200));
await tester.pump(const Duration(seconds: 1));
expect(cueLabelled('Type what you ate first.'), findsOneWidget);
expectNoWords(tester, minStrings: 3, where: 'rejected log');
expect(cueLabelled('Pick a slot for that date first.'), findsOneWidget);
expectNoWords(tester, content: {_food}, minStrings: 3, where: 'cue');
});
});
testWidgets('due mode and a logged row paint no words', (tester) async {
pinLogMealClock(13);
await tester.runAsync(() async {
await show(tester, const LogMealScreen());
await tester.enterText(find.byType(TextField).first, _food);
await tester.pump();
await tester.tap(controlByLabel('Log meal'));
await Future<void>.delayed(const Duration(milliseconds: 200));
await tester.pump(const Duration(seconds: 1));
expectNoWords(tester, content: {_food}, minStrings: 5, where: 'due');
});
});
}

View File

@ -0,0 +1,145 @@
/// A meal photo is transient input to Claude, never data.
///
/// Photos came back on 2026-11-17 as input to the Claude relay only (the
/// earlier removal still stands for blob stores and the `/blobs/` route). A
/// device-local attachment would break the one-source-of-truth rule, so these
/// assertions are structural: a new field or file cannot slip an image into an
/// entry, a store or the sync wire unnoticed.
library;
import 'dart:io';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/meal_component.dart';
import 'package:flutter_test/flutter_test.dart';
Directory get _appDir {
var dir = Directory.current;
while (!File('${dir.path}/pubspec.yaml').existsSync()) {
final parent = dir.parent;
if (parent.path == dir.path) fail('could not locate app/');
dir = parent;
}
return dir;
}
List<File> _dartFilesIn(String relative) =>
Directory('${_appDir.path}/$relative')
.listSync(recursive: true)
.whereType<File>()
.where((f) => f.path.endsWith('.dart'))
.toList();
void main() {
group('a meal photo is transient input to Claude, never data', () {
const pickerHome = 'services/meal_photo_source.dart';
const photoFiles = {
'services/meal_photo_source.dart',
'services/meal_photo_cleanup.dart',
'services/meal_photo_cleanup_io.dart',
'services/meal_photo_cleanup_web.dart',
'services/claude_relay_client.dart',
'services/claude_relay_fake.dart',
};
String relative(File f) => f.path.split('/app/lib/').last;
test('image_picker is imported by the photo source alone', () {
final offenders = [
for (final file in _dartFilesIn('lib'))
if (relative(file) != pickerHome &&
file.readAsStringSync().contains('package:image_picker/'))
relative(file),
];
expect(offenders, isEmpty);
});
test('image bytes stay out of entries, storage and sync', () {
final banned = RegExp(
r'Uint8List|photo|jpeg|jpg|base64',
caseSensitive: false,
);
final offenders = [
for (final file in _dartFilesIn('lib'))
if (!photoFiles.contains(relative(file)) &&
(relative(file).startsWith('models/') ||
relative(file).contains('sync_') ||
relative(file).contains('document_store') ||
relative(file).contains('log_storage') ||
relative(file).contains('log_entry') ||
relative(file).contains('foodbank')) &&
banned.hasMatch(file.readAsStringSync()))
relative(file),
];
expect(
offenders,
isEmpty,
reason:
'A photo (or its bytes) reached a model, a store or the sync '
'wire. Photos are transient input to the Claude relay only.',
);
});
test('a FoodEntry syncs a fixed set of keys, none of them an image', () {
const entry = FoodEntry(
id: 'a',
time: '2026-11-17T08:00:00',
desc: 'x',
grams: 1,
kcal: 1,
proteinG: 1,
carbsG: 1,
fatG: 1,
source: 'claude',
slotMinute: 435,
components: [
MealComponent(
name: 'c',
kcal: 1,
proteinG: 1,
carbsG: 1,
fatG: 1,
grams: 1,
),
],
deleted: true,
);
expect(entry.toSyncJson().keys.toSet(), {
'id',
'time',
'desc',
'grams',
'kcal',
'protein_g',
'carbs_g',
'fat_g',
'source',
'slot',
'slot_min',
'components',
'deleted',
});
});
test('the photo is only ever picked into memory', () {
final source = File('${_appDir.path}/lib/$pickerHome').readAsStringSync();
expect(source.contains('readAsBytes'), isTrue);
for (final banned in [
'path_provider',
'writeAsBytes',
'getApplication',
]) {
expect(source.contains(banned), isFalse, reason: banned);
}
});
test('the camera permission is declared for the picker', () {
final manifest = File(
'${_appDir.path}/android/app/src/main/AndroidManifest.xml',
);
expect(
manifest.readAsStringSync().contains('android.permission.CAMERA'),
isTrue,
);
});
});
}

View File

@ -44,7 +44,8 @@ void main() {
expect(
Directory('${_appDir.path}/linux').existsSync(),
isFalse,
reason: 'A Linux embedder target was re-added. The desktop app is the '
reason:
'A Linux embedder target was re-added. The desktop app is the '
'web build served by bin/diet_guard_desktop.dart; see CLAUDE.md.',
);
});
@ -68,7 +69,8 @@ void main() {
expect(
offenders,
isEmpty,
reason: 'These files import dart:io outside the conditional-export '
reason:
'These files import dart:io outside the conditional-export '
'seam, which compiles for web and throws at runtime (blank white '
'window). Move the platform edge into a *_io.dart / *_web.dart '
'pair, and branch on kIsWeb before any Platform.is… check.',
@ -93,36 +95,11 @@ void main() {
expect(
offenders,
isEmpty,
reason: 'A removed feature came back. See the "Do NOT" section of '
reason:
'A removed feature came back. See the "Do NOT" section of '
'CLAUDE.md before re-adding any of these.',
);
});
// Photos took image_picker, the blob stores, the wrapper's /blobs/ route
// and the CAMERA permission with them. Re-adding photos means re-adding
// all of that *plus* syncing image blobs, since a device-local attachment
// would violate the one-source-of-truth rule.
test('no image_picker dependency', () {
final pubspec = File('${_appDir.path}/pubspec.yaml').readAsStringSync();
expect(
pubspec.contains('image_picker'),
isFalse,
reason: 'Meal photos were removed deliberately. A device-local image '
'attachment also breaks the shared-source-of-truth rule.',
);
});
test('no CAMERA permission in the Android manifest', () {
final manifest = File(
'${_appDir.path}/android/app/src/main/AndroidManifest.xml',
);
expect(
manifest.readAsStringSync().contains('android.permission.CAMERA'),
isFalse,
reason: 'The CAMERA permission came back with no photo feature to '
'justify it.',
);
});
});
group('pickers paint no words', () {
@ -138,7 +115,8 @@ void main() {
expect(
offenders,
isEmpty,
reason: 'A framework picker came back. Use pickDate, pickDateRange '
reason:
'A framework picker came back. Use pickDate, pickDateRange '
'or pickTime from widgets/pickers/pickers.dart.',
);
});
@ -159,7 +137,8 @@ void main() {
expect(
source.contains(call),
isTrue,
reason: '$call is missing from main(). The feature will silently do '
reason:
'$call is missing from main(). The feature will silently do '
'nothing on a real device while every test still passes.',
);
}
@ -177,7 +156,8 @@ void main() {
expect(
source.contains('desktopWrapperPort = 8732'),
isTrue,
reason: 'The wrapper port changed. IndexedDB is keyed by origin, so a '
reason:
'The wrapper port changed. IndexedDB is keyed by origin, so a '
'new port looks like a different app with no history at all. '
'8730 is ~/src/todo and 8731 is ~/src/habit_stack; do not collide.',
);
@ -190,7 +170,8 @@ void main() {
expect(
source.contains("'diet-guard-desktop', 'profile'"),
isTrue,
reason: 'The Chrome --user-data-dir moved. IndexedDB lives in that '
reason:
'The Chrome --user-data-dir moved. IndexedDB lives in that '
'profile, so relocating it hides the entire local food log.',
);
});

View File

@ -76,6 +76,7 @@ void main() {
) async {
await _pump(tester, const LogMealScreen());
await tester.enterText(find.byType(TextField).first, 'Oats');
await tester.pump(); // the log button greys until text is typed
await tester.runAsync(() async {
await tester.tap(controlByLabel('Log meal'));
await Future<void>.delayed(const Duration(milliseconds: 500));

View File

@ -0,0 +1,140 @@
/// Catering auto-log on the log screen: opening it with slots due logs the
/// delivered dishes without a tap (kuhy's override of 2026-11-17).
library;
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_screen.dart';
import 'package:diet_guard_app/services/kuchnia_autolog.dart';
import 'package:diet_guard_app/services/kuchnia_fill.dart';
import 'package:diet_guard_app/services/kuchnia_import.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';
KuchniaDish _dish(int n) => KuchniaDish(
name: 'Danie $n',
kcal: 100.0 * n,
proteinG: 10,
carbsG: 20,
fatG: 5,
grams: 300,
priority: n,
slotLabel: '',
dishId: '${2000 + n}',
);
void main() {
late Future<void> Function() restore;
late int fetches;
setUp(() async {
restore = await isolateLogScreenState();
fetches = 0;
pinLogMealClock(13); // 08:00 and 12:00 due
KuchniaAutoLog.instance = KuchniaAutoLog(
fetch: (day) async {
fetches++;
return KuchniaRefresh(dishes: [for (var i = 1; i <= 4; i++) _dish(i)]);
},
now: () => logMealClock(),
);
});
tearDown(() => restore());
Future<void> open(WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
await settle(tester);
}
testWidgets('opening in due mode logs the due dishes with no tap', (
tester,
) async {
await tester.runAsync(() async {
await open(tester);
final entries = await LogStorageService.instance.todayEntries();
expect(entries.map((e) => e.desc), ['Danie 1', 'Danie 2']);
expect(entries.map((e) => e.slotMinute), [480, 720]);
expect(entries.every((e) => e.source == kuchniaSource), isTrue);
// A restaurant glyph and an undo per row; nothing is due any more.
expect(find.byIcon(Icons.restaurant), findsNWidgets(2));
expect(byIconLabel('Undo'), findsNWidgets(2));
expect(find.byType(AppBar), findsOneWidget);
});
});
testWidgets('undo removes one dish and a reopen does not log it again', (
tester,
) async {
await tester.runAsync(() async {
await open(tester);
await tester.tap(byIconLabel('Undo').first);
await settle(tester);
expect(find.byIcon(Icons.restaurant), findsOneWidget);
var live = await LogStorageService.instance.todayEntries();
expect(live.map((e) => e.desc), ['Danie 2']);
// Reopen: 08:00 is due again, but its tombstoned id blocks the dish.
await tester.pumpWidget(const SizedBox());
await open(tester);
live = await LogStorageService.instance.todayEntries();
expect(live.map((e) => e.desc), ['Danie 2']);
expect(find.byIcon(Icons.restaurant), findsNothing);
expect(find.byType(AppBar), findsNothing, reason: 'still due');
});
});
testWidgets('opening twice fetches once and leaves one entry per dish', (
tester,
) async {
await tester.runAsync(() async {
await open(tester);
await tester.pumpWidget(const SizedBox());
await open(tester);
final entries = await LogStorageService.instance.todayEntries();
expect(entries, hasLength(2));
expect(fetches, 1);
});
});
testWidgets('normal mode logs nothing and never fetches', (tester) async {
pinLogMealClock(7);
await tester.runAsync(() async {
await open(tester);
expect(await LogStorageService.instance.todayEntries(), isEmpty);
expect(fetches, 0);
});
});
testWidgets('resuming into a due slot logs the dishes with no tap', (
tester,
) async {
await tester.runAsync(() async {
// Opened before the first slot: normal mode, nothing logged.
logMealClock = () {
final t = DateTime.now();
return DateTime(t.year, t.month, t.day, 7);
};
await open(tester);
expect(await LogStorageService.instance.todayEntries(), isEmpty);
expect(fetches, 0);
// Time passes (08:00 and 12:00 elapse); the app comes back to front.
pinLogMealClock(13);
final state = tester.state<State<LogMealScreen>>(
find.byType(LogMealScreen),
);
(state as WidgetsBindingObserver).didChangeAppLifecycleState(
AppLifecycleState.resumed,
);
await settle(tester);
final entries = await LogStorageService.instance.todayEntries();
expect(entries.map((e) => e.desc), ['Danie 1', 'Danie 2']);
expect(find.byIcon(Icons.restaurant), findsNWidgets(2));
});
});
}

View File

@ -0,0 +1,200 @@
/// The sparkle button and the photo button on the log screen.
library;
import 'dart:typed_data';
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_entry_lookup.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_photo_source.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';
class _Photos implements MealPhotoSource {
final List<PhotoOrigin> asked = [];
final Uint8List bytes = Uint8List.fromList([1, 2, 3]);
@override
Future<Uint8List?> pick(PhotoOrigin origin) async {
asked.add(origin);
return bytes;
}
}
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;
late _Photos photos;
setUp(() async {
restore = await isolateLogScreenState();
relay = FakeClaudeRelayClient();
photos = _Photos();
});
tearDown(() => restore());
Future<void> open(WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: LogMealScreen(relay: relay, photos: photos),
),
);
await settle(tester);
}
bool sparkleEnabled(WidgetTester tester) =>
tester
.widget<FilledButton>(
find.ancestor(
of: find.byWidgetPredicate(
(w) =>
w is Icon &&
(w.semanticLabel == 'Ask Claude' ||
w.icon == Icons.hourglass_top ||
w.icon == Icons.lock ||
w.icon == Icons.error_outline),
),
matching: find.byType(FilledButton),
),
)
.onPressed !=
null;
testWidgets('the sparkle is greyed until there is text or a photo', (
tester,
) async {
pinLogMealClock(13);
await tester.runAsync(() async {
await open(tester);
expect(sparkleEnabled(tester), isFalse);
await tester.enterText(find.byType(TextField).at(0), 'kurczak');
await settle(tester);
expect(sparkleEnabled(tester), isTrue);
});
});
testWidgets('a photo alone enables the sparkle; tap camera, hold gallery', (
tester,
) async {
pinLogMealClock(13);
await tester.runAsync(() async {
await open(tester);
// Inside runAsync the recognizer's timer is real, so wait in real time.
final press = await tester.startGesture(
tester.getCenter(controlByLabel('Photo')),
);
await Future<void>.delayed(const Duration(milliseconds: 700));
await press.up();
await settle(tester);
expect(photos.asked, [PhotoOrigin.gallery]);
await tester.tap(byIconLabel('Remove photo'));
await settle(tester);
await tester.tap(controlByLabel('Photo'));
await settle(tester);
expect(photos.asked, [PhotoOrigin.gallery, PhotoOrigin.camera]);
expect(sparkleEnabled(tester), isTrue);
expect(byIconLabel('Photo attached'), findsOneWidget);
expect(find.byType(Image), findsNothing);
await tester.tap(byIconLabel('Remove photo'));
await settle(tester);
expect(sparkleEnabled(tester), isFalse);
});
});
testWidgets('a send carries the text, photo and the oldest due slot', (
tester,
) async {
pinLogMealClock(13); // 08:00 and 12:00 are due
await tester.runAsync(() async {
await open(tester);
await tester.tap(controlByLabel('Photo'));
await settle(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(sent.text, 'kurczak');
expect(sent.photoJpeg, photos.bytes);
expect(sent.slotMinute, 480);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
});
});
testWidgets('queued, then logged: the row shows and undo tombstones it', (
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();
relay.emit(const ClaudeRelayQueued());
await settle(tester);
expect(byIconLabel('Waiting for the PC'), findsOneWidget);
final id = claudeEntryId(relay.sent.single.requestId);
relay.emit(ClaudeRelayLogged(_claudeEntry(id)));
await settle(tester);
expect(find.text('kurczak z ryzem'), findsOneWidget);
expect(find.byIcon(Icons.auto_awesome), findsWidgets);
expect((await LogStorageService.instance.todayEntries()).single.id, id);
// The form reset, and the photo is gone with the send.
expect(
tester.widget<TextField>(find.byType(TextField).at(0)).controller!.text,
'',
);
await tester.tap(byIconLabel('Undo'));
await settle(tester);
expect(await LogStorageService.instance.todayEntries(), isEmpty);
expect((await LogStorageService.instance.findEntry(id))!.deleted, isTrue);
expect(find.text('kurczak z ryzem'), findsNothing);
});
});
for (final (event, glyph) in [
(const ClaudeRelayLocked(), Icons.lock),
(const ClaudeRelayFailed('boom'), Icons.error_outline),
]) {
testWidgets('$event paints its glyph and keeps the text', (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();
relay.emit(event);
await settle(tester);
expect(find.byIcon(glyph), findsOneWidget);
expect(find.text('kurczak'), findsOneWidget);
expect(sparkleEnabled(tester), isTrue); // a tap retries
});
});
}
}

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

@ -0,0 +1,146 @@
/// Due mode versus normal mode on the log screen: what shows, which slot a
/// log lands in, and when the status bar is hidden.
library;
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_screen.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/widgets/sync_health_banner.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';
final _plain = nutritionForPortion(
kcal: 100,
proteinG: 1,
carbsG: 1,
fatG: 1,
perGrams: 0,
ateGrams: 100,
source: 'manual',
);
void main() {
late Future<void> Function() restore;
late List<bool> statusBar;
setUp(() async {
restore = await isolateLogScreenState();
statusBar = [];
setStatusBarHidden = ({required hidden}) async => statusBar.add(hidden);
});
tearDown(() => restore());
Future<void> open(WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
await settle(tester);
}
Future<void> logTyped(WidgetTester tester, String text) async {
await tester.enterText(find.byType(TextField).at(0), text);
await settle(tester);
await tester.tap(controlByLabel('Log meal'));
await settle(tester);
}
testWidgets('due mode strips the bar, banner, date row and chips', (
tester,
) async {
pinLogMealClock(13);
await tester.runAsync(() async {
await open(tester);
expect(find.byType(AppBar), findsNothing);
expect(find.byType(SyncHealthBanner), findsNothing);
expect(find.byIcon(Icons.date_range), findsNothing);
expect(find.byType(ChoiceChip), findsNothing);
expect(find.byIcon(Icons.playlist_add_check), findsNothing);
// What stays: field, six macro fields, the three buttons.
expect(find.byType(TextField), findsNWidgets(7));
expect(byIconLabel('Photo'), findsOneWidget);
expect(byIconLabel('Ask Claude'), findsOneWidget);
expect(byIconLabel('Log meal'), findsOneWidget);
});
});
testWidgets('normal mode keeps the bar and date row, drops chips and fill', (
tester,
) async {
await tester.runAsync(() async {
await open(tester);
expect(find.byType(AppBar), findsOneWidget);
expect(find.byIcon(Icons.date_range), findsOneWidget);
expect(find.byType(ChoiceChip), findsNothing);
expect(find.byIcon(Icons.playlist_add_check), findsNothing);
expect(byIconLabel('Photo'), findsOneWidget);
expect(byIconLabel('Ask Claude'), findsOneWidget);
expect(statusBar, isEmpty, reason: 'normal mode never touches the bar');
});
});
testWidgets('both buttons target the oldest due slot, one after another', (
tester,
) async {
pinLogMealClock(13); // 08:00 and 12:00 due
await tester.runAsync(() async {
await open(tester);
await logTyped(tester, 'first');
await logTyped(tester, 'second');
final slots = (await LogStorageService.instance.todayEntries()).map(
(e) => e.slotMinute,
);
expect(slots, [480, 720]);
});
});
testWidgets('with nothing due the nearest slot is used', (tester) async {
pinLogMealClock(18); // 16:00 is the latest elapsed slot
await tester.runAsync(() async {
for (final minute in [480, 720, 960]) {
await LogStorageService.instance.logMeal(
'seed$minute',
_plain,
slotMinute: minute,
);
}
await open(tester);
expect(find.byType(AppBar), findsOneWidget);
await logTyped(tester, 'late snack');
final last = (await LogStorageService.instance.todayEntries()).last;
expect(last.slotMinute, 960);
});
});
testWidgets('the status bar hides in due mode and returns afterwards', (
tester,
) async {
pinLogMealClock(13);
await tester.runAsync(() async {
await open(tester);
expect(statusBar, [true]);
await logTyped(tester, 'first');
expect(statusBar, [true], reason: '12:00 is still due');
await logTyped(tester, 'second');
expect(statusBar, [true, false]);
});
});
testWidgets('leaving the screen in due mode restores the status bar', (
tester,
) async {
pinLogMealClock(13);
await tester.runAsync(() async {
await open(tester);
expect(statusBar, [true]);
await tester.pumpWidget(const SizedBox());
expect(statusBar, [true, false]);
});
});
test('the suite default clock is before the first slot', () {
final now = logMealClock();
expect(now.hour, 7);
});
}

View File

@ -1,245 +0,0 @@
/// "Fill all with catering" as the log form drives it.
///
/// `kuchnia_fill_flow_test.dart` proves the flow writes nothing until the
/// second tap. This covers what the *screen* must do around it: publish once
/// for the whole batch (and never after the first tap), drop the filled
/// dishes from the delivery queue, and not leave a just-logged dish
/// prefilled in the form where a second submit would duplicate it.
///
/// Driven through a minimal host, like `log_meal_kuchnia_mixin_test.dart`:
/// the real `LogMealScreen` fans out into sync and notifications and does not
/// pump to quiescence in a widget test.
library;
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/screens/log_meal_fill_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_kuchnia_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
import 'package:diet_guard_app/services/kuchnia_fill.dart';
import 'package:diet_guard_app/services/kuchnia_fill_flow.dart';
import 'package:diet_guard_app/services/kuchnia_import.dart';
import 'package:diet_guard_app/services/kuchnia_queue.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/widgets/macro_input_row.dart';
import 'package:material_ui/material_ui.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import '../kuchnia_fill_support.dart';
class _Host extends StatefulWidget {
const _Host(this.storage, this.delivery);
final LogStorageService storage;
final List<KuchniaDish> delivery;
@override
State<_Host> createState() => _HostState();
}
class _HostState extends State<_Host>
with
WidgetsBindingObserver,
LogMealSyncMixin<_Host>,
LogMealKuchniaMixin<_Host>,
LogMealFutureMixin<_Host>,
LogMealFillMixin<_Host> {
final TextEditingController desc = TextEditingController();
final MacroControllers macros = MacroControllers();
int publishes = 0;
String status = '';
CueKind statusKind = CueKind.info;
@override
int? selectedSlot;
@override
http.Client? get syncHttpClient => null;
@override
TextEditingController get descController => desc;
@override
MacroControllers get macroControllers => macros;
@override
void initState() {
super.initState();
fillFlow = FillAllFlow(
fetch: (_) async => KuchniaRefresh(dishes: widget.delivery),
slots: (_) => defaultSlots,
storage: widget.storage,
);
}
int? statusCount;
@override
void showFillStatus(FillCue cue) => setState(() {
status = cue.label;
statusKind = cue.kind;
statusCount = cue.count;
});
/// Counted instead of run: the real one starts a network sync.
@override
Future<DayLog> publishAfterLog() {
publishes++;
return widget.storage.readLog();
}
@override
Widget build(BuildContext context) =>
Text(status, textDirection: TextDirection.ltr);
}
void main() {
late LogStorageService storage;
late _HostState host;
final delivery = dishes(4);
Future<void> pumpHost(WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(home: _Host(storage, delivery)));
host = tester.state(find.byType(_Host));
// Mirrors the screen: the delivery is queued and the first dish prefilled.
KuchniaQueueService.instance.offer(delivery);
host.prefillNextDish();
}
setUp(() async {
storage = freshStorage();
await KuchniaQueueService.initForTesting(MemoryStore());
});
tearDown(() {
KuchniaQueueService.resetForTesting();
LogStorageService.resetForTesting();
});
testWidgets('the first tap only proposes: no write, no publish', (t) async {
await pumpHost(t);
await t.runAsync(host.onFillAll);
expect(host.status, startsWith('Will log 4'));
// Painted: a glyph + the number of dishes the confirm would log.
expect(host.statusCount, 4);
expect(await t.runAsync(storage.todayEntries), isEmpty);
expect(host.publishes, 0);
expect(KuchniaQueueService.remaining, 4);
expect(host.desc.text, 'D1');
});
testWidgets('confirm logs the batch, publishes once, empties the queue', (
t,
) async {
await pumpHost(t);
await t.runAsync(() async {
await host.onFillAll();
await host.onFillAll();
});
expect(host.status, 'Logged 4 catering dishes.');
expect(host.statusKind, CueKind.ok);
expect(host.statusCount, 4);
expect(await t.runAsync(() => loggedToday(storage)), hasLength(4));
expect(host.publishes, 1, reason: 'one publish per batch, not per dish');
expect(KuchniaQueueService.remaining, 0);
expect(host.loggedSlots, {480, 720, 960, 1200});
expect(host.desc.text, isEmpty, reason: 'D1 was logged by the fill');
});
testWidgets('a dish the fill skipped stays queued and prefilled', (t) async {
await pumpHost(t);
await t.runAsync(() async {
await storage.logMeal(
'own breakfast',
dishNutrition(dish('own', 1)),
slotMinute: 480,
);
await host.onFillAll();
await host.onFillAll();
});
// D1's slot was taken, so only D2..D4 landed and D1 is still on offer.
expect(host.status, 'Logged 3 catering dishes.');
expect(host.statusCount, 3);
expect(KuchniaQueueService.remaining, 1);
expect(host.desc.text, 'D1');
});
testWidgets('cancel says so and writes nothing', (t) async {
await pumpHost(t);
await t.runAsync(host.onFillAll);
host.onFillCancel();
await t.pump();
expect(host.status, contains('cancelled'));
expect(host.fillFlow.armedCount, 0);
expect(await t.runAsync(storage.todayEntries), isEmpty);
expect(host.publishes, 0);
});
testWidgets('a failure mid-fill publishes what landed and says so', (
t,
) async {
await pumpHost(t);
host.fillFlow = FillAllFlow(
fetch: (_) async => KuchniaRefresh(dishes: delivery),
slots: (_) => defaultSlots,
occupiedSlots: (_) async => throw Exception('storage unavailable'),
storage: storage,
);
await t.runAsync(host.onFillAll);
expect(host.status, startsWith('Fill all failed'));
expect(host.statusKind, CueKind.error);
expect(host.publishes, 1, reason: 'a partial batch must still sync');
expect(host.fillFlow.busy, isFalse);
});
testWidgets('a later-day fill leaves today alone and returns to it', (
t,
) async {
final now = DateTime.now();
final tomorrow = DateTime(now.year, now.month, now.day + 1);
await pumpHost(t);
await t.runAsync(() async {
await host.selectLogDate(tomorrow);
await host.onFillAll();
await host.onFillAll();
});
expect(
host.status,
'Logged 4 catering dishes for ${localDateKey(tomorrow)}.',
);
final log = await t.runAsync(storage.readLog);
expect(log![localDateKey(tomorrow)], hasLength(4));
expect(await t.runAsync(storage.todayEntries), isEmpty);
expect(host.publishes, 1);
expect(KuchniaQueueService.remaining, 4, reason: "today's queue untouched");
expect(host.desc.text, 'D1');
expect(host.futureDate, isNull);
});
testWidgets('changing the date disarms a proposal', (t) async {
final now = DateTime.now();
await pumpHost(t);
await t.runAsync(() async {
await host.selectLogDate(DateTime(now.year, now.month, now.day + 1));
await host.onFillAll();
});
expect(host.fillFlow.armedCount, 4);
host.resetFutureLog();
expect(host.fillFlow.armedCount, 0);
});
}

View File

@ -0,0 +1,181 @@
/// Due mode on a real phone's geometry: Pixel-class 1080x2400 at 2.625, with
/// the status-bar and gesture insets and the keyboard open.
///
/// Two promises (kuhy, 2026-11-17): the food field never moves between states,
/// and nothing scrolls with the keyboard up -- the whole form is reachable at
/// once. Heights are asserted, not eyeballed: a form that merely "looks fine"
/// in an unconstrained test viewport is the failure this guards against.
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';
void _phone(WidgetTester tester, {required bool keyboard}) {
tester.view
..physicalSize = const Size(1080, 2400)
..devicePixelRatio = 2.625
..padding = const FakeViewPadding(top: 132, bottom: 63)
..viewPadding = const FakeViewPadding(top: 132, bottom: 63)
..viewInsets = FakeViewPadding(bottom: keyboard ? 840 : 0);
addTearDown(tester.view.reset);
}
double _fieldTop(WidgetTester tester) =>
tester.getTopLeft(find.byType(TextField).at(0)).dy;
double _maxScroll(WidgetTester tester) => tester
.state<ScrollableState>(
find
.descendant(
of: find.byType(SingleChildScrollView),
matching: find.byType(Scrollable),
)
.first,
)
.position
.maxScrollExtent;
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 {
pinLogMealClock(13); // 08:00 and 12:00 are due, so logging one stays due
await tester.pumpWidget(MaterialApp(home: LogMealScreen(relay: relay)));
await settle(tester);
}
Future<void> fillWorstCase(WidgetTester tester) async {
await tester.enterText(find.byType(TextField).at(0), 'kurczak z ryzem');
final worst = ['1250', '2400', '1234', '1234', '1234', '1234'];
for (var i = 0; i < worst.length; i++) {
await tester.enterText(find.byType(TextField).at(i + 1), worst[i]);
}
await settle(tester);
}
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,
);
testWidgets('keyboard open: no scroll, field fixed across every state', (
tester,
) async {
_phone(tester, keyboard: true);
await tester.runAsync(() async {
await open(tester);
await fillWorstCase(tester);
final top = _fieldTop(tester);
expect(_maxScroll(tester), 0, reason: 'idle, worst-case values');
Future<void> expectSteady(String state) async {
// A spinner never settles, so pump a few frames instead.
await Future<void>.delayed(const Duration(milliseconds: 100));
await tester.pump(const Duration(milliseconds: 100));
expect(_fieldTop(tester), top, reason: '$state moved the field');
expect(_maxScroll(tester), 0, reason: '$state made the form scroll');
}
await tester.tap(controlByLabel('Ask Claude'));
await tester.pump();
await expectSteady('sending');
relay.emit(const ClaudeRelayQueued());
await expectSteady('queued');
relay.emit(const ClaudeRelayLocked());
await expectSteady('locked');
await tester.tap(controlByLabel('Sync is locked'));
await tester.pump();
relay.emit(const ClaudeRelayFailed('x'));
await expectSteady('error');
await tester.tap(controlByLabel('Claude failed'));
await tester.pump();
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.
expect(find.byType(AppBar), findsNothing);
await fillWorstCase(tester);
await expectSteady('logged row');
await tester.tap(controlByLabel('Log meal'));
await settle(tester);
// Both due slots are logged now: due mode ends, so this is the one
// transition where the field is allowed to move.
expect(find.byType(AppBar), findsOneWidget);
expect(
(await LogStorageService.instance.todayEntries()).map(
(e) => e.slotMinute,
),
[480, 720],
);
});
});
testWidgets('keyboard closed: the form fits too', (tester) async {
_phone(tester, keyboard: false);
await tester.runAsync(() async {
await open(tester);
await fillWorstCase(tester);
expect(_maxScroll(tester), 0);
expect(tester.takeException(), isNull);
});
});
testWidgets('the suggestion block is a fixed height, empty or full', (
tester,
) async {
_phone(tester, keyboard: true);
await tester.runAsync(() async {
await open(tester);
final empty = tester.getTopLeft(controlByLabel('Ask Claude')).dy;
await tester.enterText(find.byType(TextField).at(0), 'a');
await settle(tester);
expect(tester.getTopLeft(controlByLabel('Ask Claude')).dy, empty);
});
});
testWidgets('the scroll probe sees a squeezed form scroll', (tester) async {
// Proves the maxScrollExtent == 0 assertions above can fail: a keyboard
// far taller than a phone's must leave the form scrollable.
tester.view
..physicalSize = const Size(1080, 2400)
..devicePixelRatio = 2.625
..viewInsets = const FakeViewPadding(bottom: 1800);
addTearDown(tester.view.reset);
await tester.runAsync(() async {
await open(tester);
expect(_maxScroll(tester), greaterThan(0));
});
});
}

View File

@ -89,17 +89,16 @@ void main() {
});
});
testWidgets('a rejected log (empty description) gives only the error tick', (
testWidgets('a greyed log button (empty description) gives no feedback', (
tester,
) async {
await tester.runAsync(() async {
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
await settle(tester);
await tester.tap(controlByLabel('Log meal'));
await tester.tap(controlByLabel('Log meal'), warnIfMissed: false);
await settle(tester);
expect(cueLabelled('Type what you ate first.'), findsOneWidget);
// Only the error cue's own heavy tick: no success buzz.
expect(haptics, ['HapticFeedbackType.heavyImpact']);
// Nothing to log, so neither the success buzz nor the sound.
expect(haptics, isEmpty);
expect(cues, 0);
});
});

View File

@ -1,211 +0,0 @@
/// The delivered-dish queue as the log form actually drives it.
///
/// `kuchnia_queue_test.dart` covers the queue's own state machine. This file
/// covers the part that state machine exists for and that a queue-only test
/// cannot see: after a submit, are the **form controllers** already holding
/// the next dish?
///
/// That distinction is the whole point. On the PC this regressed once --
/// `_prefill_next_dish` briefly had exactly one caller, so the queue was
/// correct and the form was not. Every dish after the first stayed behind
/// another tap and the "(N more to go)" line became a dead letter. A test
/// asserting "the dish was offered" passes throughout that bug; one asserting
/// the controller contents after a submit does not.
///
/// Driven through a minimal host rather than the real `LogMealScreen`: that
/// screen's `initState` fans out into sync, notifications and the food bank,
/// and pumping it to quiescence in a widget test does not terminate. The
/// mixin is the unit that owns this behaviour, so it is the unit under test.
library;
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/screens/log_meal_kuchnia_mixin.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/kuchnia_queue.dart';
import 'package:diet_guard_app/widgets/macro_input_row.dart';
import 'package:material_ui/material_ui.dart';
import 'package:flutter_test/flutter_test.dart';
/// In-memory store, so these tests need no plugin channel.
class _MemoryStore implements DocumentStore {
final Map<String, String> documents = {};
@override
Future<String?> read(String name) async => documents[name];
@override
Future<void> write(String name, String contents) async {
documents[name] = contents;
}
}
/// The smallest widget that uses the mixin the way the log screen does.
class _Host extends StatefulWidget {
const _Host();
@override
State<_Host> createState() => _HostState();
}
class _HostState extends State<_Host> with LogMealKuchniaMixin<_Host> {
final TextEditingController desc = TextEditingController();
final MacroControllers macros = MacroControllers();
@override
void initState() {
super.initState();
for (final c in [
macros.kcal,
macros.protein,
macros.carbs,
macros.fat,
macros.perGrams,
macros.grams,
]) {
c.addListener(() {
if (source == 'food bank') source = 'manual';
});
}
}
@override
TextEditingController get descController => desc;
@override
MacroControllers get macroControllers => macros;
/// Mirrors the screen: a macro edit demotes a food-bank pick to manual,
/// and a prefilled dish stamps catering.
String source = 'manual';
@override
void onDishPrefilled() => source = 'catering';
/// Stands in for the screen's submit: the entry write is irrelevant here,
/// the queue advance is what is under test.
void submit() {
final logged = desc.text;
desc.clear();
macros.clear();
advanceQueueAfterLog(logged);
}
@override
Widget build(BuildContext context) =>
Text(queueStatusLine ?? '', textDirection: TextDirection.ltr);
}
KuchniaDish _dish(String name, int priority) => KuchniaDish(
name: name,
kcal: 400,
proteinG: 25,
carbsG: 45.5,
fatG: 12,
grams: 300,
priority: priority,
slotLabel: 'Obiad',
);
void main() {
late _HostState host;
Future<void> pumpHost(WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: _Host()));
host = tester.state(find.byType(_Host));
}
setUp(() async {
await KuchniaQueueService.initForTesting(_MemoryStore());
});
tearDown(KuchniaQueueService.resetForTesting);
testWidgets('after a submit the form already holds the next dish', (
tester,
) async {
await pumpHost(tester);
KuchniaQueueService.instance.offer([
_dish('Pancakes', 1),
_dish('Kaszotto', 2),
]);
host.prefillNextDish();
await tester.pump();
expect(host.desc.text, 'Pancakes');
host.submit();
await tester.pump();
expect(
host.desc.text,
'Kaszotto',
reason: 'the form must already hold dish 2. Empty here means the queue '
'is right and the form is not -- the dead-letter regression where '
'every dish after the first waits behind another tap.',
);
expect(KuchniaQueueService.remaining, 1);
});
testWidgets('the macros come with the dish, not just the name', (
tester,
) async {
await pumpHost(tester);
KuchniaQueueService.instance.offer([_dish('Pancakes', 1)]);
host.prefillNextDish();
await tester.pump();
// Whole numbers print without a trailing `.0`, matching Python's `:g`.
expect(host.macros.kcal.text, '400');
expect(host.macros.protein.text, '25');
expect(host.macros.carbs.text, '45.5');
expect(host.macros.fat.text, '12');
expect(host.macros.grams.text, '300');
});
testWidgets('the leftover dish is named rather than dropped', (tester) async {
// Five delivered meals against four default slots leaves one queued when
// the last slot is logged. It is already banked, so say so.
await pumpHost(tester);
KuchniaQueueService.instance.offer([_dish('A', 1), _dish('B', 2)]);
host.prefillNextDish();
await tester.pump();
host.submit();
await tester.pump();
expect(find.text('1 more delivered dish to log.'), findsOneWidget);
});
testWidgets('editing the description does not consume the offer', (
tester,
) async {
// What the user logged was not the delivered dish, so marking it eaten
// would lose a real delivered meal silently.
await pumpHost(tester);
KuchniaQueueService.instance.offer([_dish('Pancakes', 1)]);
host.prefillNextDish();
await tester.pump();
host.desc.text = 'Something else';
host.submit();
await tester.pump();
expect(KuchniaQueueService.remaining, 1);
});
testWidgets('an empty queue clears the offer instead of throwing', (
tester,
) async {
await pumpHost(tester);
host.prefillNextDish();
await tester.pump();
expect(host.offeredDish, isNull);
expect(host.queueStatusLine, isNull);
});
testWidgets('submitting with nothing offered is a no-op', (tester) async {
await pumpHost(tester);
host.submit();
await tester.pump();
expect(KuchniaQueueService.remaining, 0);
});
}

View File

@ -1,183 +0,0 @@
/// What a prefilled dish actually *logs*, as distinct from what it displays.
///
/// Split from `log_meal_kuchnia_mixin_test.dart` (250-line cap) along the
/// seam the 2026-08-23 corruption exposed: that file asserts the queue's
/// mechanics and the controllers' text, and every one of its tests passed
/// while a delivered dish logged 2.58x its real calories. The bug lived in
/// the *computed* `Nutrition`, which nothing there looked at.
///
/// So these tests assert the computed value, never the field text.
library;
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/screens/log_meal_actions.dart';
import 'package:diet_guard_app/screens/log_meal_kuchnia_mixin.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/kuchnia_queue.dart';
import 'package:diet_guard_app/widgets/macro_input_row.dart';
import 'package:material_ui/material_ui.dart';
import 'package:flutter_test/flutter_test.dart';
/// In-memory store, so these tests need no plugin channel.
class _MemoryStore implements DocumentStore {
final Map<String, String> documents = {};
@override
Future<String?> read(String name) async => documents[name];
@override
Future<void> write(String name, String contents) async {
documents[name] = contents;
}
}
/// The smallest widget that uses the mixin the way the log screen does.
class _Host extends StatefulWidget {
const _Host();
@override
State<_Host> createState() => _HostState();
}
class _HostState extends State<_Host> with LogMealKuchniaMixin<_Host> {
final TextEditingController desc = TextEditingController();
final MacroControllers macros = MacroControllers();
@override
void initState() {
super.initState();
for (final c in [
macros.kcal,
macros.protein,
macros.carbs,
macros.fat,
macros.perGrams,
macros.grams,
]) {
c.addListener(() {
if (source == 'food bank') source = 'manual';
});
}
}
@override
TextEditingController get descController => desc;
@override
MacroControllers get macroControllers => macros;
/// Mirrors the screen: a macro edit demotes a food-bank pick to manual,
/// and a prefilled dish stamps catering.
String source = 'manual';
@override
void onDishPrefilled() => source = 'catering';
/// Stands in for the screen's submit: the entry write is irrelevant here,
/// the queue advance is what is under test.
void submit() {
final logged = desc.text;
desc.clear();
macros.clear();
advanceQueueAfterLog(logged);
}
@override
Widget build(BuildContext context) =>
Text(queueStatusLine ?? '', textDirection: TextDirection.ltr);
}
KuchniaDish _dish(String name, int priority) => KuchniaDish(
name: name,
kcal: 400,
proteinG: 25,
carbsG: 45.5,
fatG: 12,
grams: 300,
priority: priority,
slotLabel: 'Obiad',
);
void main() {
late _HostState host;
Future<void> pumpHost(WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: _Host()));
host = tester.state(find.byType(_Host));
}
setUp(() async {
await KuchniaQueueService.initForTesting(_MemoryStore());
});
tearDown(KuchniaQueueService.resetForTesting);
testWidgets('a stale per-grams does not rescale the prefilled dish', (
tester,
) async {
// The 2026-08-23 corruption: a food-bank pick leaves `perGrams` at 100,
// the dish prefills over it without clearing, and `nutritionForPortion`
// reads the dish's *per-portion* macros as *per-100g* and multiplies them
// by 300/100. Asserting controller text passes throughout that bug --
// only the computed Nutrition sees it.
await pumpHost(tester);
host.macros.perGrams.text = '100';
KuchniaQueueService.instance.offer([_dish('Pancakes', 1)]);
host.prefillNextDish();
await tester.pump();
final nutrition = nutritionFromControllers(host.macros, 'kuchnia wikinga');
expect(
nutrition.kcal,
400,
reason: 'the dish must log its own calories. 1200 here is the stale '
'per-grams rescaling a per-portion dish by 300/100.',
);
expect(nutrition.proteinG, 25);
expect(nutrition.carbsG, 45.5);
expect(nutrition.fatG, 12);
expect(nutrition.grams, 300);
});
testWidgets('clear() empties every macro controller', (tester) async {
// Enumerated deliberately: the bug was a *forgotten* field, so a new
// seventh controller must fail this until it is cleared too.
await pumpHost(tester);
final controllers = <String, TextEditingController>{
'kcal': host.macros.kcal,
'protein': host.macros.protein,
'carbs': host.macros.carbs,
'fat': host.macros.fat,
'perGrams': host.macros.perGrams,
'grams': host.macros.grams,
};
for (final c in controllers.values) {
c.text = '99';
}
host.macros.clear();
controllers.forEach((name, c) {
expect(c.text, isEmpty, reason: '$name survived clear()');
});
});
testWidgets('the prefill stamps catering even though clearing demotes it', (
tester,
) async {
// Ordering is load-bearing and invisible: `clear()` fires the macro
// listener, which demotes a food-bank pick to 'manual'. `onDishPrefilled`
// runs after and must have the last word, or a delivered dish logs as a
// manual entry and the queue never advances.
await pumpHost(tester);
host.source = 'food bank';
host.macros.perGrams.text = '100';
KuchniaQueueService.instance.offer([_dish('Pancakes', 1)]);
host.prefillNextDish();
await tester.pump();
expect(host.source, 'catering');
});
}

View File

@ -1,4 +1,4 @@
/// The log screen's slot row versus a meal-schedule change.
/// The log screen's due slots versus a meal-schedule change.
///
/// Split from `log_meal_screen_test.dart` for the repo's 250-line cap.
library;
@ -6,6 +6,7 @@ library;
import 'dart:io';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_nav_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
@ -17,6 +18,8 @@ import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:material_ui/material_ui.dart';
import 'package:flutter_test/flutter_test.dart';
import 'log_meal_test_support.dart' show pinLogMealClock;
void main() {
late Directory tempDir;
@ -43,31 +46,32 @@ void main() {
await tester.pumpAndSettle();
}
testWidgets('the slot row follows a schedule change made in settings', (
testWidgets('the due slots follow a schedule change made in settings', (
tester,
) async {
// Found on the phone: the settings preview and the overdue reminder both
// picked up a four -> five meal change while the row behind them kept
// rendering the old four checkpoints until the app was restarted, because
// onOpenSettings pushed without awaiting the pop.
// picked up a schedule change while the screen behind them kept the old
// checkpoints until the app was restarted, because onOpenSettings pushed
// without awaiting the pop.
pinLogMealClock(13);
await tester.runAsync(() async {
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
await settle(tester);
expect(find.text('12:00'), findsOneWidget);
await MealScheduleService.instance.recordChange(
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
);
final state = tester.state<State<LogMealScreen>>(
find.byType(LogMealScreen),
);
final due = state as LogMealDueMixin<LogMealScreen>;
expect(due.dueSlots, [480, 720]);
await MealScheduleService.instance.recordChange(
const MealSchedule(firstMinute: 9 * 60, lastMinute: 21 * 60, count: 4),
);
await (state as LogMealNavMixin<LogMealScreen>)
.onScheduleMayHaveChanged();
await settle(tester);
expect(find.text('11:00'), findsOneWidget);
expect(find.text('17:00'), findsOneWidget);
expect(find.text('12:00'), findsNothing);
expect(due.dueSlots, [540, 780]);
expect(due.targetSlot, 540);
});
});
}

View File

@ -144,55 +144,14 @@ void main() {
expect(find.byType(FoodBankScreen), findsOneWidget);
});
});
testWidgets('logged slot chip renders check-icon avatar', (tester) async {
await tester.runAsync(() async {
final now = DateTime.now();
final dateKey =
'${now.year.toString().padLeft(4, '0')}-'
'${now.month.toString().padLeft(2, '0')}-'
'${now.day.toString().padLeft(2, '0')}';
final at8 = DateTime(now.year, now.month, now.day, 8);
await LogStorageService.instance.writeLog({
dateKey: [
FoodEntry(
id: 'slot-seed',
time: at8.toIso8601String(),
desc: 'breakfast',
grams: 100,
kcal: 300,
proteinG: 10,
carbsG: 40,
fatG: 5,
source: 'manual',
slotMinute: 480,
),
],
});
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
await settle(tester);
// The 08:00 slot is logged — its ChoiceChip has a check-icon avatar.
expect(find.byIcon(Icons.check), findsWidgets);
});
});
testWidgets('tapping a slot chip selects it', (tester) async {
testWidgets('normal mode has no slot chips', (tester) async {
await tester.runAsync(() async {
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
await settle(tester);
// Tap the 08:00 chip to force _selectedSlot = 8.
await tester.tap(find.text('08:00'));
await settle(tester);
final chip = tester.widget<ChoiceChip>(
find.ancestor(
of: find.text('08:00'),
matching: find.byType(ChoiceChip),
),
);
expect(chip.selected, isTrue);
// The slot is derived (oldest due, else nearest), never picked.
expect(find.byType(ChoiceChip), findsNothing);
expect(find.text('08:00'), findsNothing);
});
});
}

View File

@ -39,11 +39,6 @@ class _FakeUrlLauncher extends UrlLauncherPlatform
}
}
/// Returns a fixed [XFile] without touching any real platform channel.
/// A minimal valid 1x1 transparent PNG, so the thumbnail preview can decode
/// it as a real image instead of throwing on bogus bytes.
void main() {
late Directory tempDir;
@ -152,17 +147,27 @@ void main() {
expect(find.byType(TodayProgressCard), findsNothing);
});
});
testWidgets('refuses to log with an empty description', (tester) async {
testWidgets('the log button is greyed until a description is typed', (
tester,
) async {
await tester.runAsync(() async {
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
await settle(tester);
await tester.ensureVisible(logMealButton);
await tester.tap(logMealButton);
FilledButton log() => tester.widget<FilledButton>(
find.ancestor(
of: byIconLabel('Log meal'),
matching: find.byType(FilledButton),
),
);
expect(log().onPressed, isNull);
await tester.tap(logMealButton, warnIfMissed: false);
await settle(tester);
expect(cueLabelled('Type what you ate first.'), findsOneWidget);
expect(await LogStorageService.instance.todayEntries(), isEmpty);
await tester.enterText(find.byType(TextField).at(0), 'toast');
await settle(tester);
expect(log().onPressed, isNotNull);
});
});
testWidgets(
@ -217,7 +222,7 @@ void main() {
await settle(tester);
// The empty-query suggestion list shows the only banked food.
await tester.tap(find.text('seeded food'));
await tester.tap(find.text('seeded food').first);
await settle(tester);
await tester.ensureVisible(logMealButton);
await tester.tap(logMealButton);
@ -228,7 +233,7 @@ void main() {
expect(firstEntry.source, 'food bank');
expect(firstEntry.kcal, 250);
await tester.tap(find.text('seeded food'));
await tester.tap(find.text('seeded food').first);
await settle(tester);
await tester.enterText(find.byType(TextField).at(2), '999');
await settle(tester);

View File

@ -0,0 +1,53 @@
/// Shared setup for the log screen's due-mode tests.
library;
import 'dart:io';
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/kuchnia_autolog.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:flutter_test/flutter_test.dart';
/// Pins the screen's clock to [hour]:[minute] today for this test only; the
/// suite default (07:00, before the first slot) comes back afterwards.
void pinLogMealClock(int hour, [int minute = 0]) {
final previous = logMealClock;
final today = DateTime.now();
logMealClock = () =>
DateTime(today.year, today.month, today.day, hour, minute);
addTearDown(() => logMealClock = previous);
}
/// Points every singleton the screen touches at a fresh temp directory.
///
/// Call from `setUp`; the returned function undoes it, for `tearDown`.
Future<Future<void> Function()> isolateLogScreenState() async {
final dir = await Directory.systemTemp.createTemp('diet_guard_due_');
LogStorageService.resetForTesting(store: FileDocumentStore(dir));
FoodBankService.resetForTesting(store: FileDocumentStore(dir));
AppSettingsService.resetForTesting(store: FileDocumentStore(dir));
BudgetHistoryService.resetForTesting(store: FileDocumentStore(dir));
await MealScheduleService.initForTesting(FileDocumentStore(dir));
KuchniaAutoLog.instance = KuchniaAutoLog();
return () async {
LogStorageService.resetForTesting();
FoodBankService.resetForTesting();
AppSettingsService.resetForTesting();
BudgetHistoryService.resetForTesting();
MealScheduleService.resetForTesting();
KuchniaAutoLog.instance = KuchniaAutoLog();
await dir.delete(recursive: true);
};
}
/// Lets real file I/O finish, then settles the frame (the screens' file
/// stores run outside the fake-async zone).
Future<void> settle(WidgetTester tester) async {
await Future<void>.delayed(const Duration(milliseconds: 200));
await tester.pumpAndSettle();
}

View File

@ -0,0 +1,80 @@
/// The relay interface and its fake: the contract the screen depends on.
library;
import 'dart:async';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/services/claude_relay_client.dart';
import 'package:diet_guard_app/services/claude_relay_fake.dart';
import 'package:flutter_test/flutter_test.dart';
const _request = ClaudeRelayRequest(
requestId: '01JD5Z8K3M7Q2W9XH4TBN6VR0E',
slotMinute: 480,
text: 'x',
);
void main() {
test(
'queued is not terminal: the same stream later delivers the meal',
() async {
final relay = FakeClaudeRelayClient();
final events = <ClaudeRelayEvent>[];
final done = Completer<void>();
relay.send(_request).listen(events.add, onDone: done.complete);
relay.emit(const ClaudeRelayQueued());
await Future<void>.delayed(Duration.zero);
expect(done.isCompleted, isFalse);
final entry = FoodEntry(
id: claudeEntryId(_request.requestId),
time: 't',
desc: 'x',
grams: 1,
kcal: 1,
proteinG: 1,
carbsG: 1,
fatG: 1,
source: 'claude',
);
relay.emit(ClaudeRelayLogged(entry));
await done.future;
expect(events.map((e) => e.runtimeType), [
ClaudeRelayQueued,
ClaudeRelayLogged,
]);
expect(
(events.last as ClaudeRelayLogged).entry.id,
claudeEntryId(_request.requestId),
);
},
);
for (final event in [
const ClaudeRelayLocked(),
const ClaudeRelayFailed('boom'),
]) {
test('${event.runtimeType} ends the stream', () async {
final relay = FakeClaudeRelayClient();
final done = Completer<void>();
relay.send(_request).listen((_) {}, onDone: done.complete);
relay.emit(event);
await done.future;
});
}
test('the fake records every request', () {
final relay = FakeClaudeRelayClient()
..send(_request).listen((_) {})
..send(_request).listen((_) {});
expect(relay.sent, hasLength(2));
});
test('the unwired client fails closed', () async {
final events = await const UnconfiguredClaudeRelayClient()
.send(_request)
.toList();
expect(events.single, isA<ClaudeRelayFailed>());
});
}

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,84 @@
/// The catering auto-log entry ids against the shared fixture.
///
/// `tests/fixtures/kuchnia_autolog_ids.json` is generated by Python's stdlib
/// `uuid.uuid5` (scripts/build_kuchnia_autolog_fixture.py), so this test
/// checks a value Dart did not compute itself.
library;
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/services/kuchnia_autolog.dart';
import 'package:diet_guard_app/services/kuchnia_parse.dart';
import 'package:flutter_test/flutter_test.dart';
Map<String, dynamic> _fixture() {
var dir = Directory.current;
while (!File(
'${dir.path}/tests/fixtures/kuchnia_autolog_ids.json',
).existsSync()) {
dir = dir.parent;
}
return jsonDecode(
File(
'${dir.path}/tests/fixtures/kuchnia_autolog_ids.json',
).readAsStringSync(),
)
as Map<String, dynamic>;
}
/// The payload meal the fixture case describes, as the panel sends it.
Map<String, Object?> _payloadMeal(Map<String, dynamic> c) => {
if (c['delivery_meal_id'] != null) 'deliveryMealId': c['delivery_meal_id'],
'mealName': 'Obiad',
'mealPriority': 3,
'menuMealName': c['name'],
'nutrition': {
'weight': 300.0,
'calories': 400.0,
'protein': 25.0,
'carbohydrate': 45.0,
'fat': 12.0,
},
};
void main() {
final fixture = _fixture();
final cases = (fixture['cases'] as List).cast<Map<String, dynamic>>();
test('the fixture uses the RFC URL namespace', () {
expect(fixture['namespace'], '6ba7b811-9dad-11d1-80b4-00c04fd430c8');
expect(cases, isNotEmpty);
});
for (final c in cases) {
test('${c['name_string']} -> ${c['expected_id']}', () {
final dish = parseMeal(_payloadMeal(c), 1)!;
expect(
kuchniaAutologId(c['delivery_date'] as String, dish),
c['expected_id'],
);
});
}
test('the panel id never leaks into the bank record', () {
final dish = parseMeal(_payloadMeal(cases.first), 1)!;
expect(dish.toBankRecord().containsKey('dishId'), isFalse);
expect(dish.dishId, '1001');
});
test('a dish with no id keys on its bank key', () {
const dish = KuchniaDish(
name: ' Zupa ',
kcal: 1,
proteinG: 0,
carbsG: 0,
fatG: 0,
grams: 1,
priority: 1,
slotLabel: '',
);
expect(dish.autologKey, 'zupa');
});
}

View File

@ -0,0 +1,143 @@
/// Catering auto-log: due slots log their dish without a tap, exactly once.
library;
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/services/kuchnia_autolog.dart';
import 'package:diet_guard_app/services/kuchnia_fill.dart';
import 'package:diet_guard_app/services/kuchnia_import.dart';
import 'package:diet_guard_app/services/log_entry_lookup.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/sync_merge.dart';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter_test/flutter_test.dart';
import '../kuchnia_fill_support.dart';
KuchniaDish _dish(int n) => KuchniaDish(
name: 'D$n',
kcal: 100.0 * n,
proteinG: 10,
carbsG: 20,
fatG: 5,
grams: 300,
priority: n,
slotLabel: '',
dishId: '${1000 + n}',
);
void main() {
late LogStorageService storage;
late int fetches;
late KuchniaRefresh result;
late DateTime clock;
late KuchniaAutoLog autoLog;
setUp(() {
storage = freshStorage();
fetches = 0;
result = KuchniaRefresh(dishes: [for (var i = 1; i <= 4; i++) _dish(i)]);
final today = DateTime.now();
clock = DateTime(today.year, today.month, today.day, 13);
autoLog = KuchniaAutoLog(
fetch: (day) async {
fetches++;
return result;
},
now: () => clock,
);
});
test('logs only the dishes of the due slots, source catering', () async {
final written = await autoLog.logDue([480, 720]);
expect(written.map((e) => e.desc), ['D1', 'D2']);
expect(written.map((e) => e.slotMinute), [480, 720]);
expect(written.every((e) => e.source == kuchniaSource), isTrue);
expect(await loggedToday(storage), ['D1@480', 'D2@720']);
});
test('ids are the deterministic v5 ids', () async {
final written = await autoLog.logDue([480]);
final day = written.single.time.substring(0, 10);
expect(written.single.id, kuchniaAutologId(day, _dish(1)));
});
test('opening twice leaves one entry per dish', () async {
await autoLog.logDue([480, 720]);
final second = await KuchniaAutoLog(
fetch: (day) async => result,
now: () => clock,
).logDue([480, 720]);
expect(second, isEmpty);
expect(await loggedToday(storage), ['D1@480', 'D2@720']);
});
test('an undone dish is not logged again on the next open', () async {
final first = await autoLog.logDue([480]);
await storage.deleteEntry(first.single.id!);
final again = await KuchniaAutoLog(
fetch: (day) async => result,
now: () => clock,
).logDue([480]);
expect(again, isEmpty);
expect(await storage.todayEntries(), isEmpty);
expect((await storage.findEntry(first.single.id!))!.deleted, isTrue);
});
test('a copy logged on another device merges to one entry', () async {
final mine = (await autoLog.logDue([480])).single;
final theirs = FoodEntry(
id: mine.id,
time: mine.time.replaceRange(17, 19, '59'),
desc: mine.desc,
grams: mine.grams,
kcal: mine.kcal,
proteinG: mine.proteinG,
carbsG: mine.carbsG,
fatG: mine.fatG,
source: mine.source,
slotMinute: mine.slotMinute,
);
final merged = logToDayLog(
mergeLogs(
dayLogToLog(await storage.readLog()),
dayLogToLog({
mine.time.substring(0, 10): [theirs],
}),
),
);
expect(merged.values.expand((e) => e), hasLength(1));
});
test('later slots find their dish without a second fetch', () async {
await autoLog.logDue([480]);
final later = await autoLog.logDue([720]);
expect(later.map((e) => e.desc), ['D2']);
expect(fetches, 1);
});
test('an empty or failed fetch is retried only after the gap', () async {
result = const KuchniaRefresh(reason: 'offline');
expect(await autoLog.logDue([480]), isEmpty);
expect(await autoLog.logDue([480]), isEmpty);
expect(fetches, 1);
clock = clock.add(const Duration(minutes: 11));
result = KuchniaRefresh(dishes: [_dish(1)]);
expect((await autoLog.logDue([480])).single.desc, 'D1');
expect(fetches, 2);
});
test('nothing due fetches nothing', () async {
expect(await autoLog.logDue(const []), isEmpty);
expect(fetches, 0);
});
test('a slot that already holds a meal is left alone', () async {
await storage.logMeal(
'manual toast',
dishNutrition(_dish(1)),
slotMinute: 480,
);
expect(await autoLog.logDue([480]), isEmpty);
});
}

View File

@ -2,9 +2,8 @@
///
/// Three behaviours here are load-bearing, and each fails silently if broken:
///
/// * **Nothing is ever logged.** A delivered meal is not an eaten meal; if the
/// import logged, the gate would satisfy its own checkpoint from a delivery
/// note.
/// * **The fetch only banks.** Logging is `kuchnia_autolog.dart`'s job (see
/// `kuchnia_autolog_test.dart`); `refreshDelivery` itself writes no entry.
/// * **Unchanged dishes are not re-banked.** `addManualEntry` restamps
/// `editedAt` unconditionally and the merge derives each record's clock from
/// it, so re-banking republishes the whole curated bank to every peer. The
@ -130,7 +129,7 @@ void main() {
expect(result.dishes.single.name, 'Kaszotto');
final bank = await FoodBankService.instance.readManualBank();
expect(bank.keys, contains('kaszotto'));
// The whole point: a delivered meal is not an eaten meal.
// The fetch banks; it never logs.
expect(await LogStorageService.instance.todayEntries(), isEmpty);
});

View File

@ -0,0 +1,66 @@
/// The photo source: permission before camera, bytes only, cache file dropped.
library;
import 'dart:typed_data';
import 'package:diet_guard_app/services/meal_photo_source.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:image_picker/image_picker.dart';
void main() {
final jpeg = Uint8List.fromList([0xFF, 0xD8, 0xFF, 0xD9]);
late List<ImageSource> picked;
late List<String> discarded;
late int permissionAsks;
late bool granted;
late XFile? next;
ImagePickerPhotoSource source() => ImagePickerPhotoSource(
pickFile: (s) async {
picked.add(s);
return next;
},
requestCamera: () async {
permissionAsks++;
return granted;
},
discard: (path) async => discarded.add(path),
);
setUp(() {
picked = [];
discarded = [];
permissionAsks = 0;
granted = true;
next = XFile.fromData(jpeg, path: '/cache/pick.jpg');
});
test('the camera is not opened until permission is granted', () async {
granted = false;
expect(await source().pick(PhotoOrigin.camera), isNull);
expect(permissionAsks, 1);
expect(picked, isEmpty);
});
test('a granted camera pick returns the bytes and drops the file', () async {
expect(await source().pick(PhotoOrigin.camera), jpeg);
expect(picked, [ImageSource.camera]);
expect(discarded, ['/cache/pick.jpg']);
});
test('the gallery needs no camera permission', () async {
expect(await source().pick(PhotoOrigin.gallery), jpeg);
expect(permissionAsks, 0);
expect(picked, [ImageSource.gallery]);
});
test('backing out of the picker returns nothing', () async {
next = null;
expect(await source().pick(PhotoOrigin.gallery), isNull);
expect(discarded, isEmpty);
});
test('photos are scaled to 1024 px', () {
expect(mealPhotoMaxEdge, 1024);
});
}

View File

@ -1,108 +0,0 @@
/// The log form's action row, and the delivery button the phone lacked.
///
/// The PC lock screen has had a "🍱 Today's delivery" button since the import
/// shipped; the phone had the queue but no visible control, so standing in
/// the kitchen there was nothing to tap. These tests pin the affordance and
/// the two ways it silently fails: a clipped label, and a dead control on the
/// web build.
library;
import 'package:diet_guard_app/widgets/log_meal_actions_row.dart';
import 'package:material_ui/material_ui.dart';
import 'package:flutter_test/flutter_test.dart';
import '../label_finders.dart';
void main() {
Future<void> pump(
WidgetTester tester, {
int queued = 0,
bool busy = false,
bool canFetch = true,
Future<void> Function()? onLoad,
VoidCallback? onLog,
double width = 360,
}) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SizedBox(
width: width,
child: LogMealActionsRow(
onLoadDelivery: onLoad ?? () async {},
onLog: onLog ?? () {},
deliveryBusy: busy,
dishesQueued: queued,
canFetchDelivery: canFetch,
),
),
),
),
);
}
testWidgets('the delivery button is there to tap', (tester) async {
var taps = 0;
await pump(tester, onLoad: () async => taps++);
await tester.tap(find.byIcon(Icons.restaurant));
await tester.pump();
expect(taps, 1);
});
testWidgets('the queue count is a numeral beside the icon', (tester) async {
await pump(tester, queued: 4);
expect(find.text('4'), findsOneWidget);
expect(byIconLabel("Load today's catering delivery"), findsOneWidget);
});
testWidgets('nothing queued shows no numeral and never overflows', (
tester,
) async {
await pump(tester, width: 300);
await tester.pumpAndSettle();
expect(find.text('0'), findsNothing);
expect(tester.takeException(), isNull);
});
testWidgets('a fetch in flight disables the button and spins', (
tester,
) async {
await pump(tester, busy: true);
final button = tester.widget<OutlinedButton>(find.byType(OutlinedButton));
expect(button.onPressed, isNull);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
});
testWidgets('the button stays visible with nothing queued', (tester) async {
// Never hidden or disabled on an empty queue: the outcome arrives as a
// cue so a late delivery can still be retried.
await pump(tester);
expect(byIconLabel("Load today's catering delivery"), findsOneWidget);
final button = tester.widget<OutlinedButton>(find.byType(OutlinedButton));
expect(button.onPressed, isNotNull);
});
testWidgets('web gets no delivery button at all', (tester) async {
// The desktop target *is* the web build, and the caterer's panel blocks
// browser requests -- an unguarded button would ship a dead control.
await pump(tester, canFetch: false);
expect(find.byIcon(Icons.restaurant), findsNothing);
expect(find.byIcon(Icons.check_circle), findsOneWidget);
});
testWidgets('the log button still logs', (tester) async {
var logged = 0;
await pump(tester, onLog: () => logged++);
await tester.tap(find.byIcon(Icons.check_circle));
await tester.pump();
expect(logged, 1);
});
}

View File

@ -0,0 +1,95 @@
/// The macro fields at the worst case: every value four digits wide.
///
/// "No overflow exception" proves nothing here -- a Row of Expanded fields
/// clips its text silently (see the row-expanded-clips-chips memory) -- so each
/// test measures the painted digits against the width the field really has.
library;
import 'package:diet_guard_app/ui/theme.dart';
import 'package:diet_guard_app/widgets/macro_input_row.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.dart';
/// `flutter test` paints with Ahem, whose every glyph is one em wide. Roboto's
/// digits (the phone's font) are 0.5615 em, so measured widths are scaled down
/// to what the phone paints; without this the check would demand room no real
/// font needs.
const _ahemToRoboto = 0.5615;
const _worst = ['1250', '2400', '1234', '1234', '1234', '1234'];
Future<MacroControllers> _pump(WidgetTester tester, double width) async {
tester.view
..physicalSize = Size(width * 2, 1600)
..devicePixelRatio = 2;
addTearDown(tester.view.reset);
final macros = MacroControllers();
addTearDown(macros.dispose);
final all = [
macros.perGrams,
macros.kcal,
macros.protein,
macros.carbs,
macros.fat,
macros.grams,
];
for (var i = 0; i < all.length; i++) {
all[i].text = _worst[i];
}
await tester.pumpWidget(
MaterialApp(
theme: buildAppTheme(),
home: Scaffold(
body: Padding(
padding: const EdgeInsets.all(AppSpacing.md),
child: MacroInputRow(controllers: macros, compact: true),
),
),
),
);
return macros;
}
void main() {
for (final width in [411.0, 360.0]) {
group('at $width dp', () {
testWidgets('four digits fit the field at 16 sp or more', (tester) async {
await _pump(tester, width);
final editables = tester.widgetList<EditableText>(
find.byType(EditableText),
);
expect(editables, hasLength(6));
for (final (i, editable) in editables.indexed) {
expect(editable.style.fontSize, greaterThanOrEqualTo(16));
final painter = TextPainter(
text: TextSpan(text: _worst[i], style: editable.style),
textDirection: TextDirection.ltr,
)..layout();
final room = tester.getSize(find.byType(EditableText).at(i)).width;
final painted = painter.width * _ahemToRoboto;
expect(
painted,
lessThanOrEqualTo(room),
reason: '${_worst[i]} is clipped: $painted > $room',
);
}
expect(tester.takeException(), isNull);
});
testWidgets('six fields sit in two rows of three', (tester) async {
await _pump(tester, width);
final tops = [
for (var i = 0; i < 6; i++)
tester.getTopLeft(find.byType(TextField).at(i)),
];
expect(tops[0].dy, tops[1].dy);
expect(tops[1].dy, tops[2].dy);
expect(tops[3].dy, tops[4].dy);
expect(tops[4].dy, tops[5].dy);
expect(tops[3].dy, greaterThan(tops[0].dy));
expect(tops[0].dx, lessThan(tops[1].dx));
});
});
}
}

View File

@ -0,0 +1,179 @@
/// The 1A action row: photo, Claude, log; greyed until there is something.
library;
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/widgets/logged_meal_row.dart';
import 'package:diet_guard_app/widgets/meal_action_row.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.dart';
import '../label_finders.dart';
Widget _row({
ClaudeButtonState claude = ClaudeButtonState.idle,
bool photo = false,
bool canSend = true,
bool canLog = true,
List<String>? taps,
}) => MaterialApp(
home: Scaffold(
body: MealActionRow(
claude: claude,
photoAttached: photo,
canSend: canSend,
canLog: canLog,
onPhoto: () => taps?.add('photo'),
onGallery: () => taps?.add('gallery'),
onRemovePhoto: () => taps?.add('remove'),
onSend: () => taps?.add('send'),
onLog: () => taps?.add('log'),
),
),
);
bool _enabled(WidgetTester tester, String label) {
final button = tester.widget<FilledButton>(
find.ancestor(of: byIconLabel(label), matching: find.byType(FilledButton)),
);
return button.onPressed != null;
}
void main() {
testWidgets('tap is the camera, long press is the gallery', (tester) async {
final taps = <String>[];
await tester.pumpWidget(_row(taps: taps));
await tester.tap(controlByLabel('Photo'));
await tester.longPress(controlByLabel('Photo'));
expect(taps, ['photo', 'gallery']);
});
testWidgets('send and log are greyed with nothing to send or log', (
tester,
) async {
await tester.pumpWidget(_row(canSend: false, canLog: false));
expect(_enabled(tester, 'Ask Claude'), isFalse);
expect(_enabled(tester, 'Log meal'), isFalse);
expect(_enabled(tester, 'Photo'), isTrue);
});
testWidgets('an attached photo shows both badges and removes on the x', (
tester,
) async {
final taps = <String>[];
await tester.pumpWidget(_row(photo: true, taps: taps));
expect(byIconLabel('Photo attached'), findsOneWidget);
await tester.tap(byIconLabel('Remove photo'));
expect(taps, ['remove']);
expect(find.byType(Image), findsNothing);
});
testWidgets('no badges without a photo', (tester) async {
await tester.pumpWidget(_row());
expect(byIconLabel('Photo attached'), findsNothing);
expect(byIconLabel('Remove photo'), findsNothing);
});
for (final (state, label) in [
(ClaudeButtonState.queued, 'Waiting for the PC'),
(ClaudeButtonState.locked, 'Sync is locked'),
(ClaudeButtonState.error, 'Claude failed'),
]) {
testWidgets('$state paints its own glyph', (tester) async {
await tester.pumpWidget(_row(claude: state));
expect(byIconLabel(label), findsOneWidget);
expect(byIconLabel('Ask Claude'), findsNothing);
});
}
testWidgets('sending shows a spinner and blocks a second send', (
tester,
) async {
await tester.pumpWidget(_row(claude: ClaudeButtonState.sending));
expect(find.byType(CircularProgressIndicator), findsOneWidget);
final send = tester.widget<FilledButton>(find.byType(FilledButton).at(1));
expect(send.onPressed, isNull);
});
testWidgets('a locked or failed button can be tapped to retry', (
tester,
) async {
final taps = <String>[];
await tester.pumpWidget(_row(claude: ClaudeButtonState.error, taps: taps));
await tester.tap(find.byType(FilledButton).at(1));
expect(taps, ['send']);
});
testWidgets('a logged row names the meal and undoes on a 48 dp button', (
tester,
) async {
var undone = 0;
const entry = FoodEntry(
id: 'a',
time: '2026-11-17T12:00:00',
desc: 'kurczak z ryzem',
grams: 300,
kcal: 540,
proteinG: 42,
carbsG: 61,
fatG: 9,
source: 'claude',
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: LoggedMealRow(
meal: const LoggedMeal(entry, LoggedOrigin.claude),
onUndo: () => undone++,
),
),
),
);
expect(find.text('kurczak z ryzem'), findsOneWidget);
expect(find.text('540'), findsOneWidget);
expect(byIconLabel('Undo'), findsOneWidget);
final size = tester.getSize(find.byType(IconButton));
expect(size.width, 48);
expect(size.height, 48);
expect(find.byType(CircularProgressIndicator), findsNothing);
await tester.tap(byIconLabel('Undo'));
expect(undone, 1);
});
testWidgets('the glyph tells where a logged meal came from', (tester) async {
const entry = FoodEntry(
id: 'a',
time: 't',
desc: 'x',
grams: 1,
kcal: 1,
proteinG: 1,
carbsG: 1,
fatG: 1,
source: 's',
);
for (final (origin, icon) in [
(LoggedOrigin.claude, Icons.auto_awesome),
(LoggedOrigin.catering, Icons.restaurant),
(LoggedOrigin.local, Icons.check_circle),
]) {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: LoggedMealRow(
meal: const LoggedMeal(entry, LoggedOrigin.claude),
onUndo: () {},
),
),
),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: LoggedMealRow(meal: LoggedMeal(entry, origin), onUndo: () {}),
),
),
);
expect(find.byIcon(icon), findsOneWidget);
}
});
}

View File

@ -9,3 +9,8 @@ exceptions:
reason: local toolchain /opt/flutter is 3.47.9; fleet-wide Flutter 3.50 bump is separate work
blocked_by: local-toolchain
expires: "2026-11-26"
- ecosystem: pub
package: material_ui
pinned: "1.11.0"
reason: sync_settings_ui 0.8.2 (git dependency from kuhyx/utils) pins material_ui 1.11.0 exactly, so 1.11.1 cannot resolve until utils releases a sync_settings_ui that takes it
blocked_by: transitive:sync_settings_ui@0.8.2

20
diet-guard-claude.service Normal file
View File

@ -0,0 +1,20 @@
[Unit]
Description=Diet Guard "send to Claude" relay worker (phone meal requests)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
# Event-driven: one RTDB stream does the waiting, so a PC that was off simply
# serves the queued requests when this starts. Headless: no DISPLAY, unlike
# the gate. No PYTHONPATH: diet_guard (and claude_agent_sdk, rtdb_relay,
# httpx) are pip-installed into system Python's user site-packages by
# install.sh, which is what /usr/bin/python resolves.
ExecStart=/usr/bin/python -m diet_guard claude-worker
# A cancelled stream (the rules refuse the path) exits 1; an unconfigured or
# locked relay does not exit at all, it waits and retries (docs/DOCS-claude-relay.md).
Restart=on-failure
RestartSec=10
[Install]
WantedBy=default.target

View File

@ -0,0 +1,50 @@
"""The food-bank rows handed to the estimator.
The skill looks the bank up first (kuhy's own logged numbers beat generic
ones), but the whole bank would bloat every prompt. So the rows are the
closest matches for each part of the typed meal plus the most-logged staples,
deduplicated. Curated and log-derived rows both come through
:func:`diet_guard._foodbank_search.search_foods`.
"""
from __future__ import annotations
import re
from typing import TYPE_CHECKING, Final
from diet_guard._foodbank_search import search_foods
if TYPE_CHECKING:
from diet_guard._estimator import Nutrition
#: Splits a meal typed as a list: commas, plus, "i"/"oraz"/"and"/"with".
_PARTS: Final = re.compile(
r"\s*(?:,|;|\+|\bi\b|\boraz\b|\band\b|\bz\b)\s*", re.IGNORECASE
)
PER_QUERY: Final = 4
STAPLES: Final = 6
MAX_ROWS: Final = 20
def _row(name: str, nutrition: Nutrition) -> str:
"""One bank row as a compact line the model can scale."""
return (
f"{name} | {nutrition.grams:g} g | {nutrition.kcal:g} kcal | "
f"P{nutrition.protein_g:g} C{nutrition.carbs_g:g} F{nutrition.fat_g:g}"
)
def bank_rows(text: str | None) -> list[str]:
"""Bank rows relevant to ``text``, best first, at most :data:`MAX_ROWS`.
A photo-only request (``text`` None or blank) gets the staples alone.
"""
queries = [text.strip()] if text and text.strip() else []
queries += [part for part in _PARTS.split(text or "") if part.strip()]
rows: dict[str, str] = {}
for query in dict.fromkeys(queries):
for name, nutrition in search_foods(query, PER_QUERY):
rows.setdefault(name.casefold(), _row(name, nutrition))
for name, nutrition in search_foods("", STAPLES):
rows.setdefault(name.casefold(), _row(name, nutrition))
return list(rows.values())[:MAX_ROWS]

View File

@ -0,0 +1,104 @@
"""Connecting the relay worker to RTDB, signed in and unlocked.
The database URL and API key come from crdt-sync's shared
``~/.config/crdt-sync/firebase.json``; the signed-in session is the sync's own,
``~/.config/diet_guard/firebase_auth.json``. Sharing it is safe: the worker's
pull and publish already refresh it through the ordinary sync client,
Firebase does not invalidate an older refresh token when one is reused, and
crdt-sync's ``FileCredentialStore`` writes atomically with a unique temp name
for exactly this several-process case. Never ``firebase_client_for``: without
a session it falls back to the dead shared password and fails with a
misleading error.
:func:`connect_sealed` is the worker's only network entry point besides the
event stream it returns; ``conftest`` blocks it.
"""
from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING, Final
from crdt_sync import (
ConfigError,
E2eLockedError,
FirebaseAuthError,
FirebaseConfig,
FirebaseTokenProvider,
credential_store_for,
)
from rtdb_relay.rtdb import Rtdb, RtdbError
from rtdb_relay.seal import Sealer
from rtdb_relay.unlock import unlock
from diet_guard import _sync_e2e
from diet_guard._claude_layout import E2E_LAYOUT, LAYOUT, ROOT
if TYPE_CHECKING:
from collections.abc import Awaitable, Callable
APP: Final = "diet_guard"
class RelaySetupError(RuntimeError):
"""The relay cannot start: no config, no session, or the key is locked."""
def token_source(provider: FirebaseTokenProvider) -> Callable[[], Awaitable[str]]:
"""An async id-token getter (the provider is sync and refreshes itself)."""
async def token() -> str:
try:
return await asyncio.to_thread(provider.id_token)
except FirebaseAuthError as err:
msg = f"firebase auth failed: {err}"
raise RtdbError(msg) from None
return token
def connect() -> Rtdb:
"""An unsealed RTDB client rooted at the relay, signed in as the worker."""
try:
config = FirebaseConfig.load()
except ConfigError as err:
msg = f"no crdt-sync firebase config: {err}"
raise RelaySetupError(msg) from err
provider = FirebaseTokenProvider(config.api_key, credential_store_for(APP))
if not provider.has_session():
msg = (
f"no signed-in session in ~/.config/{APP}/firebase_auth.json; sign "
"diet_guard's sync in first (the phone and the gate use the same one)"
)
raise RelaySetupError(msg)
return Rtdb(config.database_url, token_source(provider), root=ROOT)
def passphrase() -> str:
"""The shared crdt-sync passphrase of this PC, or "" (locked)."""
try:
return _sync_e2e.PASSWORD_FILE.read_text(encoding="utf-8").strip()
except OSError:
return ""
async def connect_sealed() -> Rtdb:
"""The test seam: the worker connects only through this name."""
return await unlock_sealed(connect())
async def unlock_sealed(rtdb: Rtdb) -> Rtdb:
"""Unlock ``rtdb``: everything it writes is sealed from now on.
Raises:
RelaySetupError: The e2e key is locked or unreachable. Nothing may be
read or written (fail closed).
"""
try:
key = await unlock(rtdb, passphrase(), E2E_LAYOUT, _sync_e2e.ARGON2_PARAMS)
except (E2eLockedError, RtdbError) as err:
await rtdb.aclose()
msg = f"e2e locked or unreachable ({err})"
raise RelaySetupError(msg) from err
rtdb.sealer = Sealer(key.cipher(), LAYOUT)
return rtdb

View File

@ -0,0 +1,123 @@
"""The relay contract's pure parts: body validation, ids, result shapes.
Stdlib only. ``docs/DOCS-claude-relay.md`` is the prose; the shared fixture
``tests/fixtures/claude_relay_contract.json`` drives both this validator and
the phone's, so they cannot drift.
"""
from __future__ import annotations
import base64
import binascii
from dataclasses import dataclass
from typing import Final, Literal
import uuid
TEXT_MAX: Final = 2000
PHOTO_B64_MAX: Final = 600_000
SLOT_MAX: Final = 1439
EXPIRY_MS: Final = 24 * 60 * 60 * 1000
#: Codes the handler raises (``docs/DOCS-claude-relay.md`` section 3).
BAD_REQUEST: Final = "bad_request"
EXPIRED: Final = "expired"
#: A fixed namespace: the same rid always maps to the same entry id.
_ENTRY_NAMESPACE: Final = uuid.UUID("5d9c1a40-6f0e-5c3e-9b57-d1e7a3c0b2f4")
_JPEG_MAGIC: Final = b"\xff\xd8"
Mode = Literal["due", "normal"]
class BadRequestError(ValueError):
"""The request body breaks the contract."""
@dataclass(frozen=True)
class MealRequest:
"""A validated request body.
Attributes:
text: The typed meal, trimmed, or None.
photo: The decoded JPEG bytes, or None.
client_slot_min: The slot the phone would use; a hint in due mode.
mode: ``"due"`` (oldest due slot) or ``"normal"`` (nearest slot).
"""
text: str | None
photo: bytes | None
client_slot_min: int
mode: Mode
def entry_id_for(rid: str) -> str:
"""The log entry id of request ``rid``: a uuid5, so replays find it."""
return str(uuid.uuid5(_ENTRY_NAMESPACE, rid))
def _photo(value: object) -> bytes | None:
"""The decoded JPEG, None when absent."""
if value is None:
return None
if not isinstance(value, str) or len(value) > PHOTO_B64_MAX:
msg = "photo_jpeg_b64 is not a base64 string within the size cap"
raise BadRequestError(msg)
try:
data = base64.b64decode(value, validate=True)
except binascii.Error as err:
msg = "photo_jpeg_b64 is not valid base64"
raise BadRequestError(msg) from err
if not data.startswith(_JPEG_MAGIC):
msg = "photo_jpeg_b64 is not a JPEG"
raise BadRequestError(msg)
return data
def _text(value: object) -> str | None:
"""The trimmed text, None when absent."""
if value is None:
return None
if not isinstance(value, str):
msg = "text is not a string"
raise BadRequestError(msg)
trimmed = value.strip()
if not trimmed or len(trimmed) > TEXT_MAX:
msg = f"text must be 1..{TEXT_MAX} characters"
raise BadRequestError(msg)
return trimmed
def parse_body(body: dict[str, object]) -> MealRequest:
"""Validate a request body.
Raises:
BadRequestError: any field breaks the contract, or there is neither
text nor photo to estimate.
"""
text = _text(body.get("text"))
photo = _photo(body.get("photo_jpeg_b64"))
if text is None and photo is None:
msg = "neither text nor photo"
raise BadRequestError(msg)
slot = body.get("client_slot_min")
if isinstance(slot, bool) or not isinstance(slot, int) or not 0 <= slot <= SLOT_MAX:
msg = f"client_slot_min must be an int in 0..{SLOT_MAX}"
raise BadRequestError(msg)
mode = body.get("mode")
if mode == "due":
return MealRequest(text, photo, slot, "due")
if mode == "normal":
return MealRequest(text, photo, slot, "normal")
msg = "mode must be 'due' or 'normal'"
raise BadRequestError(msg)
def is_expired(created_ms: object, now_ms: float) -> bool:
"""Whether a request created at ``created_ms`` is older than 24 h.
A missing or non-numeric ``created`` counts as expired: the request has no
server timestamp, so it cannot be trusted to be fresh (fail closed).
"""
if isinstance(created_ms, bool) or not isinstance(created_ms, (int, float)):
return True
return now_ms - created_ms > EXPIRY_MS

View File

@ -0,0 +1,96 @@
"""Estimate one meal with Claude: ``estimate_meal(text, photo) -> Estimate``.
The pure entry point for the relay worker now and the Tk gate later. It never
logs anything: it returns an :class:`~diet_guard._claude_schema.Estimate` or
raises :class:`EstimateError` with the contract's error code, and the caller
decides. Every failure (no login, CLI or API error, timeout, invalid JSON)
is an error, never a guess (fail closed).
The model runs through :func:`diet_guard._claude_sdk.run_model` in an
isolated config dir with the ``diet-food`` skill as its system prompt, the
text and photo as one user message, and the closest food-bank rows.
"""
from __future__ import annotations
import asyncio
import base64
from typing import Any, Final
from diet_guard import _claude_sandbox, _claude_sdk
from diet_guard._claude_bank import bank_rows
from diet_guard._claude_schema import (
SCHEMA,
Estimate,
InvalidEstimateError,
parse_estimate,
)
#: Contract error codes (``docs/DOCS-claude-relay.md`` section 3).
TIMEOUT: Final = "estimate_timeout"
FAILED: Final = "estimate_failed"
INVALID: Final = "estimate_invalid"
#: Wall-clock budget for one model call; the contract's 45 s.
BUDGET_S: Final = 45.0
class EstimateError(Exception):
"""The meal could not be estimated; ``code`` is the contract's code."""
def __init__(self, code: str, message: str) -> None:
"""Carry the contract ``code`` and a log-only ``message``."""
super().__init__(message)
self.code = code
def _content(text: str | None, photo: bytes | None) -> list[dict[str, Any]]:
"""The user message: the typed meal, the bank rows, the photo."""
rows = bank_rows(text)
parts = [f"Meal as typed: {text.strip()}" if text and text.strip() else "No text."]
if rows:
parts.append("Food bank (name | grams | kcal | macros per logged portion):")
parts.extend(rows)
blocks: list[dict[str, Any]] = [{"type": "text", "text": "\n".join(parts)}]
if photo is not None:
data = base64.b64encode(photo).decode("ascii")
source = {"type": "base64", "media_type": "image/jpeg", "data": data}
blocks.append({"type": "image", "source": source})
return blocks
async def estimate_meal_async(text: str | None, photo: bytes | None) -> Estimate:
"""Estimate one meal; for callers already inside an event loop.
Raises:
ValueError: neither ``text`` nor ``photo`` was given.
EstimateError: the model failed, timed out or answered nonsense.
"""
if not (text and text.strip()) and photo is None:
msg = "nothing to estimate: no text and no photo"
raise ValueError(msg)
prompt = await asyncio.to_thread(_claude_sandbox.skill_text)
content = await asyncio.to_thread(_content, text, photo)
try:
answer = await _claude_sdk.run_model(prompt, content, SCHEMA, budget_s=BUDGET_S)
except _claude_sdk.ModelTimeoutError as err:
raise EstimateError(TIMEOUT, str(err)) from err
except _claude_sdk.ModelError as err:
raise EstimateError(FAILED, str(err)) from err
try:
return parse_estimate(answer)
except InvalidEstimateError as err:
raise EstimateError(INVALID, str(err)) from err
def estimate_meal(text: str | None, photo: bytes | None) -> Estimate:
"""Estimate one meal from a description and/or a JPEG photo (blocking).
Not callable from inside a running event loop; use
:func:`estimate_meal_async` there.
Raises:
ValueError: neither ``text`` nor ``photo`` was given.
EstimateError: the model failed, timed out or answered nonsense.
"""
return asyncio.run(estimate_meal_async(text, photo))

View File

@ -0,0 +1,34 @@
"""Where the "send to Claude" relay lives in RTDB and what is sealed.
The contract is ``docs/DOCS-claude-relay.md``; ``tests/fixtures/
claude_relay_contract.json`` pins the same layout for the phone. The root is
chosen so its e2e header is the one diet_guard already uses
(``diet-guard-sync/e2e``): same passphrase, same salt, same key.
Imports ``rtdb_relay`` and ``crdt_sync``, so only the relay worker's own
modules import this one -- never the gate or the CLI at load time.
"""
from __future__ import annotations
from typing import Final
from crdt_sync import E2eLayout
from rtdb_relay.layout import Layout
#: The unencrypted-era prefix the e2e root and header are derived from.
OLD_PREFIX: Final = "diet-guard-sync/claude"
E2E_LAYOUT: Final = E2eLayout.of(OLD_PREFIX)
ROOT: Final = E2E_LAYOUT.prefix
#: The only request kind this relay serves.
KIND: Final = "meal"
LAYOUT: Final = Layout(
root=ROOT,
clear=("requests/*/claim",),
units={
"requests/*/req": frozenset({"created"}),
"requests/*/result": frozenset({"at"}),
},
)

90
diet_guard/_claude_log.py Normal file
View File

@ -0,0 +1,90 @@
"""Turning an estimate into one logged entry: slot, write, result data.
The slot rule (``docs/DOCS-claude-relay.md`` section 4) only *calls*
``_slots`` and ``_gate``; no slot arithmetic lives here.
* ``"due"``: the oldest elapsed-but-unlogged slot of today; with nothing due
(already logged elsewhere, free or sick day, hold, outside the enforcement
window) the ordinary ``slot_for_log`` rule, never an error.
* ``"normal"``: ``nearest_slot`` of the phone's ``client_slot_min``.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from diet_guard._claude_contract import entry_id_for
from diet_guard._estimator import Nutrition
from diet_guard._gate import due_slots
from diet_guard._meal_schedule_store import current_schedule
from diet_guard._slot_wire import entry_slot_minute
from diet_guard._slots import nearest_slot, slot_for_log
from diet_guard._state_sync import find_entry, log_meal_as
if TYPE_CHECKING:
from datetime import datetime
from diet_guard._claude_contract import MealRequest
from diet_guard._claude_schema import Estimate
#: ``Nutrition.source`` and so the entry's ``source`` field.
SOURCE = "claude"
def resolve_slot(request: MealRequest, now: datetime) -> int:
"""The slot minute this request's meal is logged under."""
if request.mode == "due":
due = due_slots(now)
return due[0] if due else slot_for_log(now, current_schedule())
return nearest_slot(request.client_slot_min, current_schedule())
def result_data(entry: dict[str, object]) -> dict[str, object]:
"""The ``logged`` result fields of a stored entry."""
slot = entry_slot_minute(entry)
return {
"entry_id": entry["id"],
"desc": entry["desc"],
"grams": entry["grams"],
"kcal": entry["kcal"],
"protein_g": entry["protein_g"],
"carbs_g": entry["carbs_g"],
"fat_g": entry["fat_g"],
"slot_min": slot,
"time": entry["time"],
}
def already_logged(rid: str) -> dict[str, object] | None:
"""The result data of ``rid``'s entry if it was logged before, else None."""
entry = find_entry(entry_id_for(rid))
return result_data(entry) if entry is not None else None
def log_estimate(
rid: str, estimate: Estimate, request: MealRequest, now: datetime
) -> dict[str, object]:
"""Log ``estimate`` for request ``rid`` and return its result data.
Idempotent: the entry id is derived from ``rid``, and an entry that
already carries it is returned untouched instead of logged again.
"""
if (existing := already_logged(rid)) is not None:
return existing
nutrition = Nutrition(
kcal=estimate.kcal,
protein_g=estimate.protein_g,
carbs_g=estimate.carbs_g,
fat_g=estimate.fat_g,
grams=estimate.grams,
source=SOURCE,
)
components = [dict(item) for item in estimate.components or ()] or None
entry = log_meal_as(
entry_id_for(rid),
estimate.desc,
nutrition,
resolve_slot(request, now),
components=components,
)
return result_data(entry)

View File

@ -0,0 +1,57 @@
"""``python -m diet_guard claude-worker``: connect, serve, never idle-poll.
One SSE stream on ``requests`` does the waiting (``rtdb_relay.sse`` reconnects
forever with backoff). The only timers are fault retries: an unconfigured or
locked relay (no session, no passphrase, wrong key) writes nothing and is
tried again every :data:`RETRY_S`.
"""
from __future__ import annotations
import asyncio
import logging
from typing import TYPE_CHECKING, Final
from rtdb_relay.sse import StreamCancelledError
from diet_guard import _claude_connect, _device
from diet_guard._claude_worker import MealHandler, MealServer
if TYPE_CHECKING:
from collections.abc import Awaitable, Callable
RETRY_S: Final = 60.0
_logger = logging.getLogger(__name__)
async def serve(
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
) -> None:
"""Connect and serve until cancelled; a setup failure waits and retries."""
worker = f"claude-{_device.device_id()}"
while True:
try:
rtdb = await _claude_connect.connect_sealed()
except _claude_connect.RelaySetupError as err:
_logger.warning("relay not started, nothing written: %s", err)
await sleep(RETRY_S)
continue
try:
await MealServer(rtdb, worker, MealHandler()).run()
finally:
await rtdb.aclose()
def main() -> int:
"""Run the worker; 0 on Ctrl-C, 1 when RTDB cancelled the stream."""
logging.basicConfig(
level=logging.INFO, format="%(levelname)s %(name)s: %(message)s"
)
try:
asyncio.run(serve())
except KeyboardInterrupt:
return 0
except StreamCancelledError:
_logger.exception("the rules refuse the relay path")
return 1
return 0

View File

@ -0,0 +1,138 @@
"""The isolated Claude config dir the meal estimator runs in.
kuhy's own ``~/.claude`` stays outside: its hooks and rules make the model
answer with a grilling round instead of JSON, and its credentials file also
holds a refresh token and every MCP server's OAuth tokens. The sandbox holds
exactly two things: a copy of the Claude access token (no refresh token, so
the CLI inside never refreshes and never rotates kuhy's own login out) and the
``diet-food`` skill. Same approach as ``~/src/tutor/tutor/model_login.py``.
``CLAUDE_CONFIG_DIR`` is set only in the model call's own ``env`` (see
:mod:`diet_guard._claude_sdk`), never in this process: ``HOST_LOGIN_FILE``
must keep naming kuhy's real login.
"""
from __future__ import annotations
import json
import logging
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import time
from typing import TYPE_CHECKING, Final
if TYPE_CHECKING:
from collections.abc import Callable
_logger = logging.getLogger(__name__)
#: Scratch config dir (``CLAUDE_CONFIG_DIR``); cache, not the synced data dir.
SANDBOX_DIR: Path = Path.home() / ".cache" / "diet_guard" / "claude-sandbox"
#: kuhy's own CLI login: read to copy the access token, never written.
HOST_LOGIN_FILE: Path = Path.home() / ".claude" / ".credentials.json"
#: The skill shipped in the repo (an editable install runs the working tree).
SKILL_DIR: Final = Path(__file__).resolve().parent.parent / "skills" / "diet-food"
#: The CLI refreshes its token within 5 minutes of expiry.
REFRESH_MARGIN_MS: Final = 300_000
_REFRESH_TIMEOUT_S: Final = 40
_LOGIN_NAME: Final = ".credentials.json"
def skill_text() -> str:
"""The ``SKILL.md`` body without its front matter (the system prompt)."""
text = SKILL_DIR.joinpath("SKILL.md").read_text(encoding="utf-8")
if text.startswith("---\n"):
_, _, text = text[4:].partition("\n---\n")
return text.strip()
def host_cli() -> Path | None:
"""The ``claude`` binary kuhy's login is refreshed with, if any."""
found = shutil.which("claude")
return Path(found) if found else None
def copy_login() -> int | None:
"""Copy the host's access token into the sandbox; its expiry in ms.
Only ``claudeAiOauth`` minus ``refreshToken`` is written (0600, atomic).
No readable host login writes nothing and returns None.
"""
try:
raw = json.loads(HOST_LOGIN_FILE.read_text(encoding="utf-8"))
oauth = dict(raw["claudeAiOauth"])
except (OSError, ValueError, KeyError, TypeError) as err:
_logger.warning("no host Claude login to copy: %r", err)
return None
oauth.pop("refreshToken", None)
SANDBOX_DIR.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=SANDBOX_DIR, prefix=".credentials.")
with os.fdopen(fd, "w", encoding="utf-8") as out:
json.dump({"claudeAiOauth": oauth}, out)
Path(tmp).replace(SANDBOX_DIR / _LOGIN_NAME)
expires = oauth.get("expiresAt")
return int(expires) if isinstance(expires, (int, float)) else None
def refresh_host_login() -> None:
"""Let kuhy's own CLI refresh his login: one tiny call, nothing loaded."""
cli = host_cli()
if cli is None:
return
cmd = [
str(cli),
"-p",
"Reply with OK.",
"--tools=",
"--setting-sources=",
"--strict-mcp-config",
"--max-turns=1",
"--no-session-persistence",
]
env = {k: v for k, v in os.environ.items() if k != "CLAUDECODE"}
work = SANDBOX_DIR / "refresh"
work.mkdir(parents=True, exist_ok=True)
subprocess.run(
cmd,
cwd=work,
env=env,
check=True,
capture_output=True,
timeout=_REFRESH_TIMEOUT_S,
)
def install_skill() -> None:
"""Copy the ``diet-food`` skill into the sandbox's ``skills/`` dir."""
target = SANDBOX_DIR / "skills" / SKILL_DIR.name
target.mkdir(parents=True, exist_ok=True)
shutil.copyfile(SKILL_DIR / "SKILL.md", target / "SKILL.md")
def prepare(
now: Callable[[], float] = time.time,
refresh: Callable[[], None] = refresh_host_login,
) -> Path | None:
"""Make the sandbox ready; its path, or None when there is no login.
A login about to expire is refreshed on the host first. Never raises on a
refresh failure: the model call then reports the CLI's own error and the
request fails closed as ``estimate_failed``.
"""
expires = copy_login()
if expires is None:
return None
if expires - now() * 1000 <= REFRESH_MARGIN_MS:
try:
refresh()
except (OSError, subprocess.SubprocessError) as err:
_logger.warning("could not refresh the Claude login: %r", err)
else:
copy_login()
install_skill()
(SANDBOX_DIR / "work").mkdir(exist_ok=True)
return SANDBOX_DIR

View File

@ -0,0 +1,136 @@
"""The estimator's strict output: a JSON schema and a validator.
The schema goes to the model as ``output_format`` (so the CLI constrains the
answer), and :func:`parse_estimate` re-validates what came back: a model
answer that is not a sane, complete object is never logged. Pure stdlib, so
the gate can import it.
"""
from __future__ import annotations
from dataclasses import dataclass
import math
from typing import Any, Final
MAX_DESC: Final = 120
MAX_GRAMS: Final = 5000.0
MAX_KCAL: Final = 5000.0
_NUMBERS: Final = ("grams", "kcal", "protein_g", "carbs_g", "fat_g")
_NUMBER: Final = {"type": "number", "minimum": 0}
_ITEM_PROPS: Final = {
"name": {"type": "string", "minLength": 1, "maxLength": MAX_DESC},
**dict.fromkeys(_NUMBERS, _NUMBER),
}
#: The JSON schema the model's answer must satisfy.
SCHEMA: Final[dict[str, Any]] = {
"type": "object",
"additionalProperties": False,
"required": ["desc", *_NUMBERS],
"properties": {
"desc": {"type": "string", "minLength": 1, "maxLength": MAX_DESC},
**dict.fromkeys(_NUMBERS, _NUMBER),
"components": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": False,
"required": ["name", *_NUMBERS],
"properties": _ITEM_PROPS,
},
},
},
}
class InvalidEstimateError(ValueError):
"""The model's answer is not a usable estimate."""
@dataclass(frozen=True)
class Estimate:
"""One estimated meal: totals for the whole portion.
Attributes:
desc: Short name for the whole meal.
grams: Total edible weight, greater than 0.
kcal: Energy for the portion.
protein_g: Protein for the portion.
carbs_g: Carbohydrate for the portion.
fat_g: Fat for the portion.
components: Per-item breakdown, or None for a single item.
"""
desc: str
grams: float
kcal: float
protein_g: float
carbs_g: float
fat_g: float
components: tuple[dict[str, object], ...] | None = None
def _number(data: dict[str, Any], key: str, ceiling: float) -> float:
"""``data[key]`` as a finite float in ``[0, ceiling]`` (bool is refused)."""
value = data.get(key)
if isinstance(value, bool) or not isinstance(value, (int, float)):
msg = f"{key} is not a number"
raise InvalidEstimateError(msg)
number = float(value)
if not math.isfinite(number) or not 0 <= number <= ceiling:
msg = f"{key}={value!r} is out of range"
raise InvalidEstimateError(msg)
return number
def _text(data: dict[str, Any], key: str) -> str:
"""``data[key]`` as a non-blank string of at most :data:`MAX_DESC`."""
value = data.get(key)
if not isinstance(value, str) or not value.strip() or len(value) > MAX_DESC:
msg = f"{key} is not a short non-blank string"
raise InvalidEstimateError(msg)
return value.strip()
def _macros(data: dict[str, Any]) -> dict[str, float]:
"""The five numbers every meal and every component carries."""
numbers = {
"grams": _number(data, "grams", MAX_GRAMS),
"kcal": _number(data, "kcal", MAX_KCAL),
}
for key in ("protein_g", "carbs_g", "fat_g"):
numbers[key] = _number(data, key, MAX_GRAMS)
return numbers
def _component(item: object) -> dict[str, object]:
"""One validated component."""
if not isinstance(item, dict):
msg = "a component is not an object"
raise InvalidEstimateError(msg)
return {"name": _text(item, "name"), **_macros(item)}
def parse_estimate(data: object) -> Estimate:
"""Validate the model's answer.
Raises:
InvalidEstimateError: not an object, a field is missing or mistyped,
a number is non-finite, negative or absurd, or ``grams`` is 0.
"""
if not isinstance(data, dict):
msg = "the answer is not an object"
raise InvalidEstimateError(msg)
numbers = _macros(data)
if numbers["grams"] <= 0:
msg = "grams must be greater than 0"
raise InvalidEstimateError(msg)
raw = data.get("components")
components: tuple[dict[str, object], ...] | None = None
if raw is not None:
if not isinstance(raw, list):
msg = "components is not a list"
raise InvalidEstimateError(msg)
components = tuple(_component(item) for item in raw)
return Estimate(desc=_text(data, "desc"), components=components, **numbers)

132
diet_guard/_claude_sdk.py Normal file
View File

@ -0,0 +1,132 @@
"""The one place that talks to Claude: ``claude_agent_sdk`` in the sandbox.
Every other module reaches the model through :func:`run_model`, so a single
test seam (``conftest`` blocks it) keeps the suite off the network and off
kuhy's subscription. The SDK is imported inside the function: the gate and
the CLI import this package at load time, and system Python has no
``claude_agent_sdk`` until the install step ran (the 2026-06-19 outage
shape).
Isolation: ``CLAUDE_CONFIG_DIR`` points at the sandbox (token copy + skill),
``setting_sources`` is empty and there are no tools, MCP servers or hooks, so
nothing of kuhy's own configuration can steer the model.
"""
from __future__ import annotations
import asyncio
from importlib import import_module
from typing import TYPE_CHECKING, Any, Final
from diet_guard import _claude_sandbox
if TYPE_CHECKING:
from collections.abc import AsyncIterator
from pathlib import Path
from claude_agent_sdk import ClaudeAgentOptions
MODEL: Final = "claude-sonnet-5-5"
_SDK: Final = "claude_agent_sdk" # imported lazily, see the module docstring
class ModelError(RuntimeError):
"""The model call failed or returned no structured answer."""
class ModelTimeoutError(ModelError):
"""The model call ran past its time budget."""
def _blocks(content: list[dict[str, Any]]) -> AsyncIterator[dict[str, Any]]:
"""One streamed user message carrying content blocks (how images go in)."""
async def stream() -> AsyncIterator[dict[str, Any]]:
message = {"role": "user", "content": content}
yield {"type": "user", "message": message, "parent_tool_use_id": None}
return stream()
def _options(
system_prompt: str, schema: dict[str, Any], config: Path
) -> ClaudeAgentOptions:
"""Isolated, tool-less options with the structured-output schema."""
work = config / "work"
return import_module(_SDK).ClaudeAgentOptions(
model=MODEL,
system_prompt=system_prompt,
tools=[],
allowed_tools=[],
setting_sources=[],
strict_mcp_config=True,
mcp_servers={},
cwd=work,
output_format={"type": "json_schema", "schema": schema},
effort="low",
env={
"CLAUDE_CONFIG_DIR": str(config),
"CLAUDE_CODE_DISABLE_AUTO_MEMORY": "1",
"DISABLE_TELEMETRY": "1",
"DISABLE_AUTOUPDATER": "1",
},
extra_args={"disable-slash-commands": None, "no-session-persistence": None},
)
async def _ask(
system_prompt: str, content: list[dict[str, Any]], schema: dict[str, Any]
) -> dict[str, Any]:
config = await asyncio.to_thread(_claude_sandbox.prepare)
if config is None:
msg = "no Claude login to copy into the sandbox"
raise ModelError(msg)
options = _options(system_prompt, schema, config)
answer: object = None
sdk = import_module(_SDK)
async for message in sdk.query(prompt=_blocks(content), options=options):
if isinstance(message, sdk.ResultMessage):
if message.is_error:
detail = f"{message.subtype} {message.errors} {message.result}"
raise ModelError(detail)
answer = message.structured_output
if not isinstance(answer, dict):
msg = "model returned no structured object"
raise ModelError(msg)
return answer
async def run_model(
system_prompt: str,
content: list[dict[str, Any]],
schema: dict[str, Any],
*,
budget_s: float,
) -> dict[str, Any]:
"""The test seam: callers reach the model only through this name."""
return await bounded_ask(system_prompt, content, schema, budget_s=budget_s)
async def bounded_ask(
system_prompt: str,
content: list[dict[str, Any]],
schema: dict[str, Any],
*,
budget_s: float,
) -> dict[str, Any]:
"""Ask the model once; its structured answer (a JSON object).
Raises:
ModelTimeoutError: ``budget_s`` seconds passed.
ModelError: any other failure: login, CLI, API, or a missing answer.
"""
try:
async with asyncio.timeout(budget_s):
return await _ask(system_prompt, content, schema)
except TimeoutError as err:
msg = f"model call exceeded {budget_s:g} s"
raise ModelTimeoutError(msg) from err
except ModelError:
raise
except Exception as err: # SDK/CLI errors have no common base worth naming
raise ModelError(type(err).__name__) from err

View File

@ -0,0 +1,28 @@
"""The relay worker's two sync touch points, behind one module seam.
* :func:`pull_peers` runs before a request is served, so the due slot is
computed from a log that already holds what the phone logged. It is the
narrow pull (``_sync_refresh.pull_peer_logs``, ~84 ms), not a full tick.
* :func:`publish` runs after the answer is written: a full tick (15 to 27 s)
that must never sit in front of the answer (``docs/DOCS-claude-relay.md``
section 5).
Both return ``None`` on success or a short reason, never raise on an outage
(fail closed: the worker leaves the request pending on a failed pull).
``conftest`` patches both names here, so a test that logs through the worker
cannot reach the real remote.
"""
from __future__ import annotations
from diet_guard import _sync_events, _sync_refresh
def pull_peers() -> str | None:
"""Pull every peer's log; None on success, else why not."""
return _sync_refresh.pull_peer_logs()
def publish() -> str | None:
"""Run a full sync tick after a write; None on success, else why not."""
return _sync_events.publish_after_log()

View File

@ -0,0 +1,213 @@
"""Serving meal requests: validate, estimate, log, answer, then publish.
``MealServer`` is ``rtdb_relay``'s ``RequestServer`` with the four things this
relay adds on top (``docs/DOCS-claude-relay.md`` section 5):
* a narrow peer pull before a request is claimed; a failed pull leaves the
request pending (no claim, no answer, no model cost) and retries later;
* the request's id and server ``created`` time reach the handler;
* ``req`` (the photo) is deleted once the result is written; the node keeps
``claim`` and ``result`` until the phone deletes it or 24 h pass;
* the full sync tick runs *after* the answer, in the background.
``MealHandler`` is the handler for kind ``meal``.
"""
from __future__ import annotations
import asyncio
import logging
import time
from typing import TYPE_CHECKING, Any, Final
from rtdb_relay import mirror, sse
from rtdb_relay.lease import ms, valid_rid
from rtdb_relay.rtdb import RtdbError
from rtdb_relay.server import RequestError, RequestServer
from diet_guard import _claude_sync
from diet_guard._claude_contract import (
BAD_REQUEST,
EXPIRED,
EXPIRY_MS,
BadRequestError,
is_expired,
parse_body,
)
from diet_guard._claude_estimate import EstimateError, estimate_meal_async
from diet_guard._claude_layout import KIND
from diet_guard._claude_log import already_logged, log_estimate
from diet_guard._state import now_local
if TYPE_CHECKING:
from collections.abc import Awaitable, Callable
from datetime import datetime
from rtdb_relay.lease import Lease
from rtdb_relay.rtdb import Rtdb
from diet_guard._claude_schema import Estimate
type Estimator = Callable[[str | None, bytes | None], Awaitable[Estimate]]
#: Seconds before a request left pending by a failed pull is tried again.
RETRY_S: Final = 30.0
_logger = logging.getLogger(__name__)
class MealHandler:
"""The handler of kind ``meal``: body in, ``logged`` result data out."""
def __init__(
self,
estimate: Estimator = estimate_meal_async,
now: Callable[[], datetime] = now_local,
clock: Callable[[], float] = time.time,
) -> None:
"""Estimate with ``estimate``; ``now`` stamps the entry, ``clock`` ages it."""
self._estimate = estimate
self._now = now
self._clock = clock
#: The one lock of everything that reads-merges-writes the food log
#: (the pull, the log write, the publish): two of them at once lose an
#: append, and the phone has already been told "logged". Also keeps
#: two requests from taking the same due slot. Shared with the server.
self.log_lock = asyncio.Lock()
async def handle(self, body: dict[str, Any]) -> dict[str, Any]:
"""Serve one request body (``rid`` and ``created`` injected by the server)."""
rid = str(body.get("rid"))
if (done := await asyncio.to_thread(already_logged, rid)) is not None:
_logger.info("request %s was logged before: answering from the log", rid)
return done
if is_expired(body.get("created"), self._clock() * 1000):
raise RequestError(EXPIRED, "request older than 24 h")
try:
request = parse_body(body)
except BadRequestError as err:
raise RequestError(BAD_REQUEST, str(err)) from err
try:
estimate = await self._estimate(request.text, request.photo)
except EstimateError as err:
raise RequestError(err.code, str(err), retry=True) from err
async with self.log_lock:
return await asyncio.to_thread(
log_estimate, rid, estimate, request, self._now()
)
class MealServer(RequestServer):
"""``RequestServer`` plus the pull, the cleanup and the late publish."""
def __init__(
self,
rtdb: Rtdb,
worker: str,
handler: MealHandler,
now: Callable[[], float] = time.time,
) -> None:
"""Serve kind ``meal`` with ``handler`` as ``worker``."""
super().__init__(rtdb, worker, {KIND: handler.handle}, now)
# Replaceable (tests): the pause before a pending request is retried.
self._sleep: Callable[[float], Awaitable[None]] = asyncio.sleep
self.tree: dict[str, Any] = {}
self._retry: asyncio.Task[None] | None = None
self._collecting: set[str] = set()
self._log_lock = handler.log_lock
async def answer(self, rid: str, node: dict[str, Any]) -> dict[str, Any] | None:
"""Pull, serve, then clean up and publish; None when not ours to answer."""
if not valid_rid(rid) or "result" in node or "req" not in node:
return None
async with self._log_lock:
reason = await asyncio.to_thread(_claude_sync.pull_peers)
if reason is not None:
_logger.warning("not serving %s, request stays pending: %s", rid, reason)
self._retry_later()
return None
result = await super().answer(rid, node)
if result is not None:
await self._drop_request(rid)
self._start(self._publish())
return result
async def _run(
self, lease: Lease, kind: str, req: dict[str, Any]
) -> dict[str, Any]:
"""Hand the handler the rid and the server's ``created``; add ``status``."""
body = req.get("body")
body = body if isinstance(body, dict) else {}
enriched = {
**req,
"body": {**body, "rid": lease.rid, "created": req.get("created")},
}
result = await super()._run(lease, kind, enriched)
if result.get("ok"):
return {**result, "status": "logged", "id": lease.rid}
return {
**result,
"status": "error",
"id": lease.rid,
"error_code": result.get("code"),
}
async def _drop_request(self, rid: str) -> None:
"""Delete ``req`` (the photo): useless once the result is out."""
try:
await self.rtdb.delete(f"requests/{rid}/req")
except RtdbError as err:
_logger.warning("could not delete the request payload of %s: %s", rid, err)
async def _publish(self) -> None:
"""The full sync tick, after the answer; an outage is only logged."""
async with self._log_lock:
reason = await asyncio.to_thread(_claude_sync.publish)
if reason is not None:
_logger.warning("post-answer sync skipped: %s", reason)
def _start(self, work: Awaitable[None]) -> None:
"""Run ``work`` in the background, remembered so it is not collected."""
task = asyncio.ensure_future(work)
self.tasks.add(task)
task.add_done_callback(self.tasks.discard)
def _retry_later(self) -> None:
"""Try the pending requests again in :data:`RETRY_S` (one timer at most)."""
if self._retry is None or self._retry.done():
self._retry = asyncio.ensure_future(self._retry_after())
async def _retry_after(self) -> None:
await self._sleep(RETRY_S)
self.dispatch(self.tree)
def dispatch(self, tree: dict[str, Any]) -> None:
"""Serve what is pending, and drop answers older than 24 h."""
super().dispatch(tree)
cutoff = ms(self._now()) - EXPIRY_MS
for rid, node in tree.items():
result = node.get("result") if isinstance(node, dict) else None
at = result.get("at") if isinstance(result, dict) else None
old = (
isinstance(at, (int, float))
and not isinstance(at, bool)
and at < cutoff
)
if old and valid_rid(rid) and rid not in self._collecting:
self._collecting.add(rid)
self._start(self._collect(rid))
async def _collect(self, rid: str) -> None:
"""Delete one answered request node (a failure is retried next event)."""
try:
await self.rtdb.delete(f"requests/{rid}")
except RtdbError as err:
_logger.warning("could not delete the old request %s: %s", rid, err)
finally:
self._collecting.discard(rid)
async def run(self) -> None:
"""Watch ``requests`` (raw, so sealing is checked) until cancelled."""
self.tree = {}
async for event in sse.listen(self._raw, "requests"):
self.tree = mirror.apply(self.tree, event)
self.dispatch(self.tree)

View File

@ -34,6 +34,7 @@ from diet_guard._cli_body import (
cmd_profile,
cmd_weight,
)
from diet_guard._cli_claude import cmd_claude_worker
from diet_guard._cli_gate import cmd_gate
from diet_guard._cli_init import cmd_init
from diet_guard._cli_kuchnia import cmd_kuchnia
@ -225,6 +226,7 @@ _COMMANDS: dict[str, Callable[[argparse.Namespace], int]] = {
"sync": lambda _args: cmd_sync(_emit),
"kuchnia": _dispatch_kuchnia,
"prune-peers": _dispatch_prune,
"claude-worker": lambda _args: cmd_claude_worker(),
"gate": _dispatch_gate,
"undo": lambda _args: _cmd_undo(),
"body": lambda args: cmd_body(_emit, args),

View File

@ -16,6 +16,7 @@ import argparse
from diet_guard._cli_averages import register_averages_subparser
from diet_guard._cli_body import register_body_subparsers
from diet_guard._cli_claude import register_claude_subparser
from diet_guard._cli_kuchnia import register_kuchnia_subparser
from diet_guard._cli_prune import register_prune_subparser
from diet_guard._cli_sync import register_sync_subparser
@ -98,6 +99,7 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
register_averages_subparser(sub)
register_kuchnia_subparser(sub)
register_prune_subparser(sub)
register_claude_subparser(sub)
register_sync_subparser(sub)
register_body_subparsers(sub)

29
diet_guard/_cli_claude.py Normal file
View File

@ -0,0 +1,29 @@
"""CLI handler for the ``claude-worker`` subcommand.
The relay worker needs ``claude_agent_sdk``, ``rtdb_relay`` and ``httpx``,
which system Python only gains after the install step. Importing the worker
here would make every command (the gate included) fail at load time on a
machine that has not run it -- the 2026-06-19 outage shape -- so the worker
module is imported only when this subcommand actually runs.
"""
from __future__ import annotations
from importlib import import_module
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import argparse
def register_claude_subparser(sub: argparse._SubParsersAction) -> None:
"""Register the ``claude-worker`` subcommand on ``sub``."""
sub.add_parser(
"claude-worker",
help="Serve the phone's 'send to Claude' meal requests (long-running).",
)
def cmd_claude_worker() -> int:
"""Run the relay worker until it is stopped; its exit code."""
return import_module("diet_guard._claude_relay").main()

View File

@ -35,6 +35,8 @@ _LAZY_ATTRS = {
# ``_sync_refresh`` reaches ``crdt_sync`` -> ``requests``; the not-due
# tick never pulls, so it must not pay that import either.
"pull_peer_logs": ("diet_guard._sync_refresh", "pull_peer_logs"),
# The catering auto-log reaches the panel client; same reasoning.
"autolog_due_delivery": ("diet_guard._kuchnia_autolog", "autolog_due_delivery"),
}
@ -48,7 +50,7 @@ def __getattr__(name: str) -> object:
return getattr(import_module(module_name), attr)
def _should_lock(emit: Callable[[str], None]) -> bool:
def _should_lock(emit: Callable[[str], None], *, autolog: bool = True) -> bool:
"""Decide whether to lock, pulling from sync first if a lock looks due.
This wraps the pure, local :func:`~diet_guard._gate.gate_is_due` predicate
@ -64,15 +66,29 @@ def _should_lock(emit: Callable[[str], None]) -> bool:
in :func:`cmd_gate` once the window has closed. Only the peer logs can
answer "has a peer already logged this slot?", which is the sole question
this predicate asks.
After the pull, ``autolog`` (every real mode except ``--check``) logs
today's catering for the due slots (:mod:`diet_guard._kuchnia_autolog`,
kuhy's 2026-11-17 override of "delivered is not eaten"). It is capped at
5 s and fail-closed: any failure leaves the lock decision untouched. When
it clears the lock no window opens, so it publishes here -- ``cmd_gate``'s
own publish only follows a window -- or the phone would keep nagging.
"""
if not gate_is_due():
return False
# Through the module object so the lazy hook above resolves it, and so a
# test's ``patch.object`` still wins.
reason = sys.modules[__name__].pull_peer_logs()
module = sys.modules[__name__]
reason = module.pull_peer_logs()
if reason is not None:
emit(f"{reason}; using local log.")
return gate_is_due()
written = module.autolog_due_delivery(emit) if autolog else 0
due = gate_is_due()
if written and not due:
reason = module.publish_after_log()
if reason is not None:
emit(f"auto-logged locally, not yet published ({reason}).")
return due
def cmd_gate(emit: Callable[[str], None], *, check: bool, demo: bool) -> int:
@ -97,7 +113,7 @@ def cmd_gate(emit: Callable[[str], None], *, check: bool, demo: bool) -> int:
For ``--check``: 0 if not due, 1 if a lock is due. Otherwise 0.
"""
if check:
due = _should_lock(emit)
due = _should_lock(emit, autolog=False)
emit("due (a lock is warranted)" if due else "ok (no lock needed)")
return 1 if due else 0
if not demo and not _should_lock(emit):

View File

@ -27,16 +27,14 @@ prominent, with macros and the protein target beneath. The unlock condition is
*logging*, never *estimating correctly*: a manual calorie value always works
offline, so a dead OFF endpoint can never trap you behind the lock.
Building ``MealGate`` spans several sibling modules to keep each under the
repo's 250-line limit: :mod:`._gatelock_core` provides the shared leaf
widget/field helpers and state (``_GateCore``, ``_GateState``);
:mod:`._gatelock_nutrition` provides the reference->total nutrition maths and
food lookup (``_GateNutrition``); :mod:`._gatelock_mealflow` provides the
submit/log flow, dashboard, callback errors and the pull-it-in buttons
(``_GateMealFlow`` + ``_PullFlows``); :mod:`._gatelock_calendar` the tab --
the budget-adherence calendar, streaks, YTD tally (:mod:`._daystatus`) and
budget editing (``_GateCalendar``). ``MealGate`` wires these together, owns the
``gatelock.LockWindow``, and handles construction, layout and event binding.
Building ``MealGate`` spans several sibling modules (the 250-line limit):
:mod:`._gatelock_core` holds the shared leaf widget/field helpers and state
(``_GateCore``, ``_GateState``, the Claude button's glue);
:mod:`._gatelock_nutrition` the reference->total maths and food lookup;
:mod:`._gatelock_mealflow` the submit/log flow, dashboard, callback errors and
pull-it-in buttons (``_GateMealFlow`` + ``_PullFlows``); :mod:`._gatelock_calendar`
the tab -- calendar, streaks, YTD tally (:mod:`._daystatus`), budget editing.
``MealGate`` wires these together and owns the ``gatelock.LockWindow``.
"""
from __future__ import annotations
@ -161,6 +159,7 @@ class MealGate(_GateCalendar):
on_fetch_sync=self._on_fetch_sync,
on_load_delivery=self._on_load_delivery,
on_fill_all=self._on_fill_all,
on_claude=self._on_claude,
)
self._build()

View File

@ -0,0 +1,173 @@
"""The lock screen's Claude button: estimate the typed meal, log it, unlock.
The user types a description and presses the sparkle instead of filling the
macro fields. The text (never a photo, the PC has none) goes to
:func:`diet_guard._claude_estimate.estimate_meal`; on success the meal is
logged through the gate's own ``record`` hook, so it takes the same path as a
typed meal: the slot being locked for, the food bank, the dashboard, the
unlock. Its entry carries ``source="claude"``.
**It can never make the lock worse.** Four rules, each with a test:
* *Off the Tk thread.* The call runs on a daemon thread that only ``put``s on
a queue; the Tk thread polls it with ``after`` (Tcl is not thread-safe, and
a model call takes seconds). A daemon so a hung call cannot keep the
``Type=oneshot`` unit alive once the window is gone.
* *A hard 45 s deadline* on the poll, whatever the worker does. Past it the
result is abandoned and a late answer is discarded.
* *Any failure is an icon, nothing else.* No login, timeout, bad JSON, a bug:
the button shows the error icon and the manual log path is untouched. There
is no state in which a failed estimate unlocks, blocks or freezes anything.
* *A result for a slot that moved on is dropped*: if the user logged the slot
by hand while Claude thought, the answer must not land on the next one.
Composed into the gate (as ``FillAllFlow`` is) rather than mixed in: pylint's
``max-parents`` counts every class in the gate's MRO and the chain is at the
cap. The gate hands this object the few callables it needs.
``_claude_estimate`` reaches the Agent SDK, which the gate's frequent not-due
tick must not import, so the name resolves on first access (PEP 562) and a
test's ``patch.object`` still wins.
"""
from __future__ import annotations
from contextlib import suppress
from importlib import import_module
import queue
import sys
import threading
from time import monotonic
from typing import TYPE_CHECKING, NamedTuple
from diet_guard import _gatelock_glyphs as g
from diet_guard._estimator import Nutrition
from diet_guard._gatelock_fetch import FETCH_POLL_MS
if TYPE_CHECKING: # pragma: no cover - typing only
from collections.abc import Callable
import tkinter as tk
from diet_guard._claude_schema import Estimate
#: The poll's hard deadline in seconds; the estimator's own budget matches it.
CLAUDE_TIMEOUT_S = 45.0
#: Polls between spinner frames (50 ms each).
_FRAME_TICKS = 4
#: ``Nutrition.source`` of an estimated meal; keys ``g.source_glyph``.
SOURCE = "claude"
def __getattr__(name: str) -> object:
"""Resolve the deferred estimator import on first attribute access."""
if name != "estimate_meal":
msg = f"module {__name__!r} has no attribute {name!r}"
raise AttributeError(msg)
return import_module("diet_guard._claude_estimate").estimate_meal
def start_estimate(text: str) -> queue.Queue[Estimate | None]:
"""Run the estimator on a daemon thread; return its result queue.
The queue always receives exactly one item: the estimate, or ``None`` for
any failure (the worker has nowhere to propagate to, so an escaping
exception would leave the poll waiting for the whole deadline).
"""
result: queue.Queue[Estimate | None] = queue.Queue(maxsize=1)
def _worker() -> None:
"""Runs OFF the Tk thread. Touches no widget, by construction."""
outcome: Estimate | None = None
with suppress(Exception):
outcome = sys.modules[__name__].estimate_meal(text, None)
result.put(outcome)
threading.Thread(target=_worker, daemon=True).start()
return result
class ClaudeHooks(NamedTuple):
"""What the flow calls back into the gate."""
#: The typed description.
get_desc: Callable[[], str]
#: The gate's status-line writer.
set_status: Callable[..., None]
#: The slot the gate is locking for now, None when nothing is pending.
slot: Callable[[], int | None]
#: Log and advance, exactly like a typed meal (``_GateMealFlow._record``).
record: Callable[[str, Nutrition], None]
class ClaudeFlow:
"""Drives one gate's Claude button through estimate, poll and log."""
def __init__(self, root: tk.Misc, label: tk.StringVar, hooks: ClaudeHooks) -> None:
"""Bind the flow to a gate.
Args:
root: Schedules the poll on the Tk thread.
label: The button's icon, shared by its copy on every monitor.
hooks: The gate callbacks the flow drives.
"""
self._root = root
self._label = label
self._hooks = hooks
self._result: queue.Queue[Estimate | None] | None = None
self._slot: int | None = None
self._deadline = 0.0
self._tick = 0
def click(self) -> None:
"""Estimate the typed meal; a click while one is running is ignored."""
if self._result is not None:
return
text = self._hooks.get_desc()
if not text:
self._hooks.set_status(f"{g.ERROR} {g.FOOD}", error=True)
return
self._slot = self._hooks.slot()
self._deadline = monotonic() + CLAUDE_TIMEOUT_S
self._tick = 0
self._label.set(g.CLAUDE_BUSY[0])
self._result = sys.modules[__name__].start_estimate(text)
self._root.after(FETCH_POLL_MS, self._poll)
def _poll(self) -> None:
"""On the Tk thread: spin, time out, or pick up the estimate."""
result = self._result
if result is None:
return
try:
estimate = result.get_nowait()
except queue.Empty:
if monotonic() >= self._deadline:
self._finish(failed=True)
return
self._tick += 1
frames = g.CLAUDE_BUSY
self._label.set(frames[self._tick // _FRAME_TICKS % len(frames)])
self._root.after(FETCH_POLL_MS, self._poll)
return
if estimate is None:
self._finish(failed=True)
return
self._finish(failed=False)
if self._hooks.slot() != self._slot:
return # the user moved on while Claude thought
nutrition = Nutrition(
kcal=estimate.kcal,
protein_g=estimate.protein_g,
carbs_g=estimate.carbs_g,
fat_g=estimate.fat_g,
grams=estimate.grams,
source=SOURCE,
)
self._hooks.record(estimate.desc, nutrition)
def _finish(self, *, failed: bool) -> None:
"""Free the button before anything else can raise."""
self._result = None
self._label.set(g.CLAUDE_FAILED if failed else g.CLAUDE)

View File

@ -15,6 +15,7 @@ import logging
import tkinter as tk
from typing import TYPE_CHECKING
from diet_guard._gatelock_claude import ClaudeFlow, ClaudeHooks
from diet_guard._gatelock_glyphs import CLOCK, OK
from diet_guard._gatelock_ui import (
BASIS_PREFIX_GRAMS,
@ -85,6 +86,28 @@ class _GateCore:
_vars: GateVars
_widgets: GateWidgets
close: Callable[[], None]
# Supplied by ``_GateMealFlow``, which sits below this class.
_set_status: Callable[..., None]
_record: Callable[[str, Nutrition], None]
#: Built on the first Claude click; it holds that button's state.
_claude_flow: ClaudeFlow | None = None
def _on_claude(self) -> None:
"""Estimate the typed meal with Claude and log it like a typed one.
Composed (:mod:`._gatelock_claude`), not a mixin: the gate's MRO is at
pylint's ``max-parents`` cap. Built once, on the first click.
"""
if self._claude_flow is None:
hooks = ClaudeHooks(
self._get_desc,
self._set_status,
lambda: self._pending[0] if self._pending else None,
self._record,
)
self._claude_flow = ClaudeFlow(self.root, self._vars.claude_label, hooks)
self._claude_flow.click()
# -- description field ---------------------------------------------------

View File

@ -9,9 +9,9 @@ link in the controller chain -- pylint caps that chain's depth and the gate is
at the limit -- and a separate module so both stay under the 250-line cap.
**Neither logs anything by itself.** The catering fetch fills the form and
stops; the user still clicks "Log & Continue". Auto-submitting would let the
gate satisfy its own checkpoint from a delivery note, which is the one thing
this feature is designed not to do.
stops; the user still clicks "Log & Continue". The tap-free logging happens
earlier and elsewhere (:mod:`diet_guard._kuchnia_autolog`, before the window
opens), never from inside it.
"""
from __future__ import annotations

View File

@ -2,8 +2,10 @@
Two clicks, never one. The first fetches the day's delivery off the Tk thread
and shows exactly what would be written; the button relabels to "Confirm (N)".
Only the second click writes. A delivered meal is not an eaten meal, so the
user sees the dishes and the slots before anything lands -- and no modal
Only the second click writes. This is the *manual* path; the pre-lock
auto-log (:mod:`diet_guard._kuchnia_autolog`) logs due slots without a tap, but
this button reaches every slot, so the user sees the dishes and the slots
before anything lands -- and no modal
dialog asks instead, because a pop-up over a fullscreen grab risks stealing the
very keyboard grab the lock depends on.

View File

@ -53,6 +53,15 @@ FILL_ALL: Final = "⇊"
INFINITE: Final = "∞"
UNLOCKING: Final = "⇥"
# The Claude estimate button: idle, one frame per poll tick while working
# (the spinner), and the error state it rests in until the next click. Idle is
# the monochrome four-pointed star, not the sparkles emoji (U+2728): that one
# is only in FreeSerif and Noto Color Emoji here, and a colour-emoji fallback
# can crash Tk 8.6 -- the one window that must never fail to draw.
CLAUDE: Final = "✦"
CLAUDE_BUSY: Final = "◐◓◑◒"
CLAUDE_FAILED: Final = "⚠"
# Notebook tabs.
TAB_LOG: Final = "✚"
TAB_HISTORY: Final = "▦"
@ -84,5 +93,6 @@ def source_glyph(source: str) -> str:
"food bank": "▤",
"staple": "★",
"catering": DELIVERY,
"claude": CLAUDE,
"manual": FOOD,
}.get(head, "≈")

View File

@ -22,7 +22,8 @@ exists to forbid, so the pattern is copied rather than bent:
the window is gone -- the gate is a ``Type=oneshot`` unit and must exit.
Nothing here logs anything. The fetch only *offers* dishes; writing entries is
a separate, explicitly confirmed step (:mod:`diet_guard._kuchnia_log`).
a separate, explicitly confirmed step (:mod:`diet_guard._kuchnia_log`), or the
tap-free pre-lock auto-log (:mod:`diet_guard._kuchnia_autolog`).
"""
from __future__ import annotations

View File

@ -102,15 +102,30 @@ def _build_readouts(body: tk.Frame, vars_: GateVars) -> None:
def _build_actions(
body: tk.Frame, callbacks: GateCallbacks, fill_label: tk.StringVar
body: tk.Frame,
callbacks: GateCallbacks,
fill_label: tk.StringVar,
claude_label: tk.StringVar,
) -> None:
"""Pack the submit button and the three "pull it in" buttons."""
"""Pack the submit and Claude buttons, then the "pull it in" buttons."""
log = tk.Frame(body, bg=BG) # one row: no extra height (1366x768 fit test)
log.pack(pady=(XS, XS))
make_button(
body,
log,
_COLORS,
glyphs.SUBMIT,
callbacks.on_submit,
).pack(pady=(XS, XS))
).pack(side="left", padx=(0, XS))
# Claude estimates the typed meal and logs it; the icon is a shared variable.
claude = make_button(
log,
_COLORS,
claude_label.get(),
callbacks.on_claude,
ButtonStyle(variant="secondary", bold=False),
)
claude.configure(textvariable=claude_label)
claude.pack(side="left")
# Both "pull it in from elsewhere" actions share one row: stacking them
# cost 42px, which pushed the tab past the viewport on a 1366x768 screen
@ -129,8 +144,8 @@ def _build_actions(
).pack(side="left", padx=(0, XS))
# Today's catering delivery, with its real macros. Loading only *offers*
# the dishes -- each still has to be checked and submitted, because a
# delivered meal is not an eaten meal.
# the dishes -- each still has to be checked and submitted here (the
# pre-lock auto-log, when it runs, has already logged the due slots).
make_button(
pulls,
_COLORS,
@ -192,7 +207,7 @@ def build_layout(
basis_prefix, per_entry, macros = build_macro_section(root, body, vars_)
_build_readouts(body, vars_)
_build_actions(body, callbacks, vars_.fill_label)
_build_actions(body, callbacks, vars_.fill_label, vars_.claude_label)
status_label = tk.Label(
body,

Some files were not shown because too many files have changed in this diff Show More