Compare commits

..

No commits in common. "main" and "v1.0.191" have entirely different histories.

28 changed files with 276 additions and 859 deletions

33
.github/workflows/file-length.yml vendored Normal file
View File

@ -0,0 +1,33 @@
name: file-length
# The 250-line cap, enforced on push as well as at commit time. The local
# pre-commit hook can be skipped (a fresh clone that never ran `pre-commit
# install` has no hooks at all), so the cap needs a second gate that no one
# can forget to install.
#
# Deliberately a SEPARATE workflow from release-apk.yml: a file that grew too
# long should fail lint, not block publishing an APK.
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
jobs:
file-length:
name: file length <= 250 lines
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# The gate and its exemption list live in the shared utils repo so every
# repo enforces the same cap. Checking it out beats vendoring a copy
# here, which is exactly how a gate and a survey start disagreeing.
- name: Check out the shared gate
uses: actions/checkout@v4
with:
repository: kuhyx/utils
path: .utils
- name: Enforce the cap
run: bash .utils/scripts/check_file_length.sh --all

View File

@ -17,9 +17,15 @@ jobs:
fail-fast: false
matrix:
include:
- group: mypy
hooks: mypy
skip: ""
- group: pylint
hooks: pylint
skip: ""
- group: rest
hooks: ""
skip: "dependency-freshness"
skip: mypy,pylint,dependency-freshness
name: pre-commit (${{ matrix.group }})
steps:
- uses: actions/checkout@v4

View File

@ -25,6 +25,11 @@ repos:
- id: check-merge-conflict
- id: detect-private-key
- id: debug-statements
- id: name-tests-test
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|claude_redirects|claude_fakes|claude_worker_fakes)\.py$
- id: check-ast
- id: mixed-line-ending
args: [--fix=lf]
@ -52,9 +57,88 @@ repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.15.2
hooks:
- id: ruff
args: [--fix, --unsafe-fixes, --exit-non-zero-on-fix, --show-fixes]
types_or: [python, pyi]
- id: ruff-format
types_or: [python, pyi]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.13.0
hooks:
- id: mypy
args:
- --ignore-missing-imports
- --no-error-summary
- --disable-error-code=no-untyped-def
- --disable-error-code=no-untyped-call
- --disable-error-code=var-annotated
- --disable-error-code=no-any-unimported
- --disable-error-code=type-arg
- --disable-error-code=no-any-return
- --disable-error-code=misc
- --disable-error-code=unused-ignore
- --disable-error-code=unreachable
- --disable-error-code=assignment
- --disable-error-code=no-redef
- --disable-error-code=attr-defined
- --disable-error-code=arg-type
- --disable-error-code=union-attr
- --disable-error-code=call-overload
- --disable-error-code=return-value
- --disable-error-code=redundant-cast
- --disable-error-code=empty-body
- --disable-error-code=list-item
additional_dependencies:
- types-requests
- repo: https://github.com/pylint-dev/pylint
rev: v3.3.2
hooks:
- id: pylint
# pre-commit itself runs on 3.15 and `python3` resolves to it; this
# pylint's --jobs=4 pickles with dill, which crashes there
# (no `co_lnotab`). The repo targets 3.14.
language_version: python3.14
args:
- --rcfile=pyproject.toml
- --fail-under=10
- --jobs=4
additional_dependencies:
- pytest
- requests
# Kept in step with pyproject.toml: pip refuses two different
# direct URLs for one distribution, so any pin that drifts from
# the manifest becomes an unresolvable hook environment rather
# than merely an old one.
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.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.5#subdirectory=sickdays
- kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.0#subdirectory=kuhy_credit
- rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.1#subdirectory=rtdb_relay
- claude-agent-sdk==0.2.184
- httpx==0.28.1
- mcp>=2,<3
- pydantic
- defusedxml==0.7.1
# Test suites intentionally use patterns (protected-access, magic-value
# comparisons) that don't belong in the source-code 10/10 gate.
exclude: ^(\.venv/)|(^|/)(tests/|conftest\.py)
- repo: https://github.com/PyCQA/bandit
rev: 1.7.10
hooks:
- id: bandit
args:
- -c
- pyproject.toml
- --severity-level=high
- --confidence-level=medium
- --skip=B113
additional_dependencies: ["bandit[toml]"]
exclude: ^(tests/|.*test.*\.py$)
- repo: local
hooks:
# Split into <60 s steps (run in this order); no-arg ci_mirror.sh is the CI form.
@ -82,6 +166,14 @@ repos:
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-flutter-analyze
name: CI mirror 4 (flutter analyze)
entry: bash scripts/ci_mirror.sh flutter-analyze
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-flutter-test-1
name: CI mirror 5 (flutter test 1/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 0/12
@ -179,6 +271,15 @@ repos:
require_serial: true
stages: [manual]
- repo: https://github.com/codespell-project/codespell
rev: v2.3.0
hooks:
- id: codespell
args:
- --skip=*.json,*.lock,.git,__pycache__,.venv
# Devine: the 1974 ideal-body-weight formula's author, not "define".
- --ignore-words-list=devine
- repo: local
hooks:
# Fails a commit that still points crdt_sync at a local path. Local
@ -199,6 +300,29 @@ repos:
pass_filenames: false
always_run: true
require_serial: true
- id: shellcheck
name: shellcheck
entry: bash -c 'printf "%s\0" "$@" | xargs -0 -n 40 shellcheck --severity=warning' --
language: system
types: [shell]
# A PKGBUILD is a makepkg manifest, not a standalone script: it has no
# shebang (SC2148) and its variables are read by makepkg rather than by
# the file itself (SC2034). namcap is what actually lints these.
exclude: '^packaging/aur/PKGBUILD$'
# The shared 250-line cap. Checks only the files in the commit, so an
# unrelated commit never breaks; exits 1 rather than warning. No
# baseline and no allowlist -- those are suppressions. The exemption
# list (generated/vendored/data files) lives with the checker in
# ~/src/utils/file_length/config.py so the gate and the survey cannot
# disagree.
#
# Deliberately unfiltered: no types_or and no files. The cap applies to
# Dart and prose too, and a type filter here is what would silently
# exempt the whole Flutter app and every .md.
- id: file-length
name: file length <= 250 lines
entry: scripts/check_file_length.sh
language: system
# unittest.mock.patch fails OPEN: once a refactor moves a name, a patch
# target that still imports redirects nothing, the test passes, and the

View File

@ -20,10 +20,10 @@ show adherence, streaks, a YTD tally and weekly/monthly averages, all derived fr
- 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`
- test-changed: `scripts/test_changed.sh` (maps py and app/ dart changes to their tests, no coverage)
- lint: n/a: dropped (kuhy, 2026-11-27)
- coverage: n/a: dropped (kuhy, 2026-11-27)
- lint: `pre-commit run --all-files`
- coverage: `python -m pytest -n auto -p no:sugar -q` (writes coverage.lcov)
- deploy: `bash scripts/deploy.sh` (pull ~/src/diet-guard, system-Python install, desktop app; health-checked)
- coverage-gaps: n/a: dropped (kuhy, 2026-11-27)
- coverage-gaps: `coverage-gaps coverage.lcov`
## Scheduling
@ -143,7 +143,6 @@ install -e`, so the clone must persist for `git pull` to reach the running servi
`test_budget_history.py`; it syncs as `hist:<YYYY-MM-DD>` fields on the
existing `budget` record, so devices predating the feature relay them
untouched.
- **Offline first**: save locally before any network call; store fetched data on disk (`kuchnia_delivery.json`, both devices).
- **Body data persists and syncs** (profile, weight log, PC workouts) as
`body.json`; its tables are informational. [docs/DOCS-body.md](docs/DOCS-body.md).
- **PC and phone share one source of truth for everything**: food log, budget,

View File

@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.2-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-all.zip

View File

@ -13,11 +13,9 @@ 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/document_store_factory.dart';
import 'package:diet_guard_app/services/firebase_client.dart' show openFirebase;
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_autolog.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
import 'package:diet_guard_app/services/kuchnia_queue.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
@ -58,8 +56,6 @@ Future<void> main() async {
await KuchniaCredentialService.init();
await BodyService.init();
await KuchniaQueueService.init();
// Offline first: the day's catering dishes survive a restart.
KuchniaAutoLog.instance = KuchniaAutoLog(store: await openDocumentStore());
// The sparkle button's transport; until this line it fails closed.
claudeRelay = RtdbClaudeRelay.firebase();
final notifications = await NotificationService.init();

View File

@ -23,32 +23,6 @@ class KuchniaDish {
this.dishId = '',
});
/// Rebuilds a dish stored by [toJson]; throws on a malformed record.
factory KuchniaDish.fromJson(Map<String, Object?> json) => KuchniaDish(
name: json['name']! as String,
kcal: (json['kcal']! as num).toDouble(),
proteinG: (json['protein_g']! as num).toDouble(),
carbsG: (json['carbs_g']! as num).toDouble(),
fatG: (json['fat_g']! as num).toDouble(),
grams: (json['grams']! as num).toDouble(),
priority: json['priority']! as int,
slotLabel: json['slot_label']! as String,
dishId: json['dish_id'] as String? ?? '',
);
/// The stored form; the keys follow the PC's `kuchnia_delivery.json`.
Map<String, Object?> toJson() => {
'name': name,
'kcal': kcal,
'protein_g': proteinG,
'carbs_g': carbsG,
'fat_g': fatG,
'grams': grams,
'priority': priority,
'slot_label': slotLabel,
'dish_id': dishId,
};
/// The dish itself (`menuMealName`), e.g. "Kaszotto grzybowe...".
///
/// Not `mealName`, which is the slot label ("Kolacja") and would collapse

View File

@ -162,7 +162,6 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen>
// it says nothing about Firebase.
IconButton.outlined(
onPressed: _busy ? null : _testConnection,
tooltip: 'Test',
icon: const Icon(
Icons.network_check,
semanticLabel: 'Test GitHub connection',

View File

@ -47,27 +47,22 @@ List<Widget> logMealAppBarActions({
}) => [
...leading,
IconButton(
tooltip: 'Body',
icon: const Icon(Icons.monitor_weight, semanticLabel: 'Body'),
onPressed: onBody,
),
IconButton(
tooltip: 'Foods',
icon: const Icon(Icons.restaurant_menu, semanticLabel: 'Food bank'),
onPressed: onFoodBank,
),
IconButton(
tooltip: 'History',
icon: const Icon(Icons.history, semanticLabel: 'History'),
onPressed: onHistory,
),
IconButton(
tooltip: 'Calendar',
icon: const Icon(Icons.calendar_month, semanticLabel: 'Calendar'),
onPressed: onCalendar,
),
IconButton(
tooltip: 'Sync',
icon: const Icon(Icons.settings, semanticLabel: 'Sync settings'),
onPressed: onSettings,
),

View File

@ -13,21 +13,16 @@
/// 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 in `store` (`kuchnia_delivery.json`), so a restart or an outage still
/// has them (offline first); a failed or empty fetch is retried at most every
/// [retryAfter].
/// 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 'dart:convert';
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/document_store.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';
@ -49,7 +44,6 @@ class KuchniaAutoLog {
DeliveryFetch? fetch,
DateTime Function()? now,
this.retryAfter = const Duration(minutes: 10),
this.store,
}) : _fetch = fetch ?? refreshDelivery,
_now = now ?? DateTime.now;
@ -59,12 +53,6 @@ class KuchniaAutoLog {
/// Minimum gap between fetches that found nothing or failed.
final Duration retryAfter;
/// Keeps the day's dishes across restarts; null keeps them in memory only.
final DocumentStore? store;
/// The document [store] holds the last fetched delivery in.
static const documentName = 'kuchnia_delivery.json';
final DeliveryFetch _fetch;
final DateTime Function() _now;
String? _cachedDay;
@ -106,56 +94,14 @@ class KuchniaAutoLog {
Future<List<KuchniaDish>> _dishesFor(DateTime today, String dayKey) async {
if (_cachedDay == dayKey) return _cachedDishes;
final stored = await _readStored(dayKey);
if (stored.isNotEmpty) {
_cachedDay = dayKey;
return _cachedDishes = stored;
}
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;
await _writeStored(dayKey, result.dishes);
return _cachedDishes = result.dishes;
}
_lastEmptyFetch = _now();
return const [];
}
Future<List<KuchniaDish>> _readStored(String dayKey) async {
final target = store;
if (target == null) return const [];
try {
final raw = await target.read(documentName);
if (raw == null) return const [];
final data = jsonDecode(raw);
if (data is! Map<String, Object?> || data['day'] != dayKey) {
return const [];
}
final dishes = data['dishes'];
if (dishes is! List) return const [];
return [
for (final item in dishes)
if (item is Map<String, Object?>) KuchniaDish.fromJson(item),
];
} on Object {
// A missing, foreign or malformed file is "nothing stored": fetch again.
return const [];
}
}
Future<void> _writeStored(String dayKey, List<KuchniaDish> dishes) async {
final target = store;
if (target == null) return;
final body = {
'day': dayKey,
'dishes': [for (final dish in dishes) dish.toJson()],
};
try {
await target.write(documentName, jsonEncode(body));
} on Exception {
// Best-effort: an unsaved delivery only costs a refetch after a restart.
}
}
}

View File

@ -123,7 +123,6 @@ class MealTimeDropdown extends StatelessWidget {
),
),
IconButton(
tooltip: 'Time',
icon: const Icon(
Icons.schedule,
semanticLabel: 'Type or pick an exact time',

View File

@ -157,20 +157,20 @@ packages:
dependency: "direct main"
description:
path: crdt_sync_dart
ref: "crdt_sync_dart-v0.14.2"
resolved-ref: "171a7f8ae34cec78df17a680e42878ca0b97c137"
ref: "crdt_sync_dart-v0.14.1"
resolved-ref: edd0f7a7882cb1d3904932ba94faa282d08165df
url: "https://github.com/kuhyx/utils"
source: git
version: "0.14.2"
version: "0.14.1"
crdt_sync_flutter:
dependency: "direct main"
description:
path: crdt_sync_flutter
ref: "crdt_sync_flutter-v0.9.2"
resolved-ref: "41af57870207f80a5bf571f15544a08fddcbe7bf"
ref: "crdt_sync_flutter-v0.9.1"
resolved-ref: "48dc28ad97b97c787aba4479c3ce51aade6e86b5"
url: "https://github.com/kuhyx/utils"
source: git
version: "0.9.2"
version: "0.9.1"
cross_file:
dependency: transitive
description:
@ -207,11 +207,11 @@ packages:
dependency: "direct main"
description:
path: data_transfer_flutter
ref: "data_transfer_flutter-v0.2.4"
resolved-ref: "5c2effe7d1148830c9e273e47a272791dc17509e"
ref: "data_transfer_flutter-v0.2.3"
resolved-ref: bb2f92f459283a29ad4864cf37704cc5f749cc6d
url: "https://github.com/kuhyx/utils"
source: git
version: "0.2.4"
version: "0.2.3"
dbus:
dependency: transitive
description:
@ -280,10 +280,10 @@ packages:
dependency: transitive
description:
name: file_picker
sha256: "5b99250437a4d34ee2cdc0686924452103540eaa1c248094b63f07f9d7216f6c"
sha256: c3780977700b8962c3b9b6a9aa4e2c988956893d70d4a4fa2d7adf4ec9b9eaee
url: "https://pub.dev"
source: hosted
version: "13.4.1"
version: "13.4.0"
file_picker_darwin:
dependency: transitive
description:
@ -296,10 +296,10 @@ packages:
dependency: transitive
description:
name: file_picker_linux
sha256: cf3889644e8e54551f5c3a4f98b6b6ef5f0ef85c07d2a0c1a969538983be2f9b
sha256: "9215ee8c672508cdd9a325202669f849e1baac883658626b3abed5d7777e6a4b"
url: "https://pub.dev"
source: hosted
version: "2.0.5"
version: "2.0.4"
file_picker_platform_interface:
dependency: transitive
description:
@ -392,10 +392,10 @@ packages:
dependency: "direct main"
description:
name: fl_chart
sha256: "19e4b58179f77b0858ddb9f2db321394e466cba7b2b918b0af7abd79754a1de9"
sha256: "9f11b0b87a6b1843f5ca666ade4a62c08da1a6b7f9efeb91bb2c6f3fa6e31a9a"
url: "https://pub.dev"
source: hosted
version: "1.3.2"
version: "1.3.1"
flutter:
dependency: "direct main"
description: flutter
@ -413,10 +413,10 @@ packages:
dependency: "direct main"
description:
name: flutter_local_notifications
sha256: "2b7579556c117b535ef83835798a7f3c4003dc892a888a4a99f2107bca7b6675"
sha256: "7d37d69ded3028af4f22531a0097a3baa478a384dff2e23e873707c93df3b704"
url: "https://pub.dev"
source: hosted
version: "23.0.4"
version: "23.0.3"
flutter_local_notifications_linux:
dependency: transitive
description:
@ -686,11 +686,11 @@ packages:
dependency: "direct main"
description:
path: "kuhy_credit/flutter"
ref: "kuhy-credit-v0.3.2"
resolved-ref: adeb40f68e1d6c701da43e396fc46bffa3ef10c7
ref: "kuhy-credit-v0.3.0"
resolved-ref: c3946412729991bf1e9c3b6a5cc55dbe80419fc0
url: "https://github.com/kuhyx/utils"
source: git
version: "0.3.2"
version: "0.3.0"
leak_tracker:
dependency: transitive
description:
@ -1076,11 +1076,11 @@ packages:
dependency: "direct main"
description:
path: sync_settings_ui
ref: "sync_settings_ui-v0.8.6"
resolved-ref: "41af57870207f80a5bf571f15544a08fddcbe7bf"
ref: "sync_settings_ui-v0.8.4"
resolved-ref: "15ef5b44f186cea0ab163cc88cb8743c51d58247"
url: "https://github.com/kuhyx/utils"
source: git
version: "0.8.6"
version: "0.8.4"
synchronized:
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.197+1
version: 1.0.191+1
environment:
sdk: ^3.12.2
@ -12,13 +12,13 @@ dependencies:
crdt_sync:
git:
url: https://github.com/kuhyx/utils
ref: crdt_sync_dart-v0.14.2
ref: crdt_sync_dart-v0.14.1
path: crdt_sync_dart
# Keystore-backed end-to-end encryption open + the passphrase lock button.
crdt_sync_flutter:
git:
url: https://github.com/kuhyx/utils
ref: crdt_sync_flutter-v0.9.2
ref: crdt_sync_flutter-v0.9.1
path: crdt_sync_flutter
crypto: 3.0.8
cryptography: 2.9.0
@ -27,12 +27,12 @@ dependencies:
data_transfer_flutter:
git:
url: https://github.com/kuhyx/utils
ref: data_transfer_flutter-v0.2.4
ref: data_transfer_flutter-v0.2.3
path: data_transfer_flutter
fl_chart: 1.3.2
fl_chart: 1.3.1
flutter:
sdk: flutter
flutter_local_notifications: 23.0.4
flutter_local_notifications: 23.0.3
flutter_secure_storage: 11.2.0
# One-tap sign-in for the sync account. App-side only: crdt_sync stays pure
@ -56,7 +56,7 @@ dependencies:
kuhy_credit:
git:
url: https://github.com/kuhyx/utils
ref: kuhy-credit-v0.3.2
ref: kuhy-credit-v0.3.0
path: kuhy_credit/flutter
material_ui: 1.11.1
path: 1.9.1
@ -71,7 +71,7 @@ dependencies:
sync_settings_ui:
git:
url: https://github.com/kuhyx/utils
ref: sync_settings_ui-v0.8.6
ref: sync_settings_ui-v0.8.4
path: sync_settings_ui
url_launcher: 6.3.3
uuid: 4.6.0

View File

@ -1,27 +0,0 @@
import 'package:diet_guard_app/screens/log_meal_actions.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('logMealAppBarActions tooltips name each icon', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
appBar: AppBar(
actions: logMealAppBarActions(
onFoodBank: () {},
onHistory: () {},
onCalendar: () {},
onSettings: () {},
onBody: () {},
),
),
),
),
);
for (final label in ['Body', 'Foods', 'History', 'Calendar', 'Sync']) {
expect(find.byTooltip(label), findsOneWidget, reason: label);
}
});
}

View File

@ -5,8 +5,7 @@
/// A word is two or more letters in a row. Allowed without listing: numbers,
/// punctuation, single letters, unit symbols next to a figure ([unitTokens])
/// and the method acronyms kept as DOUBT rows (`MET`). Content (food names,
/// workout labels, typed values) is passed per test as [content]. One-word
/// tooltips naming an icon are exempt (textgate one-word-tooltip exception).
/// workout labels, typed values) is passed per test as [content].
library;
import 'package:material_ui/material_ui.dart';
@ -17,15 +16,11 @@ const Set<String> unitTokens = {'kcal', 'kg', 'cm', 'lb', 'st', 'MET'};
final RegExp _word = RegExp('[A-Za-z]{2,}');
/// A one-word tooltip naming an icon (textgate exception, 2026-11-22).
final RegExp _oneWordTooltip = RegExp(r'^[A-Za-z][A-Za-z-]{0,19}$');
/// Every painted string in the current tree (one per [RichText] / tooltip).
List<String> paintedStrings(WidgetTester tester) => [
for (final w in tester.widgetList<RichText>(find.byType(RichText)))
w.text.toPlainText(includePlaceholders: false),
for (final w in tester.widgetList<Tooltip>(find.byType(Tooltip)))
if (w.message case final m? when !_oneWordTooltip.hasMatch(m)) m,
for (final w in tester.widgetList<Tooltip>(find.byType(Tooltip))) ?w.message,
];
/// The words in [text] that are neither units nor part of [content].

View File

@ -1,123 +0,0 @@
// The auto-log keeps the day's delivery on disk: offline first.
//
// A restart, or the caterer's panel being down, must not cost the dishes
// already fetched today. These tests pass an in-memory store as the disk.
import 'dart:convert';
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/kuchnia_autolog.dart';
import 'package:diet_guard_app/services/kuchnia_import.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: 'Obiad',
dishId: '${1000 + n}',
);
/// A disk that is full: every write fails.
class _FullStore implements DocumentStore {
@override
Future<String?> read(String name) async => null;
@override
Future<void> write(String name, String contents) async =>
throw Exception('disk');
}
void main() {
late int fetches;
late DateTime clock;
setUp(() {
freshStorage();
fetches = 0;
final today = DateTime.now();
clock = DateTime(today.year, today.month, today.day, 13);
});
KuchniaAutoLog autoLog(DocumentStore store, KuchniaRefresh result) =>
KuchniaAutoLog(
store: store,
fetch: (day) async {
fetches++;
return result;
},
now: () => clock,
);
const down = KuchniaRefresh(reason: 'down');
final delivered = KuchniaRefresh(dishes: [_dish(1), _dish(2)]);
test('a restart with the panel down still logs the stored dish', () async {
final store = MemoryStore();
await autoLog(store, delivered).logDue([960]);
expect(fetches, 1);
final written = await autoLog(store, down).logDue([480]);
expect(fetches, 1, reason: 'the stored delivery answers, no refetch');
expect(written.map((e) => e.desc), ['D1']);
});
test('a stored delivery of another day is ignored', () async {
final store = MemoryStore();
store.documents[KuchniaAutoLog.documentName] = jsonEncode({
'day': '1999-01-01',
'dishes': [_dish(1).toJson()],
});
expect(await autoLog(store, down).logDue([480]), isEmpty);
expect(fetches, 1);
});
test('a malformed stored document is ignored', () async {
final store = MemoryStore();
for (final raw in [
'not json',
'[]',
jsonEncode({'day': localDateKey(clock), 'dishes': 'x'}),
jsonEncode({
'day': localDateKey(clock),
'dishes': [
{'name': 'D1'},
],
}),
]) {
store.documents[KuchniaAutoLog.documentName] = raw;
expect(await autoLog(store, down).logDue([480]), isEmpty, reason: raw);
}
expect(fetches, 4);
});
test('non-map items in a stored delivery are skipped', () async {
final store = MemoryStore();
store.documents[KuchniaAutoLog.documentName] = jsonEncode({
'day': localDateKey(clock),
'dishes': [1, _dish(1).toJson()],
});
final written = await autoLog(store, down).logDue([480]);
expect(written.map((e) => e.desc), ['D1']);
expect(fetches, 0);
});
test('a failing disk does not break logging', () async {
final written = await autoLog(_FullStore(), delivered).logDue([480]);
expect(written.map((e) => e.desc), ['D1']);
});
test('toJson and fromJson round-trip every field', () {
final dish = _dish(3);
final back = KuchniaDish.fromJson(dish.toJson());
expect(back.toJson(), dish.toJson());
final noId = Map<String, Object?>.of(dish.toJson())..remove('dish_id');
expect(KuchniaDish.fromJson(noId).dishId, '');
});
}

View File

@ -171,10 +171,6 @@ KUCHNIA_SYNCED_CREDENTIAL_FILE: Path = (
KUCHNIA_LAST_IMPORT_FILE: Path = (
Path.home() / ".config" / "diet_guard" / "kuchnia_last_import"
)
# The last successfully-fetched delivery, so a panel outage can fall back to
# it instead of a blank import. Under DATA_DIR, not ~/.config: it is a cache,
# regenerable on the next successful fetch.
KUCHNIA_DELIVERY_CACHE_FILE: Path = DATA_DIR / "kuchnia_delivery.json"
KUCHNIA_TIMEOUT_SECONDS: float = 8.0
# Whole-walk ceiling. The import is 3-4 sequential requests, so a per-request
# timeout alone would permit ~32s against a slow provider.

View File

@ -1,112 +0,0 @@
"""Off-thread plumbing for the lock screen's food lookup.
The lookup used to run on the Tk thread. A food missing from the bank falls
through to an Open Food Facts request (8 s timeout), so the fullscreen lock
froze while it ran: a 1.5 s ``tk.mainloop`` stall was reported (c890f31a).
Same rules as :mod:`._gatelock_fetch`: the worker touches no widget and never
calls ``after`` (Tcl is not thread-safe); it only ``put``s its result on a
queue, and a poll scheduled on the Tk thread picks it up.
"""
from __future__ import annotations
import logging
import queue
import threading
from typing import TYPE_CHECKING
from diet_guard._gatelock_fetch import FETCH_POLL_MS
from diet_guard._resolve import lookup_candidates
if TYPE_CHECKING: # pragma: no cover - typing only
from collections.abc import Callable
from tkinter import Misc
from diet_guard._estimator import Nutrition
Candidates = list[tuple[str, Nutrition]]
__all__ = ["LookupRunner", "start_lookup"]
_logger = logging.getLogger(__name__)
def start_lookup(
lookup: Callable[[str], Candidates],
description: str,
) -> queue.Queue[Candidates]:
"""Run ``lookup(description)`` on a daemon thread; return the result queue.
Daemon so a hung request can never keep the process alive after the window
is gone -- the gate is a ``Type=oneshot`` unit and must exit.
"""
result: queue.Queue[Candidates] = queue.Queue(maxsize=1)
def _worker() -> None:
"""Runs OFF the Tk thread. Touches no widget, by construction."""
candidates: Candidates = []
try:
candidates = lookup(description)
# An unreadable bank or a malformed OFF payload; network errors are
# already caught inside ``off_candidates``.
except OSError, ValueError, KeyError, TypeError:
_logger.exception("food lookup failed")
finally:
# Always feed the queue, so the poll never waits forever and the
# form never stays busy. An empty result asks for a manual kcal.
result.put(candidates)
threading.Thread(target=_worker, daemon=True).start()
return result
class LookupRunner:
"""One food lookup at a time, collected on the Tk thread.
The window stays live while a lookup runs, so the user can log the meal by
hand and move on. A result for a food no longer in the description box is
dropped: applied late, it would fill the next slot with the wrong macros.
"""
def __init__(
self,
root: Misc,
on_result: Callable[[Candidates], None],
current: Callable[[], str],
) -> None:
"""Bind the runner to the Tk root, the result handler and the live text.
Args:
root: The gate's Tk root (schedules the poll).
on_result: Fills the form from the candidates, on the Tk thread.
current: Returns the description box's text right now.
"""
self._root = root
self._on_result = on_result
self._current = current
self._result: queue.Queue[Candidates] | None = None
self._description = ""
def start(self, description: str) -> bool:
"""Start a lookup; return False, starting nothing, if one is running."""
if self._result is not None:
return False
self._result = start_lookup(lookup_candidates, description)
self._description = description
self._root.after(FETCH_POLL_MS, self.poll)
return True
def poll(self) -> None:
"""On the Tk thread: hand a finished result over, else poll again."""
result = self._result
if result is None:
return
try:
candidates = result.get_nowait()
except queue.Empty:
self._root.after(FETCH_POLL_MS, self.poll)
return
self._result = None
if self._current() == self._description:
self._on_result(candidates)

View File

@ -18,8 +18,8 @@ from diet_guard._budget_derived import protein_target_g
from diet_guard._foodbank import remember_food
from diet_guard._gatelock_delivery import _PullFlows
from diet_guard._gatelock_fillall import RECONCILE_LABELS, FillAllFlow, FillHooks
from diet_guard._gatelock_lookup import LookupRunner
from diet_guard._gatelock_ui import ERR, FG, UNIT_GRAMS
from diet_guard._resolve import lookup_candidates
from diet_guard._slots import slot_label
from diet_guard._state import entry_kcal, log_meal
from diet_guard._state_today import (
@ -45,9 +45,6 @@ _DASH_DESC_WIDTH = 22
class _GateMealFlow(_PullFlows):
"""Submit/lookup/log flow for a logged food."""
#: The off-thread food lookup, made on first use (it needs ``root``).
_lookup: LookupRunner | None = None
# -- slot walk ------------------------------------------------------------
def _clear_inputs(self) -> None:
@ -114,19 +111,16 @@ class _GateMealFlow(_PullFlows):
self._record(description, nutrition)
def _begin_lookup(self, description: str) -> None:
"""Step 1: look the food up off the Tk thread; fill the form on return.
"""Step 1: look the food up, fill the label fields, offer alternatives.
Nothing is logged here -- the user must see and confirm the filled
values (a second submit) before they are recorded. A second submit
while a lookup runs is ignored.
values (a second submit) before they are recorded. The food is looked
up at its natural basis (per 100 g / serving); the amount eaten scales
it, so the lookup never bakes in a portion.
"""
if self._lookup is None:
self._lookup = LookupRunner(self.root, self._finish_lookup, self._get_desc)
if self._lookup.start(description):
self._set_status(g.BUSY)
def _finish_lookup(self, candidates: list[tuple[str, Nutrition]]) -> None:
"""Fill the label fields and offer alternatives, or ask for kcal."""
self.root.update_idletasks()
candidates = lookup_candidates(description)
if not candidates:
# Not found: the kcal field takes focus, the cue names it.
self._set_status(f"{g.ERROR} {g.source_glyph('')} kcal", error=True)

View File

@ -1,85 +0,0 @@
"""A local cache of the last successfully-fetched Kuchnia delivery.
Offline first: the panel is a third party that goes down, and a day's
delivery, once fetched, must stay usable without it. This module owns that
cache: :func:`save_delivery` after a successful fetch, :func:`load_delivery`
when the panel fails or the day was already fetched.
Every failure mode is "no cache": a missing file, bad JSON, another day's
delivery, or a half-written record all mean "fetch again", which is always
safe. The phone keeps the same file (``KuchniaAutoLog.store``).
"""
from __future__ import annotations
import dataclasses
import json
import logging
from typing import TYPE_CHECKING
from diet_guard import _constants
from diet_guard._kuchnia_parse import Dish
if TYPE_CHECKING: # pragma: no cover - typing only
from collections.abc import Sequence
from datetime import date
_LOGGER = logging.getLogger(__name__)
def load_delivery(day: date) -> list[Dish]:
"""Return the dishes cached for ``day``'s delivery, or ``[]``.
Any unreadable, malformed or foreign-day cache is treated as "no cache"
rather than an error: the caller falls back to the panel fetch, which is
strictly better than a stale import.
"""
path = _constants.KUCHNIA_DELIVERY_CACHE_FILE
try:
if not path.exists():
return []
raw = path.read_text()
except OSError:
return []
try:
data = json.loads(raw)
except json.JSONDecodeError:
return []
if not isinstance(data, dict) or data.get("day") != day.isoformat():
return []
dishes = data.get("dishes")
if not isinstance(dishes, list):
return []
out: list[Dish] = []
for item in dishes:
if not isinstance(item, dict):
continue
try:
out.append(Dish(**item))
except TypeError:
continue
return out
def save_delivery(day: date, dishes: Sequence[Dish]) -> None:
"""Persist ``day``'s delivery so a later outage can still import it.
Best-effort: a write failure only costs the fallback, so it is logged
and swallowed, never raised into the import path. The write goes to a
sibling ``.tmp`` and is atomically renamed, so a half-written file can
never poison :func:`load_delivery`.
"""
path = _constants.KUCHNIA_DELIVERY_CACHE_FILE
payload = json.dumps(
{
"day": day.isoformat(),
"dishes": [dataclasses.asdict(d) for d in dishes],
}
)
try:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(path.name + ".tmp")
tmp.write_text(payload)
tmp.replace(path)
except OSError:
_LOGGER.warning("could not save the kitchen delivery cache")

View File

@ -24,7 +24,6 @@ from typing import TYPE_CHECKING
from diet_guard._foodbank_manual import add_manual_entry, read_manual_bank
from diet_guard._kuchnia_client import PanelSession
from diet_guard._kuchnia_config import last_import_day, record_import_day
from diet_guard._kuchnia_delivery_cache import load_delivery, save_delivery
from diet_guard._kuchnia_errors import KuchniaError
from diet_guard._kuchnia_orders import fetch_dishes
@ -91,22 +90,16 @@ def refresh_delivery(day: date) -> tuple[list[Dish], str | None]:
day: The delivery date to fetch.
Returns:
``(dishes, None)`` on success. On a panel outage, the cached
delivery for ``day`` when one exists ``(cached, None)``, otherwise
``([], reason)`` with the failure reason so callers can surface it
and carry on.
``(dishes, None)`` on success, or ``([], reason)`` when the catering
panel could not be read. Callers surface the reason and carry on.
"""
try:
session = PanelSession()
session.authenticate()
dishes = fetch_dishes(session, day)
except KuchniaError as exc:
if cached := load_delivery(day):
return cached, None
return [], str(exc)
bank_dishes(dishes)
if dishes:
save_delivery(day, dishes)
return dishes, None
@ -130,13 +123,12 @@ def refresh_delivery_once(day: date) -> tuple[list[Dish], str | None]:
day: The delivery date to fetch.
Returns:
``(cached, None)`` when today was already fetched -- ``cached`` is the
saved delivery for the day (possibly empty), "nothing new", not an
``([], None)`` when today was already fetched -- "nothing new", not an
error. Otherwise whatever :func:`refresh_delivery` returns.
"""
stamp = day.isoformat()
if last_import_day() == stamp:
return load_delivery(day), None
return [], None
dishes, reason = refresh_delivery(day)
if reason is None and dishes:
# Only a fetch that found dishes counts: an outage, or a walk that

View File

@ -151,12 +151,6 @@ def state_redirects(tmp_path: Path) -> list[_patch[object]]:
"diet_guard._kuchnia_config.KUCHNIA_LAST_IMPORT_FILE",
tmp_path / "kuchnia_last_import",
),
# The outage fallback cache: without this a refresh_delivery test that
# saves one lands in the real DATA_DIR.
patch(
"diet_guard._constants.KUCHNIA_DELIVERY_CACHE_FILE",
tmp_path / "kuchnia_delivery.json",
),
# The catering fetch is a third network entry point. Patched at each
# call site, so a test importing `refresh_delivery` directly still
# exercises the real helper.

View File

@ -1,160 +0,0 @@
"""Tests for the off-thread food lookup of MealGate.
Covers :mod:`._gatelock_lookup` (``start_lookup``, ``LookupRunner``) and the
two ``_GateMealFlow`` methods that use it. The functional fake ``tk`` widgets
and the ``gate`` fixture live in ``conftest.py``.
"""
from __future__ import annotations
import queue
import threading
import time
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from diet_guard import _gatelock_glyphs as g
from diet_guard import _gatelock_lookup
from diet_guard._gatelock_fetch import FETCH_POLL_MS
from diet_guard._gatelock_lookup import LookupRunner, start_lookup
from diet_guard.tests.conftest import _nutrition
if TYPE_CHECKING:
import pytest
from diet_guard._estimator import Nutrition
from diet_guard._gatelock import MealGate
Candidates = list[tuple[str, Nutrition]]
def _failing_lookup(_desc: str) -> Candidates:
msg = "bad payload"
raise ValueError(msg)
class TestStartLookup:
"""The worker thread always feeds its queue."""
def test_puts_result(self) -> None:
"""A finished lookup's candidates land on the queue."""
found = [("apple", _nutrition(95, 100))]
assert start_lookup(lambda _d: found, "apple").get(timeout=5) == found
def test_failure_puts_empty_and_logs(
self, caplog: pytest.LogCaptureFixture
) -> None:
"""A failing lookup is logged and still answers, with no candidates."""
with caplog.at_level("ERROR"):
assert start_lookup(_failing_lookup, "x").get(timeout=5) == []
assert any("food lookup failed" in r.message for r in caplog.records)
class TestLookupRunner:
"""One lookup at a time, collected by a Tk-side poll."""
def test_start_schedules_poll(self) -> None:
"""Starting a lookup schedules the poll and reports it started."""
root = MagicMock()
runner = LookupRunner(root, MagicMock(), lambda: "apple")
with patch.object(_gatelock_lookup, "start_lookup", return_value=queue.Queue()):
assert runner.start("apple") is True
root.after.assert_called_once_with(FETCH_POLL_MS, runner.poll)
def test_second_start_while_running_is_ignored(self) -> None:
"""A second submit during a lookup starts nothing."""
runner = LookupRunner(MagicMock(), MagicMock(), lambda: "slow")
with patch.object(
_gatelock_lookup, "start_lookup", return_value=queue.Queue()
) as start:
runner.start("first")
assert runner.start("second") is False
start.assert_called_once()
def test_poll_reschedules_until_done(self) -> None:
"""An empty queue polls again; a result goes to the handler once."""
root, on_result = MagicMock(), MagicMock()
runner = LookupRunner(root, on_result, lambda: "apple")
pending: queue.Queue[Candidates] = queue.Queue()
with patch.object(_gatelock_lookup, "start_lookup", return_value=pending):
runner.start("apple")
runner.poll()
assert root.after.call_count == 2
on_result.assert_not_called()
pending.put([])
runner.poll()
on_result.assert_called_once_with([])
runner.poll() # nothing in flight any more: a stray poll is a no-op
assert root.after.call_count == 2
on_result.assert_called_once()
def test_start_does_not_wait_for_the_lookup(self) -> None:
"""The Tk thread returns at once while the lookup is still running."""
release = threading.Event()
def slow_lookup(desc: str) -> Candidates:
release.wait(5)
return [(desc, _nutrition())]
runner = LookupRunner(MagicMock(), MagicMock(), lambda: "slow")
began = time.perf_counter()
with patch.object(_gatelock_lookup, "lookup_candidates", slow_lookup):
runner.start("slow")
assert time.perf_counter() - began < 0.1
result = runner._result
assert result is not None
assert result.empty()
release.set()
assert result.get(timeout=5)[0][0] == "slow"
class TestGateLookup:
"""Step one of a submit: the gate fills the form from a lookup."""
def _lookup(self, gate: MealGate, found: Candidates) -> None:
"""Run ``_begin_lookup`` with a ready result, then collect it."""
ready: queue.Queue[Candidates] = queue.Queue()
ready.put(found)
gate._set_desc("apple")
with patch.object(_gatelock_lookup, "start_lookup", return_value=ready):
gate._begin_lookup("apple")
assert gate._vars.status.get() == g.BUSY
assert gate._lookup is not None
gate._lookup.poll()
def test_no_candidates(self, gate: MealGate) -> None:
"""No match asks for a manual value."""
self._lookup(gate, [])
assert gate._vars.status.get().startswith(g.ERROR)
def test_single_candidate(self, gate: MealGate) -> None:
"""A single match fills the fields and invites review."""
self._lookup(gate, [("apple", _nutrition(95, 100))])
assert gate._vars.status.get().startswith(g.OK)
assert g.TIMES not in gate._vars.status.get()
def test_multiple_candidates(self, gate: MealGate) -> None:
"""Several matches invite picking another."""
self._lookup(gate, [("a", _nutrition(95, 100)), ("b", _nutrition(120, 100))])
assert gate._vars.status.get().endswith(f" {g.TIMES}2")
def test_second_submit_keeps_busy_status(self, gate: MealGate) -> None:
"""A submit during a lookup neither restarts it nor touches the status."""
with patch.object(_gatelock_lookup, "start_lookup", return_value=queue.Queue()):
gate._begin_lookup("apple")
gate._set_status("other")
gate._begin_lookup("apple")
assert gate._vars.status.get() == "other"
def test_result_for_a_food_no_longer_typed_is_dropped(self, gate: MealGate) -> None:
"""A late result never fills the form for whatever the user moved on to."""
pending: queue.Queue[Candidates] = queue.Queue()
gate._set_desc("apple")
with patch.object(_gatelock_lookup, "start_lookup", return_value=pending):
gate._begin_lookup("apple")
gate._clear_inputs() # the meal was logged by hand; the form moved on
pending.put([("apple", _nutrition(95, 100))])
assert gate._lookup is not None
gate._lookup.poll()
assert gate._widgets.macros.kcal.get() == ""
assert gate._get_desc() == ""

View File

@ -1,9 +1,8 @@
"""Tests for the nutrition model and meal-building flow of MealGate.
"""Tests for the nutrition model, lookup, and meal-building flow of MealGate.
Covers :mod:`._gatelock_nutrition` (reference -> total maths, suggestions,
unit toggling) and :mod:`._gatelock_mealflow` (submit/record, the
dashboard, and multi-item meals). Lookup tests moved to
:mod:`test_gatelock_lookup`. The functional fake ``tk`` widgets and the
unit toggling) and :mod:`._gatelock_mealflow` (submit/lookup/record, the
dashboard, and multi-item meals). The functional fake ``tk`` widgets and the
``gate`` fixture live in ``conftest.py`` and are shared with
:mod:`test_gatelock`.
"""
@ -157,6 +156,41 @@ class TestSubmit:
submit.assert_called_once()
class TestLookup:
"""Step one: filling the form from a lookup."""
def test_no_candidates(self, gate: MealGate) -> None:
"""No match asks for a manual value."""
gate._set_desc("nonsense")
with patch.object(_gatelock_mealflow, "lookup_candidates", return_value=[]):
gate._begin_lookup("nonsense")
assert gate._vars.status.get().startswith(g.ERROR)
def test_single_candidate(self, gate: MealGate) -> None:
"""A single match fills the fields and invites review."""
with patch.object(
_gatelock_mealflow,
"lookup_candidates",
return_value=[("apple", _nutrition(95, 100))],
):
gate._begin_lookup("apple")
assert gate._vars.status.get().startswith(g.OK)
assert g.TIMES not in gate._vars.status.get()
def test_multiple_candidates(self, gate: MealGate) -> None:
"""Several matches invite picking another."""
with patch.object(
_gatelock_mealflow,
"lookup_candidates",
return_value=[
("a", _nutrition(95, 100)),
("b", _nutrition(120, 100)),
],
):
gate._begin_lookup("apple")
assert gate._vars.status.get().endswith(f"{g.TIMES}2")
class TestRecord:
"""Logging a meal and advancing the slot walk."""

View File

@ -1,155 +0,0 @@
"""The Kuchnia delivery cache: an outage falls back to the last fetched day.
Every on-disk write in these tests lands in the conftest-redirected tmp
state; the two ``pathlib`` patches below are the only fault injection.
"""
from __future__ import annotations
from contextlib import contextmanager
import dataclasses
from datetime import date
import json
from typing import TYPE_CHECKING
from unittest.mock import Mock, patch
from diet_guard import _constants
from diet_guard._kuchnia_config import record_import_day
from diet_guard._kuchnia_delivery_cache import load_delivery, save_delivery
from diet_guard._kuchnia_errors import KuchniaError
from diet_guard._kuchnia_import import refresh_delivery, refresh_delivery_once
from diet_guard._kuchnia_parse import Dish
if TYPE_CHECKING:
from collections.abc import Iterator
DAY = date(2026, 11, 27)
def _dish() -> Dish:
return Dish("Osobiste danie", 300.0, 10.0, 20.0, 2.0, 250.0, 1, "obiad")
def _write_cache(payload: object) -> None:
_constants.KUCHNIA_DELIVERY_CACHE_FILE.write_text(json.dumps(payload))
# --- load_delivery ----------------------------------------------------------
def test_save_then_load_round_trip() -> None:
save_delivery(DAY, [_dish()])
assert load_delivery(DAY) == [_dish()]
def test_load_missing_file() -> None:
assert load_delivery(DAY) == []
def test_load_wrong_day() -> None:
save_delivery(DAY, [_dish()])
assert load_delivery(date(2026, 11, 28)) == []
def test_load_malformed_json() -> None:
_constants.KUCHNIA_DELIVERY_CACHE_FILE.write_text("not json")
assert load_delivery(DAY) == []
def test_load_top_level_not_a_dict() -> None:
_write_cache([])
assert load_delivery(DAY) == []
def test_load_dishes_not_a_list() -> None:
_write_cache({"day": DAY.isoformat(), "dishes": "nope"})
assert load_delivery(DAY) == []
def test_load_skips_non_dict_items() -> None:
_write_cache(
{
"day": DAY.isoformat(),
"dishes": [42, dataclasses.asdict(_dish())],
}
)
assert load_delivery(DAY) == [_dish()]
def test_load_skips_unknown_key_items() -> None:
_write_cache(
{
"day": DAY.isoformat(),
"dishes": [{"bogus_key": 1}, dataclasses.asdict(_dish())],
}
)
assert load_delivery(DAY) == [_dish()]
def test_load_oserror_on_read() -> None:
save_delivery(DAY, [_dish()])
with patch("pathlib.Path.read_text", side_effect=OSError("io")):
assert load_delivery(DAY) == []
def test_save_oserror_on_write() -> None:
with patch("pathlib.Path.write_text", side_effect=OSError("io")):
save_delivery(DAY, [_dish()]) # must not raise
assert not _constants.KUCHNIA_DELIVERY_CACHE_FILE.exists()
# --- refresh_delivery -------------------------------------------------------
@contextmanager
def _patched_fetch(**mock_kwargs: object) -> Iterator[Mock]:
"""Patch the panel login and the dish walk; yield the ``fetch_dishes`` mock."""
with (
patch("diet_guard._kuchnia_import.PanelSession", return_value=Mock()),
patch("diet_guard._kuchnia_import.fetch_dishes", **mock_kwargs) as fetch,
):
yield fetch
def test_refresh_delivery_success_saves_cache() -> None:
with _patched_fetch(return_value=[_dish()]):
dishes, reason = refresh_delivery(DAY)
assert dishes == [_dish()]
assert reason is None
assert load_delivery(DAY) == [_dish()]
def test_refresh_delivery_outage_falls_back_to_cache() -> None:
save_delivery(DAY, [_dish()])
with _patched_fetch(side_effect=KuchniaError("down")):
dishes, reason = refresh_delivery(DAY)
assert dishes == [_dish()]
assert reason is None
def test_refresh_delivery_outage_without_cache_reports_reason() -> None:
with _patched_fetch(side_effect=KuchniaError("down")):
dishes, reason = refresh_delivery(DAY)
assert dishes == []
assert reason == "down"
def test_refresh_delivery_success_with_no_dishes_skips_cache() -> None:
with _patched_fetch(return_value=[]):
dishes, reason = refresh_delivery(DAY)
assert dishes == []
assert reason is None
assert load_delivery(DAY) == []
# --- refresh_delivery_once --------------------------------------------------
def test_refresh_delivery_once_after_import_day_reads_cache() -> None:
record_import_day(DAY.isoformat())
save_delivery(DAY, [_dish()])
with patch("diet_guard._kuchnia_import.fetch_dishes") as fetch:
dishes, reason = refresh_delivery_once(DAY)
fetch.assert_not_called()
assert dishes == [_dish()]
assert reason is None

View File

@ -40,10 +40,8 @@ from the phone; `FillAllFlow` stays as the tested plan logic.
undo plus the next resume would log the dish again.
- **The fetch is cached.** `KuchniaQueueService.refreshOnce` returns nothing
after the day's first clean fetch, so a slot falling due at 12:00 would never
see its dish. `KuchniaAutoLog` keeps the day's dishes in memory and in
`kuchnia_delivery.json` (offline first: a restart or a panel outage still has
them), and retries a failed or empty fetch at most every 10 minutes (a login
per try). The PC keeps the same file (`_kuchnia_delivery_cache.py`).
see its dish. `KuchniaAutoLog` keeps the day's dishes in memory and retries a
failed or empty fetch at most every 10 minutes (a login per try).
- Each logged dish shows as a row: restaurant glyph, name, kcal and macro
dots, a 48 dp undo. One publish per batch (`publishAfterLog`).
- Unverified: whether `deliveryMealId` is stable across fetches on the live

View File

@ -4,17 +4,17 @@ version = "1.0.0"
description = "Tkinter/systemd log-to-unlock meal gate with calorie/macro budget tracking"
requires-python = ">=3.14"
dependencies = [
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.2#subdirectory=gatelock",
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.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.4#subdirectory=freedays",
"kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit",
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays",
"kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.0#subdirectory=kuhy_credit",
"holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds",
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays",
"claude-agent-sdk==0.2.189",
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.6#subdirectory=sickdays",
"claude-agent-sdk==0.2.187",
"defusedxml==0.7.1",
"httpx==0.29.0",
"httpx==0.28.1",
"requests==2.34.2",
"rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.3#subdirectory=rtdb_relay",
"rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.1#subdirectory=rtdb_relay",
]
# Optional extras. The `mcp` group is ONLY needed by the MCP server
@ -26,7 +26,7 @@ dependencies = [
mcp = ["mcp==2.3.0"]
# Test-only: the property tests (test_claude_log.py) need it; same pin as
# requirements.txt.
dev = ["hypothesis==6.170.23"]
dev = ["hypothesis==6.170.17"]
# Without this, setuptools' flat-layout auto-discovery treats the Flutter
# app/ directory as a second top-level package and refuses to build.
@ -178,6 +178,10 @@ addopts = [
"--strict-markers",
"--strict-config",
"-ra",
"--cov=diet_guard",
"--cov-branch",
"--cov-report=term-missing",
"--cov-report=lcov",
]
filterwarnings = [
"error",
@ -203,6 +207,7 @@ omit = [
]
[tool.coverage.report]
fail_under = 100
show_missing = true
skip_covered = false
exclude_lines = [

View File

@ -1,17 +1,17 @@
# Diet Guard — runtime + development dependencies
# Runtime: tkinter/json/hmac/fcntl (stdlib) plus gatelock and requests below.
bandit==1.9.4
claude-agent-sdk==0.2.189
claude-agent-sdk==0.2.187
codespell==2.4.3
coverage==7.17.5
coverage==7.17.4
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
defusedxml==0.7.1
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.2#subdirectory=gatelock
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.0#subdirectory=gatelock
holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds
httpx==0.29.0
hypothesis==6.170.23
kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
httpx==0.28.1
hypothesis==6.170.17
kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.0#subdirectory=kuhy_credit
mcp==2.3.0
mypy==2.4.1
pre-commit==4.7.0
@ -24,6 +24,6 @@ pytest-sugar==1.1.1
pytest-xdist==3.8.0
pytest-xvfb==3.1.1
requests==2.34.2
rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.3#subdirectory=rtdb_relay
rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.1#subdirectory=rtdb_relay
ruff==0.17.6
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.6#subdirectory=sickdays