mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-28 13:09:05 +01:00
Compare commits
No commits in common. "main" and "v1.0.173" have entirely different histories.
62
.github/workflows/dependency-freshness.yml
vendored
Normal file
62
.github/workflows/dependency-freshness.yml
vendored
Normal file
@ -0,0 +1,62 @@
|
||||
name: dependency freshness
|
||||
|
||||
# Every dependency on its ecosystem's newest STABLE release, enforced on push
|
||||
# as well as at commit time. The local pre-commit hook only sees the manifests
|
||||
# in a commit and can be skipped entirely by a fresh clone that never ran
|
||||
# `pre-commit install`; this runs `--all` over the whole repo.
|
||||
#
|
||||
# `--strict` is CI-only. Offline the gate degrades to its cached answer and
|
||||
# passes, because `--no-verify` is banned locally and a hook that hard-failed
|
||||
# on a flaky connection would leave no way to commit. A runner is always
|
||||
# online, so here an undeterminable answer is a real failure.
|
||||
#
|
||||
# Expect this to go red for reasons this repo's commit did not cause: an
|
||||
# upstream release overnight is enough. That is the chosen behaviour -- the
|
||||
# alternative is a gate that only notices staleness when someone remembers to
|
||||
# look.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
dependency-freshness:
|
||||
name: dependencies on newest stable
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# The gate lives in the shared utils repo so every repo resolves the
|
||||
# same "latest stable" the same way. Checking it out beats vendoring a
|
||||
# copy, which is exactly how a gate and its survey start disagreeing.
|
||||
- name: Check out the shared gate
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: kuhyx/utils
|
||||
path: .utils
|
||||
|
||||
# "3.x", never a pinned minor: the Python target IS the interpreter the
|
||||
# gate runs under (registries/toolchain.python_installed), so a runner
|
||||
# held a release behind this machine reports a repo's `requires-python`
|
||||
# as excluding "latest" while the same check passes locally. flax-docs-mcp
|
||||
# hit exactly that -- `>=3.14` green here, red on a 3.13 runner.
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
|
||||
- name: Install the gate's two runtime dependencies
|
||||
run: python -m pip install --upgrade pyyaml packaging
|
||||
|
||||
- name: Cache registry lookups
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/dep-freshness
|
||||
key: dep-freshness-${{ hashFiles('**/pubspec.yaml', '**/pyproject.toml',
|
||||
'**/requirements*.txt', '**/package.json', '**/Cargo.toml', '**/go.mod') }}
|
||||
restore-keys: dep-freshness-
|
||||
|
||||
- name: Every dependency is on newest stable
|
||||
run: bash .utils/scripts/check_dependency_freshness.sh --all --strict
|
||||
33
.github/workflows/file-length.yml
vendored
Normal file
33
.github/workflows/file-length.yml
vendored
Normal 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
|
||||
20
.github/workflows/pre-commit.yml
vendored
20
.github/workflows/pre-commit.yml
vendored
@ -17,16 +17,22 @@ 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
|
||||
name: pre-commit (${{ matrix.group }})
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# The file-length and md-naming hooks delegate to the shared gates in
|
||||
# kuhyx/utils, which a runner does not have at $HOME/src/utils. Only
|
||||
# the rest group runs them.
|
||||
# The file-length, md-naming and dependency-freshness hooks delegate to
|
||||
# the shared gates in kuhyx/utils, which a runner does not have at
|
||||
# $HOME/src/utils. Only the rest group runs them.
|
||||
- name: Check out the shared gates
|
||||
if: matrix.group == 'rest'
|
||||
uses: actions/checkout@v4
|
||||
@ -53,9 +59,9 @@ jobs:
|
||||
# mypy and pylint bring their own hook environments, so they need only
|
||||
# pre-commit. The rest group's language: system patch-targets hook
|
||||
# imports diet_guard and every patched module (requests, gatelock,
|
||||
# crdt_sync, freedays, mcp, pydantic) -- so it keeps the full
|
||||
# requirements.txt. That install used to run in the one job, with plain
|
||||
# pip, for ~24 s.
|
||||
# crdt_sync, freedays, mcp, pydantic), and dependency-freshness needs
|
||||
# pyyaml and packaging -- so it keeps the full requirements.txt. That
|
||||
# install used to run in the one job, with plain pip, for ~24 s.
|
||||
- name: Install pre-commit and the system hooks' imports
|
||||
run: |
|
||||
if [[ "${{ matrix.group }}" == rest ]]; then
|
||||
|
||||
6
.github/workflows/release-apk.yml
vendored
6
.github/workflows/release-apk.yml
vendored
@ -60,7 +60,7 @@ jobs:
|
||||
|
||||
- uses: subosito/flutter-action@v2
|
||||
with:
|
||||
flutter-version: 3.50.1
|
||||
flutter-version: 3.47.9
|
||||
channel: stable
|
||||
cache: true
|
||||
|
||||
@ -108,9 +108,7 @@ jobs:
|
||||
run: |
|
||||
flutter build apk --release \
|
||||
--build-name="${{ steps.ver.outputs.semver }}" \
|
||||
--build-number="${{ steps.vc.outputs.code }}" \
|
||||
--dart-define=APP_BUILD="${{ steps.vc.outputs.code }}" \
|
||||
--dart-define=APP_VERSION="${{ steps.ver.outputs.semver }}"
|
||||
--build-number="${{ steps.vc.outputs.code }}"
|
||||
|
||||
# Fail closed. `findByName("release") ?: debug` silently falls back to
|
||||
# the debug key if key.properties is misplaced, producing a green build
|
||||
|
||||
@ -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,87 @@ 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.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.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
|
||||
# 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,103 +165,72 @@ 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
|
||||
name: CI mirror 5 (flutter test 1/6)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 0/6
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-2
|
||||
name: CI mirror 6 (flutter test 2/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 1/12
|
||||
name: CI mirror 6 (flutter test 2/6)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 1/6
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-3
|
||||
name: CI mirror 7 (flutter test 3/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 2/12
|
||||
name: CI mirror 7 (flutter test 3/6)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 2/6
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-4
|
||||
name: CI mirror 8 (flutter test 4/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 3/12
|
||||
name: CI mirror 8 (flutter test 4/6)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 3/6
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-5
|
||||
name: CI mirror 9 (flutter test 5/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 4/12
|
||||
name: CI mirror 9 (flutter test 5/6)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 4/6
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-6
|
||||
name: CI mirror 10 (flutter test 6/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 5/12
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-7
|
||||
name: CI mirror 11 (flutter test 7/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 6/12
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-8
|
||||
name: CI mirror 12 (flutter test 8/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 7/12
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-9
|
||||
name: CI mirror 13 (flutter test 9/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 8/12
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-10
|
||||
name: CI mirror 14 (flutter test 10/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 9/12
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-11
|
||||
name: CI mirror 15 (flutter test 11/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 10/12
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-12
|
||||
name: CI mirror 16 (flutter test 12/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 11/12
|
||||
name: CI mirror 10 (flutter test 6/6)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 5/6
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
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 +251,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
|
||||
@ -206,7 +281,7 @@ repos:
|
||||
# patch target statically so a stale path fails the commit instead.
|
||||
- id: patch-targets
|
||||
name: test patch targets resolve
|
||||
entry: python3 scripts/check_patch_targets.py diet_guard
|
||||
entry: python3 scripts/check_patch_targets.py
|
||||
language: system
|
||||
pass_filenames: false
|
||||
files: ^diet_guard/
|
||||
|
||||
14
AGENTS.md
14
AGENTS.md
@ -20,10 +20,9 @@ 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)
|
||||
- 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)
|
||||
- lint: `pre-commit run --all-files`
|
||||
- coverage: `python -m pytest -n auto -p no:sugar -q` (writes coverage.lcov)
|
||||
- coverage-gaps: `coverage-gaps coverage.lcov`
|
||||
|
||||
## Scheduling
|
||||
|
||||
@ -143,7 +142,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,
|
||||
@ -240,8 +238,10 @@ only); the CLI, gate and phone show both.
|
||||
|
||||
## Flutter/Dart AI rules
|
||||
|
||||
_Vendored from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md)
|
||||
via `~/.claude/CLAUDE.md`. Re-fetch periodically. Split across five files for the 250-line cap._
|
||||
_Vendored from [flutter/flutter
|
||||
docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md) via
|
||||
`~/.claude/CLAUDE.md` Flutter AI tooling setup. Re-fetch periodically. Split across five files to
|
||||
stay under the 250-line cap._
|
||||
|
||||
- [Language, style and architecture](docs/DOCS-flutter-rules-language.md)
|
||||
- [Architecture, lint rules, state and data](docs/DOCS-flutter-rules-state-and-data.md)
|
||||
|
||||
@ -1,30 +0,0 @@
|
||||
# Lock order
|
||||
|
||||
When several locks are due at once, gatelock shows the one with the highest
|
||||
rank first. Each lower lock waits, with no window, until every higher lock has
|
||||
been cleared. kuhy fixed this order on 2026-11-21:
|
||||
|
||||
| Order | Lock | gatelock app | Rank | Repo |
|
||||
|---|---|---|---|---|
|
||||
| 1 | workout | screen_locker | 200 | screen-locker |
|
||||
| 2 | book | book_guard | 175 | book-guard |
|
||||
| 3 | tutor | tutor_gate | 150 | tutor |
|
||||
| 4 | diet | diet_guard | 130 | diet-guard |
|
||||
| 5 | focus | focus_guard | 128 | focus-guard |
|
||||
| 6 | leetcode | leetcode_guard | 125 | leetcode-guard |
|
||||
|
||||
LeetCode goes last. Each rank is a literal in its own repo, not a
|
||||
`gatelock.RANK_*` constant, so changing one does not need a gatelock release.
|
||||
Every repo keeps a copy of this file, and its tests fail when its own number
|
||||
differs from its row here. Change the rank, this table and the copies in the
|
||||
other repos together.
|
||||
|
||||
Not in the table:
|
||||
|
||||
- The wake alarm (300) outranks everything.
|
||||
- The evening chain (`gatelock.evening_chain`) runs its rungs one at a time,
|
||||
in the order book, tutor, LeetCode. Its book rung locks at 150, which ties
|
||||
the tutor. Ranks only order locks that are due at the same moment.
|
||||
- All of these lock with a global grab and VT switching disabled, so no
|
||||
higher rank is ever a weaker lock. `gatelock/scripts/verify_all_lockers.py`
|
||||
checks this order on a private X server.
|
||||
@ -87,15 +87,6 @@ bash scripts/setup_mcp.sh # create the venv and install diet_guard[mcp]
|
||||
Then restart Claude Code in this repo and approve the project MCP server
|
||||
(registered in `.mcp.json`).
|
||||
|
||||
## Error reports
|
||||
|
||||
Every uncaught, thread or Tk callback error, and any freeze of the gate window
|
||||
over 1 s, goes to the shared app-errors spool as app `diet-guard-gate`
|
||||
through `gatelock.error_report` (`diet_guard/_errors.py`, installed by the
|
||||
CLI). The PC's `app-errors` timer turns each one into a ticket on the
|
||||
todoImplementer board (kuhyx/utils `DOCS-app-errors.md`). Nothing shows on
|
||||
screen. The Flutter app reports on its own, as `diet-guard`.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
|
||||
@ -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.8.2-all.zip
|
||||
|
||||
@ -3,9 +3,6 @@
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
|
||||
show AppErrors, AppErrorsConfig, AppErrorsRouteObserver, installAppErrors;
|
||||
import 'package:diet_guard_app/screens/log_meal_screen.dart';
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
import 'package:diet_guard_app/services/background_tasks.dart';
|
||||
@ -13,11 +10,8 @@ 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';
|
||||
@ -29,27 +23,9 @@ import 'package:material_ui/material_ui.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
// Every error and every wait over 1 s goes to the PC's app-errors ingest,
|
||||
// which files a board ticket (kuhyx/utils DOCS-app-errors.md). The release
|
||||
// build passes the versionCode and name as dart-defines (release-apk.yml).
|
||||
final errors = await installAppErrors(
|
||||
const AppErrorsConfig(
|
||||
app: 'diet-guard',
|
||||
repo: 'kuhyx/diet-guard',
|
||||
package: 'diet_guard_app',
|
||||
// 0 unless the release build passes --dart-define=APP_BUILD.
|
||||
// ignore: avoid_redundant_argument_values
|
||||
build: int.fromEnvironment('APP_BUILD'),
|
||||
version: String.fromEnvironment('APP_VERSION'),
|
||||
),
|
||||
);
|
||||
// Before anything that stamps an Hlc or syncs: until this resolves, the
|
||||
// device id falls back to the pre-migration role constant.
|
||||
final deviceId = await initSyncDeviceId();
|
||||
errors.connect(
|
||||
sink: () async => (await openFirebase())?.patchValues,
|
||||
deviceId: () async => deviceId,
|
||||
);
|
||||
await initSyncDeviceId();
|
||||
await LogStorageService.init();
|
||||
await AppSettingsService.init();
|
||||
await BudgetHistoryService.init();
|
||||
@ -58,8 +34,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();
|
||||
@ -81,25 +55,19 @@ Future<void> main() async {
|
||||
// coverage:ignore-start
|
||||
if (frameStatsEnabled) startFrameStats();
|
||||
// coverage:ignore-end
|
||||
runApp(DietGuardApp(errors: errors));
|
||||
runApp(const DietGuardApp());
|
||||
}
|
||||
|
||||
/// Root widget for the Diet Guard companion app.
|
||||
class DietGuardApp extends StatelessWidget {
|
||||
/// Creates the [DietGuardApp] root widget.
|
||||
const DietGuardApp({this.errors, super.key});
|
||||
|
||||
/// App-wide error reporting; null in widget tests.
|
||||
final AppErrors? errors;
|
||||
const DietGuardApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
title: 'Diet Guard',
|
||||
theme: buildAppTheme(),
|
||||
navigatorObservers: [
|
||||
if (errors case final errors?) AppErrorsRouteObserver(errors),
|
||||
],
|
||||
home: const LogMealScreen(),
|
||||
);
|
||||
}
|
||||
|
||||
@ -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
|
||||
|
||||
@ -9,7 +9,6 @@ library;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
|
||||
import 'package:diet_guard_app/models/day_status.dart';
|
||||
import 'package:diet_guard_app/models/period_average.dart';
|
||||
import 'package:diet_guard_app/screens/history_screen.dart';
|
||||
@ -154,7 +153,7 @@ class _CalendarScreenState extends State<CalendarScreen> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_loading) {
|
||||
return const Scaffold(body: WaitWatch.centered('calendar.load'));
|
||||
return const Scaffold(body: Center(child: CircularProgressIndicator()));
|
||||
}
|
||||
return Scaffold(
|
||||
appBar: AppBar(),
|
||||
|
||||
@ -8,7 +8,6 @@ library;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
|
||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/widgets/food_bank/fb_add_entry_dialog.dart';
|
||||
@ -184,7 +183,7 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
|
||||
],
|
||||
),
|
||||
body: all == null
|
||||
? const WaitWatch.centered('food_bank.load')
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: _displayed.isEmpty
|
||||
? Center(
|
||||
child: Icon(
|
||||
|
||||
@ -8,7 +8,6 @@ library;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
|
||||
import 'package:diet_guard_app/services/firebase_client.dart';
|
||||
import 'package:diet_guard_app/services/github_client_factory.dart';
|
||||
import 'package:diet_guard_app/services/sync_health.dart';
|
||||
@ -101,7 +100,7 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen>
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_loading) {
|
||||
return const Scaffold(body: WaitWatch.centered('github_mirror.load'));
|
||||
return const Scaffold(body: Center(child: CircularProgressIndicator()));
|
||||
}
|
||||
return Scaffold(
|
||||
// No title and no explanatory paragraph: the code glyph that opened this
|
||||
@ -162,7 +161,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',
|
||||
|
||||
@ -7,7 +7,6 @@ library;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/screens/edit_entry_screen.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
@ -190,7 +189,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
||||
],
|
||||
),
|
||||
body: allEntries == null
|
||||
? const WaitWatch.centered('history.load')
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: _displayed.isEmpty
|
||||
? Center(
|
||||
child: Icon(
|
||||
|
||||
@ -31,8 +31,7 @@ Nutrition nutritionFromControllers(MacroControllers macros, String source) =>
|
||||
source: source,
|
||||
);
|
||||
|
||||
/// The destination buttons in [LogMealScreen]'s app bar, after [leading]
|
||||
/// (the date picker).
|
||||
/// The five destination buttons in [LogMealScreen]'s app bar.
|
||||
///
|
||||
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap. Returned
|
||||
/// as a list to be spread into `AppBar.actions`, so the bar's structure and
|
||||
@ -43,31 +42,24 @@ List<Widget> logMealAppBarActions({
|
||||
required VoidCallback onCalendar,
|
||||
required VoidCallback onSettings,
|
||||
required VoidCallback onBody,
|
||||
List<Widget> leading = const [],
|
||||
}) => [
|
||||
...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,
|
||||
),
|
||||
|
||||
@ -12,6 +12,7 @@ import 'package:diet_guard_app/models/meal_schedule.dart';
|
||||
import 'package:diet_guard_app/models/slot.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/theme.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/pickers.dart';
|
||||
import 'package:diet_guard_app/widgets/slot_selector_row.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
@ -81,48 +82,45 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
|
||||
onLogDateChanged();
|
||||
}
|
||||
|
||||
/// The app bar's date actions: the picker (leftmost icon) and, once a date
|
||||
/// is picked, a way back to today. A picked date tints the picker gold with
|
||||
/// a small dot; no text is painted.
|
||||
List<Widget> buildDateActions(BuildContext context) {
|
||||
/// The "When" row: a "Log for later" button, or the picked date with a
|
||||
/// button to change it and one to clear back to today.
|
||||
Widget buildWhenRow(BuildContext context) {
|
||||
final date = _futureDate;
|
||||
final gold = Theme.of(context).colorScheme.primary;
|
||||
return [
|
||||
IconButton(
|
||||
// Not Icons.calendar_month: the bar's own "Calendar" nav button uses
|
||||
// that, and two on screen make `find.byIcon` ambiguous.
|
||||
icon: Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.edit_calendar,
|
||||
color: date == null ? null : gold,
|
||||
semanticLabel: date == null ? 'Log for later' : 'Change date',
|
||||
),
|
||||
if (date != null)
|
||||
Positioned(
|
||||
top: -1,
|
||||
right: -1,
|
||||
child: Container(
|
||||
key: const ValueKey('log-date-badge'),
|
||||
width: 8,
|
||||
height: 8,
|
||||
decoration: BoxDecoration(
|
||||
color: gold,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
return Row(
|
||||
children: [
|
||||
// Today is the default and shows nothing; only a picked date (data)
|
||||
// is shown, marked by the calendar glyph.
|
||||
if (date != null) ...[
|
||||
Icon(
|
||||
Icons.event,
|
||||
size: 18,
|
||||
color: scheme.onSurfaceVariant,
|
||||
semanticLabel: 'Log date',
|
||||
),
|
||||
const SizedBox(width: AppSpacing.xs),
|
||||
],
|
||||
Expanded(
|
||||
child: date == null ? const SizedBox() : Text(localDateKey(date)),
|
||||
),
|
||||
onPressed: _pickFutureDate,
|
||||
),
|
||||
if (date != null)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close, semanticLabel: 'Back to today'),
|
||||
onPressed: resetFutureLog,
|
||||
// Not Icons.calendar_month: the app bar's own "Calendar" nav button
|
||||
// already uses that, and a second one on screen makes
|
||||
// `find.byIcon` ambiguous for widget tests (and taps) alike.
|
||||
icon: Icon(
|
||||
Icons.date_range,
|
||||
size: 18,
|
||||
semanticLabel: date == null ? 'Log for later' : 'Change date',
|
||||
),
|
||||
onPressed: _pickFutureDate,
|
||||
),
|
||||
];
|
||||
if (date != null)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close, semanticLabel: 'Back to today'),
|
||||
onPressed: resetFutureLog,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// The slot row for a picked future date, else nothing.
|
||||
|
||||
@ -22,11 +22,6 @@ mixin LogMealLoggedMixin<T extends StatefulWidget>
|
||||
/// The rows under the action row, oldest first.
|
||||
List<LoggedMeal> loggedRows = const [];
|
||||
|
||||
/// The latest open-or-resume chain. Tests await it instead of guessing how
|
||||
/// long real file I/O takes (a fixed sleep flaked under load).
|
||||
@visibleForTesting
|
||||
Future<void> openChain = Future<void>.value();
|
||||
|
||||
/// Replaces the rows with [meals]: a new log retires the previous ones.
|
||||
void showLogged(List<LoggedMeal> meals) {
|
||||
if (mounted) setState(() => loggedRows = meals);
|
||||
@ -62,15 +57,12 @@ mixin LogMealLoggedMixin<T extends StatefulWidget>
|
||||
// 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) {
|
||||
startOpenChain();
|
||||
unawaited(onOpenedOrResumed());
|
||||
return;
|
||||
}
|
||||
super.didChangeAppLifecycleState(state);
|
||||
}
|
||||
|
||||
/// Starts [onOpenedOrResumed] and keeps its future in [openChain].
|
||||
void startOpenChain() => openChain = onOpenedOrResumed();
|
||||
|
||||
/// 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 {
|
||||
|
||||
@ -90,7 +90,7 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
unawaited(_onDescChanged());
|
||||
// Health first, so a device that stalled earlier says so before a tick.
|
||||
unawaited(refreshSyncHealth());
|
||||
startOpenChain();
|
||||
unawaited(onOpenedOrResumed());
|
||||
}
|
||||
|
||||
@override
|
||||
@ -168,8 +168,6 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
final due = dueMode;
|
||||
// Dimmed while Claude works, but never moved: nothing is added around it.
|
||||
final busy = claudeState == ClaudeButtonState.sending;
|
||||
// Hard rule: nothing sits under the keyboard, so the extras collapse.
|
||||
final typing = MediaQuery.viewInsetsOf(context).bottom > 0;
|
||||
final dim = busy || claudeState == ClaudeButtonState.queued;
|
||||
return Scaffold(
|
||||
appBar: due
|
||||
@ -181,7 +179,6 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
onCalendar: onOpenCalendar,
|
||||
onSettings: onOpenSettings,
|
||||
onBody: onOpenBody,
|
||||
leading: buildDateActions(context),
|
||||
),
|
||||
),
|
||||
body: SafeArea(
|
||||
@ -190,7 +187,11 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (!due) SyncHealthBanner(status: syncHealth),
|
||||
if (!due) ...[
|
||||
SyncHealthBanner(status: syncHealth),
|
||||
buildWhenRow(context),
|
||||
const SizedBox(height: AppSpacing.sm),
|
||||
],
|
||||
buildSlotRow(),
|
||||
Opacity(
|
||||
opacity: dim ? 0.5 : 1,
|
||||
@ -230,14 +231,13 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
onSend: sendToClaude,
|
||||
onLog: _onLogMeal,
|
||||
),
|
||||
if (!typing)
|
||||
for (final meal in loggedRows)
|
||||
LoggedMealRow(meal: meal, onUndo: () => undoLogged(meal)),
|
||||
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 && !typing) ...[
|
||||
if (_progress != null && !due) ...[
|
||||
const SizedBox(height: AppSpacing.sm),
|
||||
TodayProgressCard(progress: _progress!),
|
||||
],
|
||||
|
||||
@ -8,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/sync_attempt.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';
|
||||
@ -69,7 +68,6 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
||||
Future<void> autoSync() async {
|
||||
if (autoSyncing) return;
|
||||
autoSyncing = true;
|
||||
bool? landed; // null until the sync itself ran
|
||||
try {
|
||||
final settings = await SyncSettings.load();
|
||||
// Either backend counts. `isConfigured` means "has a GitHub token", so
|
||||
@ -89,19 +87,17 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
||||
return;
|
||||
}
|
||||
final client = createGitHubClient(settings, httpClient: syncHttpClient);
|
||||
landed = await attemptSync(() async {
|
||||
try {
|
||||
// Foreground only (this mixin is UI), and never prompts: fresh
|
||||
// Health Connect steps ride along in this tick's body.json.
|
||||
await refreshSteps();
|
||||
await runSync(await syncBackend(client));
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
});
|
||||
try {
|
||||
// Foreground only (this mixin is UI), and never prompts: fresh
|
||||
// Health Connect steps ride along in this tick's body.json.
|
||||
await refreshSteps();
|
||||
await runSync(await syncBackend(client));
|
||||
await SyncHealth.recordSuccess();
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
if (!mounted) return;
|
||||
// Outside attemptSync: a refresh error is no sync failure.
|
||||
if (landed) await refreshSlots();
|
||||
await refreshSlots();
|
||||
await refreshSyncHealth();
|
||||
} on Object catch (error, stackTrace) {
|
||||
// Best-effort, but never silent: this swallowed the reason a desktop
|
||||
@ -114,9 +110,7 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
// attemptSync already recorded the sync's own outcome; only a failure
|
||||
// before it (loading settings) is one here.
|
||||
if (landed == null) await SyncHealth.recordFailure();
|
||||
await SyncHealth.recordFailure();
|
||||
if (mounted) await refreshSyncHealth();
|
||||
} finally {
|
||||
autoSyncing = false;
|
||||
|
||||
@ -15,7 +15,6 @@
|
||||
/// encrypted either.
|
||||
library;
|
||||
|
||||
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
|
||||
import 'package:diet_guard_app/services/kuchnia_client.dart';
|
||||
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
|
||||
import 'package:diet_guard_app/services/kuchnia_import.dart';
|
||||
@ -189,12 +188,9 @@ class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
|
||||
IconButton.outlined(
|
||||
onPressed: canFetch && !_busy ? _fetch : null,
|
||||
icon: _busy
|
||||
? const WaitWatch(
|
||||
operation: 'kuchnia.sync',
|
||||
child: SizedBox.square(
|
||||
dimension: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
? const SizedBox.square(
|
||||
dimension: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(
|
||||
Icons.local_shipping_outlined,
|
||||
|
||||
@ -27,7 +27,6 @@ import 'package:diet_guard_app/widgets/meal_schedule_editor.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:kuhy_credit/kuhy_credit.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:permission_handler/permission_handler.dart';
|
||||
import 'package:sync_settings_ui/sync_settings_ui.dart';
|
||||
@ -51,7 +50,8 @@ class SettingsScreen extends StatefulWidget {
|
||||
this.firebaseFactory,
|
||||
});
|
||||
|
||||
/// HTTP client for the linked [GitHubMirrorScreen]; tests pass [MockClient].
|
||||
/// Injectable HTTP client for the linked [GitHubMirrorScreen]; tests pass
|
||||
/// a [MockClient].
|
||||
final http.Client? httpClient;
|
||||
|
||||
/// Injectable battery-optimization-exemption request; tests pass a fake.
|
||||
@ -71,10 +71,14 @@ class SettingsScreen extends StatefulWidget {
|
||||
/// Reads the stored Firebase account. Injected for the same reason as
|
||||
/// [googleFirebaseFactory]: the keystore is a platform channel.
|
||||
///
|
||||
/// Backed by [storedAccount], not [loadAccount]: the shared screen reads
|
||||
/// the account back right after a Google sign-in, and [loadAccount]'s
|
||||
/// desktop fallback throws on Android (seen on the phone as "Google sign-in
|
||||
/// failed"). See the keystore-only read in [firebase_backend.dart].
|
||||
/// Deliberately backed by [storedAccount], not [loadAccount]: the shared
|
||||
/// `SyncSettingsScreen` uses this single closure both to display the
|
||||
/// status and to read back the account right after a Google sign-in.
|
||||
/// [loadAccount]'s desktop-wrapper fallback resolves to `file:///` on
|
||||
/// Android and throws -- verified on the phone, where it turned a
|
||||
/// successful sign-in into "Google sign-in failed". `storedAccount` is the
|
||||
/// keystore-only read [firebase_backend.dart] documents for exactly this
|
||||
/// read-back case.
|
||||
final Future<FirebaseAccount?> Function()? accountLoader;
|
||||
|
||||
/// Persists the account. See [accountLoader].
|
||||
@ -237,10 +241,6 @@ class _SettingsScreenState extends State<SettingsScreen>
|
||||
const SizedBox(height: 16),
|
||||
Align(alignment: Alignment.centerLeft, child: _status),
|
||||
],
|
||||
const SizedBox(height: 24),
|
||||
const Divider(),
|
||||
const SizedBox(height: 8),
|
||||
const Align(alignment: Alignment.centerLeft, child: KuhyCredit()),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@ -15,7 +15,6 @@ import 'package:diet_guard_app/services/github_client_factory.dart';
|
||||
import 'package:diet_guard_app/services/kuchnia_credential_service.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_attempt.dart';
|
||||
import 'package:diet_guard_app/services/sync_device_id.dart';
|
||||
import 'package:diet_guard_app/services/sync_health.dart';
|
||||
import 'package:diet_guard_app/services/sync_service.dart';
|
||||
@ -91,14 +90,21 @@ Future<bool> backgroundSyncPush({http.Client? httpClient}) async {
|
||||
return true; // nothing to push; don't retry
|
||||
}
|
||||
final client = createGitHubClient(settings, httpClient: httpClient);
|
||||
// Never silent: attemptSync records the outcome, the only signal that a
|
||||
// background push failed. False -> WorkManager retries with backoff.
|
||||
final landed = await attemptSync(() async {
|
||||
try {
|
||||
await runSync(await syncBackend(client));
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
});
|
||||
return landed;
|
||||
try {
|
||||
await runSync(await syncBackend(client));
|
||||
await SyncHealth.recordSuccess();
|
||||
return true;
|
||||
} on Exception catch (error, stackTrace) {
|
||||
// Never silent: this is the only signal that a background push failed.
|
||||
log(
|
||||
'diet_guard background sync failed',
|
||||
level: 1000,
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
await SyncHealth.recordFailure();
|
||||
return false; // offline / transient error -> retry with backoff
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
|
||||
@ -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.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,42 +0,0 @@
|
||||
/// Runs one sync and records its outcome for the "not syncing" banner.
|
||||
///
|
||||
/// The banner said "Not syncing" on a phone whose sync looked fine, and the
|
||||
/// release build keeps no log that could say why (see `sync_health.dart`).
|
||||
/// So a failure here also goes to the board through the app-wide reporter:
|
||||
/// the next one files its own ticket with the exception that caused it.
|
||||
/// Inside a WorkManager isolate no reporter is installed, so a background
|
||||
/// failure is only recorded, not filed.
|
||||
///
|
||||
/// Only the sync itself is timed in: screen refreshes after a landed sync
|
||||
/// run outside, so their errors never mark a working sync as failed.
|
||||
library;
|
||||
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show AppErrors;
|
||||
import 'package:diet_guard_app/services/sync_health.dart';
|
||||
|
||||
/// Runs [sync]; records success, or failure plus a `sync.failed` report.
|
||||
///
|
||||
/// Returns whether the sync landed. Never throws.
|
||||
Future<bool> attemptSync(Future<void> Function() sync) async {
|
||||
try {
|
||||
await sync();
|
||||
} on Object catch (error, stackTrace) {
|
||||
log(
|
||||
'diet_guard sync failed',
|
||||
level: 1000,
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
AppErrors.instance?.reporter.report(
|
||||
'sync.failed',
|
||||
error,
|
||||
stack: stackTrace,
|
||||
);
|
||||
await SyncHealth.recordFailure();
|
||||
return false;
|
||||
}
|
||||
await SyncHealth.recordSuccess();
|
||||
return true;
|
||||
}
|
||||
@ -8,7 +8,6 @@
|
||||
/// send or log.
|
||||
library;
|
||||
|
||||
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
@ -128,13 +127,10 @@ class MealActionRow extends StatelessWidget {
|
||||
);
|
||||
|
||||
Widget _claudeFace() => switch (claude) {
|
||||
ClaudeButtonState.sending => const WaitWatch(
|
||||
operation: 'claude.estimate',
|
||||
child: SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: CircularProgressIndicator(strokeWidth: 3),
|
||||
),
|
||||
ClaudeButtonState.sending => const SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: CircularProgressIndicator(strokeWidth: 3),
|
||||
),
|
||||
ClaudeButtonState.queued => const Icon(
|
||||
Icons.hourglass_top,
|
||||
|
||||
@ -123,7 +123,6 @@ class MealTimeDropdown extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'Time',
|
||||
icon: const Icon(
|
||||
Icons.schedule,
|
||||
semanticLabel: 'Type or pick an exact time',
|
||||
|
||||
@ -5,10 +5,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: android_file_picker
|
||||
sha256: ec3cf2a2c7a9b2bd56747e85f80efdd994e563049dfb0981a23903acfdd58cb5
|
||||
sha256: "04c1306eda42c23ecbf449c909f4fa05c5e66fc48cf5f994d8d08b9d45e5396b"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.2.0"
|
||||
version: "2.1.5"
|
||||
archive:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -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.8.2"
|
||||
resolved-ref: "1962d303336dfe260850466b8ee841033b9ad1ce"
|
||||
url: "https://github.com/kuhyx/utils"
|
||||
source: git
|
||||
version: "0.9.2"
|
||||
version: "0.8.2"
|
||||
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.2"
|
||||
resolved-ref: eef7af4c86837ee82891493587ff3456297e5dea
|
||||
url: "https://github.com/kuhyx/utils"
|
||||
source: git
|
||||
version: "0.2.4"
|
||||
version: "0.2.2"
|
||||
dbus:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -280,10 +280,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_picker
|
||||
sha256: "5b99250437a4d34ee2cdc0686924452103540eaa1c248094b63f07f9d7216f6c"
|
||||
sha256: "079dc46b753abbddb7f77cd87e6ed9ecc62902580707514568321bdf8e050a86"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "13.4.1"
|
||||
version: "13.3.3"
|
||||
file_picker_darwin:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -296,18 +296,18 @@ 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:
|
||||
name: file_picker_platform_interface
|
||||
sha256: a2ef71c4628f92a4471d424576e3bf7042b40a2683c9f9a0e3033a7fc7f7763c
|
||||
sha256: "336e7168306834a2b68e6168ed768e00d3fabeac23154d5793e277ca9f97cf20"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.3.0"
|
||||
version: "4.2.0"
|
||||
file_picker_web:
|
||||
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: fac349e7361f80591a0cedff03548f807282c9faee9fc6192763166e5f81def2
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "23.0.4"
|
||||
version: "23.0.2"
|
||||
flutter_local_notifications_linux:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -524,11 +524,11 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: github_device_auth
|
||||
ref: "github_device_auth-v0.5.1"
|
||||
resolved-ref: da1d7c0692e2e402ae4944f2425b36a55ad43e9c
|
||||
ref: "github_device_auth-v0.5.0"
|
||||
resolved-ref: "0ef5461805e8f574de5174c940775e5245d675b3"
|
||||
url: "https://github.com/kuhyx/utils"
|
||||
source: git
|
||||
version: "0.5.1"
|
||||
version: "0.5.0"
|
||||
google_account_token:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@ -542,10 +542,10 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: health
|
||||
sha256: "683d15fdde49a942bacce871faf3090bda3c1f5dad995725337aeb1dfd348e6d"
|
||||
sha256: "8dd9625c9c26379a5753ad24c33af1d3dc5ce1f36f19c03e17c676c2f8fdbb80"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "14.0.0"
|
||||
version: "13.3.2"
|
||||
hooks:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -682,15 +682,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.12.0"
|
||||
kuhy_credit:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "kuhy_credit/flutter"
|
||||
ref: "kuhy-credit-v0.3.2"
|
||||
resolved-ref: adeb40f68e1d6c701da43e396fc46bffa3ef10c7
|
||||
url: "https://github.com/kuhyx/utils"
|
||||
source: git
|
||||
version: "0.3.2"
|
||||
leak_tracker:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -751,10 +742,10 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: material_ui
|
||||
sha256: a6b19012df437a356cbc01f8ea22a105e07194c47c9a6009da0032a0ce35c4ab
|
||||
sha256: "474c135fd46b56ff1d35ca982155e8863d28fbc6464d1192acf4ee53a738680e"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.11.1"
|
||||
version: "1.11.0"
|
||||
meta:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -787,22 +778,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.2.0"
|
||||
package_info_plus:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: package_info_plus
|
||||
sha256: "73ef2cd5c11a7548f9b7f6fc2a4f6113de2e64aa2a70de63feede95548822908"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "10.2.2"
|
||||
package_info_plus_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: package_info_plus_platform_interface
|
||||
sha256: db762cb2f4f25ee60fb6359773861b0f199e00b90d237bd85a76a1e806b46ef4
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.1.0"
|
||||
path:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@ -1076,11 +1051,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.2"
|
||||
resolved-ref: "3225af8365481677d61a8cabec0c0ad4d0407567"
|
||||
url: "https://github.com/kuhyx/utils"
|
||||
source: git
|
||||
version: "0.8.6"
|
||||
version: "0.8.2"
|
||||
synchronized:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@ -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.173+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.8.2
|
||||
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.2
|
||||
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.2
|
||||
flutter_secure_storage: 11.2.0
|
||||
|
||||
# One-tap sign-in for the sync account. App-side only: crdt_sync stays pure
|
||||
@ -40,7 +40,7 @@ dependencies:
|
||||
github_device_auth:
|
||||
git:
|
||||
url: https://github.com/kuhyx/utils
|
||||
ref: github_device_auth-v0.5.1
|
||||
ref: github_device_auth-v0.5.0
|
||||
path: github_device_auth
|
||||
# One-tap Google ID token via the framework AccountManager chooser (FOSS).
|
||||
google_account_token:
|
||||
@ -48,17 +48,12 @@ dependencies:
|
||||
url: https://github.com/kuhyx/utils
|
||||
ref: google_account_token-v0.1.0
|
||||
path: google_account_token
|
||||
health: 14.0.0
|
||||
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
|
||||
kuhy_credit:
|
||||
git:
|
||||
url: https://github.com/kuhyx/utils
|
||||
ref: kuhy-credit-v0.3.2
|
||||
path: kuhy_credit/flutter
|
||||
material_ui: 1.11.1
|
||||
material_ui: 1.11.0
|
||||
path: 1.9.1
|
||||
path_provider: 2.1.6
|
||||
permission_handler: 13.0.2
|
||||
@ -71,7 +66,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.2
|
||||
path: sync_settings_ui
|
||||
url_launcher: 6.3.3
|
||||
uuid: 4.6.0
|
||||
|
||||
@ -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);
|
||||
}
|
||||
});
|
||||
}
|
||||
@ -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].
|
||||
|
||||
@ -65,20 +65,13 @@ void main() {
|
||||
// GitHubMirrorScreen loads its settings via a fire-and-forget Future in
|
||||
// initState that Flutter's frame scheduler does not track -- same pitfall
|
||||
// as HistoryScreen/LogMealScreen.
|
||||
// [until]: keep pumping (max 5 s) until it is found -- a sync tick's real
|
||||
// I/O outlasts the fixed 200 ms on a loaded machine.
|
||||
Future<void> settle(WidgetTester tester, {Finder? until}) async {
|
||||
Future<void> settle(WidgetTester tester) async {
|
||||
tester.view.physicalSize = const Size(800, 1400);
|
||||
tester.view.devicePixelRatio = 1.0;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
final deadline = DateTime.now().add(const Duration(seconds: 5));
|
||||
do {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
await tester.pumpAndSettle();
|
||||
} while (until != null &&
|
||||
until.evaluate().isEmpty &&
|
||||
DateTime.now().isBefore(deadline));
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
/// Drains the device flow's real `Future.delayed` poll (GitHubDeviceAuth
|
||||
@ -174,7 +167,7 @@ void main() {
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(controlByLabel('Sync now'));
|
||||
await settle(tester, until: cueLabelled('Synced.'));
|
||||
await settle(tester);
|
||||
|
||||
expect(cueLabelled('Synced.'), findsOneWidget);
|
||||
});
|
||||
@ -204,7 +197,7 @@ void main() {
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(controlByLabel('Sync now'));
|
||||
await settle(tester, until: cueLabelled('Synced.'));
|
||||
await settle(tester);
|
||||
|
||||
expect(cueLabelled('Synced.'), findsOneWidget);
|
||||
final status = await SyncHealth.read();
|
||||
@ -235,7 +228,7 @@ void main() {
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(controlByLabel('Sync now'));
|
||||
await settle(tester, until: cueOfKind(CueKind.error));
|
||||
await settle(tester);
|
||||
|
||||
expect(cueOfKind(CueKind.error), findsOneWidget);
|
||||
});
|
||||
|
||||
@ -47,7 +47,7 @@ void main() {
|
||||
|
||||
Future<void> open(WidgetTester tester) async {
|
||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||
await settleOpen(tester);
|
||||
await settle(tester);
|
||||
}
|
||||
|
||||
testWidgets('opening in due mode logs the due dishes with no tap', (
|
||||
@ -72,11 +72,7 @@ void main() {
|
||||
await tester.runAsync(() async {
|
||||
await open(tester);
|
||||
await tester.tap(byIconLabel('Undo').first);
|
||||
await settleUntil(
|
||||
tester,
|
||||
() async =>
|
||||
(await LogStorageService.instance.todayEntries()).length == 1,
|
||||
);
|
||||
await settle(tester);
|
||||
expect(find.byIcon(Icons.restaurant), findsOneWidget);
|
||||
var live = await LogStorageService.instance.todayEntries();
|
||||
expect(live.map((e) => e.desc), ['Danie 2']);
|
||||
@ -134,7 +130,7 @@ void main() {
|
||||
(state as WidgetsBindingObserver).didChangeAppLifecycleState(
|
||||
AppLifecycleState.resumed,
|
||||
);
|
||||
await settleOpen(tester);
|
||||
await settle(tester);
|
||||
|
||||
final entries = await LogStorageService.instance.todayEntries();
|
||||
expect(entries.map((e) => e.desc), ['Danie 1', 'Danie 2']);
|
||||
|
||||
@ -38,7 +38,7 @@ void main() {
|
||||
|
||||
Future<void> open(WidgetTester tester) async {
|
||||
await tester.pumpWidget(MaterialApp(home: LogMealScreen(relay: relay)));
|
||||
await settleOpen(tester);
|
||||
await settle(tester);
|
||||
}
|
||||
|
||||
testWidgets('the request id is a ULID and the mode follows due mode', (
|
||||
@ -75,12 +75,7 @@ void main() {
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(controlByLabel('Log meal'));
|
||||
await settleUntil(
|
||||
tester,
|
||||
() async =>
|
||||
relay.cancelled.isNotEmpty &&
|
||||
byIconLabel('Ask Claude').evaluate().isNotEmpty,
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
expect(relay.cancelled, [relay.sent.single.requestId]);
|
||||
expect(byIconLabel('Ask Claude'), findsOneWidget);
|
||||
@ -93,12 +88,7 @@ void main() {
|
||||
_claudeEntry(claudeEntryId(relay.sent.single.requestId)),
|
||||
),
|
||||
);
|
||||
await settleUntil(
|
||||
tester,
|
||||
() async =>
|
||||
(await LogStorageService.instance.todayEntries()).length ==
|
||||
(claimed ? 2 : 1),
|
||||
);
|
||||
await settle(tester);
|
||||
final live = await LogStorageService.instance.todayEntries();
|
||||
expect(live, hasLength(claimed ? 2 : 1));
|
||||
});
|
||||
|
||||
@ -54,7 +54,7 @@ void main() {
|
||||
await open(tester);
|
||||
expect(find.byType(AppBar), findsNothing);
|
||||
expect(find.byType(SyncHealthBanner), findsNothing);
|
||||
expect(find.byIcon(Icons.edit_calendar), 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.
|
||||
@ -71,7 +71,7 @@ void main() {
|
||||
await tester.runAsync(() async {
|
||||
await open(tester);
|
||||
expect(find.byType(AppBar), findsOneWidget);
|
||||
expect(find.byIcon(Icons.edit_calendar), 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);
|
||||
|
||||
@ -122,9 +122,7 @@ void main() {
|
||||
),
|
||||
);
|
||||
await settle(tester);
|
||||
// The logged row collapses while the keyboard is up (no cover by
|
||||
// keyboard); log_meal_keyboard_test.dart covers it coming back.
|
||||
expect(find.byIcon(Icons.undo), findsNothing);
|
||||
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);
|
||||
|
||||
@ -1,170 +0,0 @@
|
||||
/// kuhy's hard rule, 2026-11-17: NO COVER BY KEYBOARD EVER. With the keyboard
|
||||
/// open the today-progress card and the logged rows collapse, so the field,
|
||||
/// suggestions, macro fields and action row all sit above it with no scroll.
|
||||
/// Also the date picker's move into the app bar and its picked-date tint.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/screens/log_meal_screen.dart';
|
||||
import 'package:diet_guard_app/widgets/logged_meal_row.dart';
|
||||
import 'package:diet_guard_app/widgets/meal_action_row.dart';
|
||||
import 'package:diet_guard_app/widgets/today_progress_card.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';
|
||||
|
||||
const double _dpr = 2.625;
|
||||
|
||||
void _phone(WidgetTester tester, {required double keyboardPx}) {
|
||||
tester.view
|
||||
..physicalSize = const Size(1080, 2400)
|
||||
..devicePixelRatio = _dpr
|
||||
..padding = const FakeViewPadding(top: 132, bottom: 63)
|
||||
..viewPadding = const FakeViewPadding(top: 132, bottom: 63)
|
||||
..viewInsets = FakeViewPadding(bottom: keyboardPx);
|
||||
}
|
||||
|
||||
double _maxScroll(WidgetTester tester) => tester
|
||||
.state<ScrollableState>(
|
||||
find
|
||||
.descendant(
|
||||
of: find.byType(SingleChildScrollView),
|
||||
matching: find.byType(Scrollable),
|
||||
)
|
||||
.first,
|
||||
)
|
||||
.position
|
||||
.maxScrollExtent;
|
||||
|
||||
/// Every widget the form shows ends above the keyboard, the action row is
|
||||
/// tappable, and nothing scrolls.
|
||||
void _expectAboveKeyboard(WidgetTester tester, double keyboardPx) {
|
||||
final keyboardTop = (2400 - keyboardPx) / _dpr;
|
||||
for (final type in <Type>[
|
||||
TextField,
|
||||
MealActionRow,
|
||||
LoggedMealRow,
|
||||
TodayProgressCard,
|
||||
]) {
|
||||
for (final e in find.byType(type).evaluate()) {
|
||||
final box = e.renderObject! as RenderBox;
|
||||
final bottom = box.localToGlobal(Offset(0, box.size.height)).dy;
|
||||
expect(bottom, lessThanOrEqualTo(keyboardTop), reason: '$type covered');
|
||||
}
|
||||
}
|
||||
expect(controlByLabel('Log meal').hitTestable(), findsOneWidget);
|
||||
expect(controlByLabel('Photo').hitTestable(), findsOneWidget);
|
||||
expect(_maxScroll(tester), 0, reason: 'the form scrolls');
|
||||
}
|
||||
|
||||
void main() {
|
||||
late Future<void> Function() restore;
|
||||
setUp(() async => restore = await isolateLogScreenState());
|
||||
tearDown(() => restore());
|
||||
|
||||
Future<void> open(WidgetTester tester) async {
|
||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||
await settle(tester);
|
||||
}
|
||||
|
||||
Future<void> fillWorstCase(WidgetTester tester, String name) async {
|
||||
await tester.enterText(find.byType(TextField).at(0), name);
|
||||
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);
|
||||
}
|
||||
|
||||
for (final kb in [840.0, 1050.0]) {
|
||||
testWidgets('normal mode, keyboard $kb px: nothing under it', (
|
||||
tester,
|
||||
) async {
|
||||
addTearDown(tester.view.reset);
|
||||
_phone(tester, keyboardPx: 0);
|
||||
await tester.runAsync(() async {
|
||||
await open(tester);
|
||||
await fillWorstCase(tester, 'kurczak z ryzem');
|
||||
await tester.tap(controlByLabel('Log meal'));
|
||||
await settle(tester);
|
||||
// Keyboard closed: the card and the logged row are both there.
|
||||
expect(find.byType(TodayProgressCard), findsOneWidget);
|
||||
expect(find.byType(LoggedMealRow), findsOneWidget);
|
||||
|
||||
_phone(tester, keyboardPx: kb);
|
||||
await fillWorstCase(tester, 'kurczak');
|
||||
expect(find.byType(TodayProgressCard), findsNothing);
|
||||
expect(find.byType(LoggedMealRow), findsNothing);
|
||||
_expectAboveKeyboard(tester, kb);
|
||||
|
||||
_phone(tester, keyboardPx: 0);
|
||||
await settle(tester);
|
||||
expect(find.byType(LoggedMealRow), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('due mode, keyboard $kb px: nothing under it', (tester) async {
|
||||
addTearDown(tester.view.reset);
|
||||
_phone(tester, keyboardPx: kb);
|
||||
pinLogMealClock(13);
|
||||
await tester.runAsync(() async {
|
||||
await open(tester);
|
||||
await fillWorstCase(tester, 'kurczak z ryzem');
|
||||
expect(find.byType(AppBar), findsNothing);
|
||||
_expectAboveKeyboard(tester, kb);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
group('date picker in the app bar', () {
|
||||
Color tint(WidgetTester tester) {
|
||||
final icon = find.byIcon(Icons.edit_calendar);
|
||||
return tester.widget<Icon>(icon).color ??
|
||||
IconTheme.of(tester.element(icon)).color!;
|
||||
}
|
||||
|
||||
testWidgets('leftmost action; no row above the field', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await open(tester);
|
||||
final date = find.byIcon(Icons.edit_calendar);
|
||||
expect(
|
||||
find.descendant(of: find.byType(AppBar), matching: date),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.byIcon(Icons.date_range), findsNothing);
|
||||
final x = tester.getCenter(date).dx;
|
||||
for (final other in [Icons.monitor_weight, Icons.settings]) {
|
||||
expect(x, lessThan(tester.getCenter(find.byIcon(other)).dx));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('a picked future date tints the icon gold with a dot', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await open(tester);
|
||||
final gold = Theme.of(
|
||||
tester.element(find.byType(AppBar)),
|
||||
).colorScheme.primary;
|
||||
const badge = ValueKey<String>('log-date-badge');
|
||||
expect(tint(tester), isNot(gold));
|
||||
expect(find.byKey(badge), findsNothing);
|
||||
|
||||
await tester.tap(controlByLabel('Log for later'));
|
||||
await settle(tester);
|
||||
await tester.tap(controlByLabel('Confirm'));
|
||||
await settle(tester);
|
||||
expect(tint(tester), gold);
|
||||
expect(find.byKey(badge), findsOneWidget);
|
||||
final dates = find.textContaining(RegExp(r'^\d{4}-\d{2}-\d{2}$'));
|
||||
expect(dates, findsNothing, reason: 'no painted date');
|
||||
|
||||
await tester.tap(controlByLabel('Back to today'));
|
||||
await settle(tester);
|
||||
expect(find.byKey(badge), findsNothing);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -68,7 +68,7 @@ void main() {
|
||||
await settle(tester);
|
||||
|
||||
final tomorrowKey = localDateKey(tomorrow());
|
||||
expect(byIconLabel('Change date'), findsOneWidget);
|
||||
expect(find.text(tomorrowKey), findsOneWidget);
|
||||
|
||||
final firstSlot = daySlots(MealScheduleService.current).first;
|
||||
await tester.tap(find.text(slotLabel(firstSlot)));
|
||||
@ -91,7 +91,7 @@ void main() {
|
||||
expect(future.time.startsWith(tomorrowKey), isTrue);
|
||||
|
||||
// Back to logging for today.
|
||||
expect(byIconLabel('Change date'), findsNothing);
|
||||
expect(find.text(tomorrowKey), findsNothing);
|
||||
expect(controlByLabel('Log for later'), findsOneWidget);
|
||||
});
|
||||
},
|
||||
@ -133,12 +133,12 @@ void main() {
|
||||
await settle(tester);
|
||||
await tester.tap(controlByLabel('Confirm'));
|
||||
await settle(tester);
|
||||
expect(byIconLabel('Change date'), findsOneWidget);
|
||||
expect(find.text(localDateKey(tomorrow())), findsOneWidget);
|
||||
|
||||
await tester.tap(controlByLabel('Back to today'));
|
||||
await settle(tester);
|
||||
|
||||
expect(byIconLabel('Change date'), findsNothing);
|
||||
expect(find.text(localDateKey(tomorrow())), findsNothing);
|
||||
expect(controlByLabel('Log for later'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
@ -4,8 +4,6 @@ library;
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
|
||||
import 'package:diet_guard_app/screens/log_meal_logged_mixin.dart';
|
||||
import 'package:diet_guard_app/screens/log_meal_screen.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';
|
||||
@ -53,28 +51,3 @@ Future<void> settle(WidgetTester tester) async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
/// Waits for the screen's open-or-resume chain (sync, slots, catering
|
||||
/// auto-log) to finish, then [settle]s.
|
||||
Future<void> settleOpen(WidgetTester tester) async {
|
||||
final state = tester.state(find.byType(LogMealScreen));
|
||||
await (state as LogMealLoggedMixin).openChain;
|
||||
await settle(tester);
|
||||
}
|
||||
|
||||
/// [settle]s, then keeps pumping until [done] holds or [timeout] passes.
|
||||
///
|
||||
/// For chains a tap starts and nothing exposes: real file I/O outlasts the
|
||||
/// fixed sleep in [settle] when the machine is loaded.
|
||||
Future<void> settleUntil(
|
||||
WidgetTester tester,
|
||||
Future<bool> Function() done, {
|
||||
Duration timeout = const Duration(seconds: 5),
|
||||
}) async {
|
||||
final deadline = DateTime.now().add(timeout);
|
||||
await settle(tester);
|
||||
while (!await done() && DateTime.now().isBefore(deadline)) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 50));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
}
|
||||
|
||||
@ -10,7 +10,6 @@ import 'package:diet_guard_app/services/firebase_backend.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||
import 'package:kuhy_credit/kuhy_credit.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:permission_handler/permission_handler.dart';
|
||||
@ -225,17 +224,4 @@ void main() {
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('shows the KuhyCredit logo at the bottom', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
|
||||
await settle(tester);
|
||||
|
||||
// Scroll to the bottom where KuhyCredit is placed.
|
||||
await tester.ensureVisible(find.byType(KuhyCredit, skipOffstage: false));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byType(KuhyCredit, skipOffstage: false), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@ -115,10 +115,13 @@ void main() {
|
||||
});
|
||||
|
||||
test('uses the real clock when now is omitted', () async {
|
||||
// Just exercises the `now ?? DateTime.now()` branch. Whether anything is
|
||||
// shown or cancelled depends on the wall clock (nothing is due after the
|
||||
// last slot's cutoff), so only completion is asserted.
|
||||
await expectLater(checkAndNotify(), completes);
|
||||
// Just exercises the `now ?? DateTime.now()` branch without asserting
|
||||
// on specific slots (which depend on the actual time the test runs).
|
||||
await checkAndNotify();
|
||||
expect(
|
||||
notificationLog.where((c) => c.method == 'show' || c.method == 'cancel'),
|
||||
isNotEmpty,
|
||||
);
|
||||
});
|
||||
|
||||
test('still syncs when nothing is due', () async {
|
||||
|
||||
@ -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, '');
|
||||
});
|
||||
}
|
||||
@ -1,58 +0,0 @@
|
||||
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
|
||||
show AppErrors, AppErrorsConfig, ErrorQueue;
|
||||
import 'package:diet_guard_app/services/sync_attempt.dart';
|
||||
import 'package:diet_guard_app/services/sync_health.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
const _config = AppErrorsConfig(
|
||||
app: 'diet-guard',
|
||||
repo: 'kuhyx/diet-guard',
|
||||
package: 'diet_guard_app',
|
||||
);
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
late ErrorQueue queue;
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
queue = await ErrorQueue.open(await SharedPreferences.getInstance());
|
||||
AppErrors.instance = AppErrors.forTest(_config, queue);
|
||||
});
|
||||
|
||||
tearDown(() => AppErrors.instance = null);
|
||||
|
||||
test('a sync that lands records success and reports nothing', () async {
|
||||
expect(await attemptSync(() async {}), isTrue);
|
||||
final status = await SyncHealth.read();
|
||||
expect(status.lastSuccess, isNotNull);
|
||||
expect(status.failureKind, isNull);
|
||||
expect(queue.entries, isEmpty);
|
||||
});
|
||||
|
||||
test('a failed sync records the failure and files its cause', () async {
|
||||
final ok = await attemptSync(() async => throw StateError('locked'));
|
||||
expect(ok, isFalse);
|
||||
final status = await SyncHealth.read();
|
||||
expect(status.failureKind, SyncFailureKind.failed);
|
||||
final entry = queue.entries.single;
|
||||
expect(entry.kind, 'sync.failed');
|
||||
expect(entry.error, contains('locked'));
|
||||
});
|
||||
|
||||
test('without installed reporting a failure is still recorded', () async {
|
||||
AppErrors.instance = null;
|
||||
expect(await attemptSync(() async => throw StateError('x')), isFalse);
|
||||
expect((await SyncHealth.read()).failureKind, SyncFailureKind.failed);
|
||||
});
|
||||
|
||||
test('a later success clears the failure (the banner goes away)', () async {
|
||||
await attemptSync(() async => throw StateError('offline'));
|
||||
await attemptSync(() async {});
|
||||
final status = await SyncHealth.read();
|
||||
expect(status.failureKind, isNull);
|
||||
expect(status.message, isNull);
|
||||
});
|
||||
}
|
||||
@ -18,6 +18,7 @@
|
||||
|
||||
<meta charset="UTF-8">
|
||||
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
|
||||
<meta name="description" content="A new Flutter project.">
|
||||
|
||||
<!-- iOS meta tags & icons -->
|
||||
<meta name="mobile-web-app-capable" content="yes">
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
"display": "standalone",
|
||||
"background_color": "#0175C2",
|
||||
"theme_color": "#0175C2",
|
||||
"description": "A new Flutter project.",
|
||||
"orientation": "portrait-primary",
|
||||
"prefer_related_applications": false,
|
||||
"icons": [
|
||||
|
||||
@ -2,4 +2,15 @@
|
||||
# entries are predicates: they clear themselves when the blocker moves, so
|
||||
# they carry no `expires`; everything else is discretionary and expires.
|
||||
|
||||
exceptions: []
|
||||
exceptions:
|
||||
- ecosystem: toolchain
|
||||
package: flutter
|
||||
pinned: "3.47.9"
|
||||
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
|
||||
|
||||
@ -6,10 +6,12 @@ Examples:
|
||||
python -m diet_guard ate "two slices of pizza" --grams 240
|
||||
python -m diet_guard ate "protein shake" --kcal 180
|
||||
python -m diet_guard status
|
||||
python -m diet_guard averages
|
||||
python -m diet_guard undo
|
||||
|
||||
``status`` and each log print the calories left of the day's budget (kept
|
||||
outside the repo) and which meal slots still need logging.
|
||||
The daily budget lives outside the repo (so it is never exposed online) but is
|
||||
shown freely on this machine: ``status`` and each log print how many calories
|
||||
are left of the day's budget, plus which meal slots still need logging.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@ -17,7 +19,6 @@ from __future__ import annotations
|
||||
import sys
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from diet_guard import _errors
|
||||
from diet_guard._budget import (
|
||||
BudgetFileCorruptError,
|
||||
BudgetNotInitializedError,
|
||||
@ -246,5 +247,4 @@ def main(argv: list[str] | None = None) -> int:
|
||||
A process exit code (0 on success).
|
||||
"""
|
||||
args = parse_args(sys.argv[1:] if argv is None else argv)
|
||||
_errors.install()
|
||||
return _COMMANDS[args.command](args)
|
||||
|
||||
@ -3,12 +3,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
RANK_DIET_GUARD: Final = 130
|
||||
"""gatelock arbitration rank: after the tutor (150), before focus-guard (128)
|
||||
and LeetCode (125) (``DOCS-lock-order.md``, kuhy 2026-11-21). A literal, not
|
||||
``gatelock.RANK_DIET_GUARD`` (100), so no gatelock release is needed."""
|
||||
|
||||
# --- Daily target -----------------------------------------------------------
|
||||
# There is deliberately NO budget number here. It is computed once from
|
||||
@ -171,10 +165,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.
|
||||
|
||||
@ -1,45 +0,0 @@
|
||||
"""Error and slow-wait reporting for the diet gate (utils DOCS-app-errors.md).
|
||||
|
||||
``install`` runs once from the CLI entry point: uncaught, thread and Tk
|
||||
callback errors, and a Tk loop frozen over 1 s, go to the app-errors spool,
|
||||
from which the PC's ingest files a board ticket. Only the CLI installs it, so
|
||||
tests that build a gate window never touch the real spool. The Flutter app
|
||||
reports separately, as ``diet-guard``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from gatelock import error_report
|
||||
from gatelock.error_report import watch_stalls
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import tkinter as tk
|
||||
|
||||
APP = "diet-guard-gate"
|
||||
REPO = "kuhyx/diet-guard"
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Slot:
|
||||
"""Holds the process's reporter once installed."""
|
||||
|
||||
reporter: error_report.Reporter | None = None
|
||||
|
||||
|
||||
#: The installed reporter (``SLOT.reporter``); None until ``install``.
|
||||
SLOT = _Slot()
|
||||
|
||||
|
||||
def install() -> error_report.Reporter:
|
||||
"""Hook this process's errors once; return the reporter."""
|
||||
SLOT.reporter = error_report.install(APP, REPO)
|
||||
return SLOT.reporter
|
||||
|
||||
|
||||
def watch(root: tk.Misc) -> None:
|
||||
"""Report ``root``'s freezes over 1 s, once ``install`` has run."""
|
||||
if SLOT.reporter is not None:
|
||||
watch_stalls(root, SLOT.reporter)
|
||||
@ -34,6 +34,7 @@ Building ``MealGate`` spans several sibling modules (the 250-line limit):
|
||||
: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
|
||||
@ -42,6 +43,7 @@ import sys
|
||||
import tkinter as tk
|
||||
|
||||
from gatelock import (
|
||||
RANK_DIET_GUARD,
|
||||
Arbiter,
|
||||
GateRoot,
|
||||
LockConfig,
|
||||
@ -50,15 +52,12 @@ from gatelock import (
|
||||
wait_for_turn,
|
||||
)
|
||||
|
||||
from diet_guard import _errors
|
||||
from diet_guard._constants import RANK_DIET_GUARD
|
||||
from diet_guard._gate import due_slots
|
||||
from diet_guard._gatelock_calendar import _GateCalendar, make_calendar_vars
|
||||
from diet_guard._gatelock_core import _GateState
|
||||
from diet_guard._gatelock_credit import arm_credit_watch
|
||||
from diet_guard._gatelock_groups import GateWidgetsGroup
|
||||
from diet_guard._gatelock_lockfile import acquire_gate_lock, release_gate_lock
|
||||
from diet_guard._gatelock_logo import place_logo
|
||||
from diet_guard._gatelock_peerpull import arm_peer_pull
|
||||
from diet_guard._gatelock_ui import GateCallbacks, make_vars
|
||||
from diet_guard._hold import watch_hold
|
||||
@ -128,7 +127,8 @@ class MealGate(_GateCalendar):
|
||||
self.root = GateRoot()
|
||||
self.root.on_callback_error = self.on_callback_error
|
||||
self.root.title("Diet Gate") # OS-level app name: the one kept noun
|
||||
# No colour overrides: LockConfig defaults are the palette (one drifted).
|
||||
# No colour overrides: LockConfig's defaults are the design-system palette
|
||||
# and _gatelock_ui reads them too (an override drifted once).
|
||||
config = LockConfig(
|
||||
mode="soft" if demo_mode else "hard",
|
||||
app_name="diet_guard",
|
||||
@ -172,9 +172,9 @@ class MealGate(_GateCalendar):
|
||||
monitor the user is actually looking at.
|
||||
"""
|
||||
widgets = self._build_tabs(parent, self._callbacks)
|
||||
place_logo(parent)
|
||||
self._widgets.add(widgets, surface.output_name)
|
||||
# A returning output gets its bindings; re-wiring the rest is a no-op.
|
||||
# An output coming back mid-lock gets its bindings too; tk's bind
|
||||
# replaces rather than stacks, so re-wiring the others is a no-op.
|
||||
self._wire_events()
|
||||
|
||||
def teardown_surface(self, surface: SurfaceInfo) -> None:
|
||||
@ -215,7 +215,6 @@ class MealGate(_GateCalendar):
|
||||
def run(self) -> None:
|
||||
"""Run the Tk loop (a hold or a meal logged elsewhere closes it), VT-safe."""
|
||||
watch_hold(self.root, self.close)
|
||||
_errors.watch(self.root) # here, not at build: the turn wait is no stall
|
||||
if not self.demo_mode: # a demo owes a synthetic slot: it would self-close
|
||||
arm_credit_watch(
|
||||
self.root, lambda: self._pending, self._reconcile_after_fetch
|
||||
|
||||
@ -1,27 +0,0 @@
|
||||
"""The kuhy logo in a corner of each gate surface (shared ``kuhy_credit``).
|
||||
|
||||
Uses the Tk widget from kuhy_credit (kuhy-credit-v0.3.0). A click opens the
|
||||
credit panel; the site opens only on a further click, so the lock cannot be
|
||||
escaped by accident. This module imports tkinter and builds widgets, so it
|
||||
belongs in ``_GATE_TK_MODULES`` (see ``_gatelock_layout``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from kuhy_credit.tk import KuhyCredit
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import tkinter as tk
|
||||
|
||||
__all__ = ["place_logo"]
|
||||
|
||||
_MARGIN = 16
|
||||
|
||||
|
||||
def place_logo(parent: tk.Misc) -> KuhyCredit:
|
||||
"""Overlay the logo on ``parent``'s bottom-right corner."""
|
||||
credit = KuhyCredit(parent, theme="dark")
|
||||
credit.place(relx=1, rely=1, x=-_MARGIN, y=-_MARGIN, anchor="se")
|
||||
return credit
|
||||
@ -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)
|
||||
@ -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._set_status(g.BUSY)
|
||||
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)
|
||||
|
||||
@ -52,14 +52,9 @@ _logger = logging.getLogger(__name__)
|
||||
FETCH_TIMEOUT_S = 5.0
|
||||
|
||||
|
||||
#: Names served lazily by ``__getattr__`` (read statically by
|
||||
#: scripts/check_patch_targets.py when the catering client cannot import).
|
||||
_LAZY_ATTRS = ("refresh_delivery",)
|
||||
|
||||
|
||||
def __getattr__(name: str) -> object:
|
||||
"""Resolve the deferred catering import on first attribute access."""
|
||||
if name not in _LAZY_ATTRS:
|
||||
if name != "refresh_delivery":
|
||||
msg = f"module {__name__!r} has no attribute {name!r}"
|
||||
raise AttributeError(msg)
|
||||
return import_module("diet_guard._kuchnia_import").refresh_delivery
|
||||
|
||||
@ -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")
|
||||
@ -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
|
||||
|
||||
@ -202,8 +202,6 @@ def fake_tk() -> Iterator[None]:
|
||||
with ExitStack() as stack:
|
||||
for module in _GATE_TK_MODULES:
|
||||
stack.enter_context(patch.object(module, "tk", _FAKE_TK))
|
||||
# The logo is a real Canvas subclass; it cannot take a fake parent.
|
||||
stack.enter_context(patch.object(_gatelock, "place_logo"))
|
||||
stack.enter_context(patch.object(_gatelock_calendar, "ttk", _FAKE_TTK))
|
||||
stack.enter_context(patch.object(_gatelock_calendar_ui, "ttk", _FAKE_TTK))
|
||||
# The schedule row's HH:MM spinboxes are ttk widgets; left real, they
|
||||
|
||||
@ -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.
|
||||
|
||||
@ -27,7 +27,6 @@ from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from diet_guard import _errors
|
||||
from diet_guard._estimator import Nutrition
|
||||
|
||||
# Importing these fixtures IS their registration: pytest discovers fixtures
|
||||
@ -114,15 +113,6 @@ def _isolate_state(tmp_path: Path) -> Iterator[None]:
|
||||
stack.enter_context(
|
||||
patch.dict(os.environ, {"HOLDS_DATA": str(tmp_path / "holds.json")})
|
||||
)
|
||||
# gatelock hooks a process once; a reporter already in INSTALLED makes
|
||||
# install() return it untouched, so no hook is set and every report
|
||||
# lands in this test's folder, never the real app-errors spool.
|
||||
spool = tmp_path / "app-errors-spool"
|
||||
rep = _errors.error_report.Reporter(_errors.APP, _errors.REPO, spool=spool)
|
||||
stack.enter_context(
|
||||
patch.object(_errors.error_report.INSTALLED, "reporter", rep)
|
||||
)
|
||||
stack.enter_context(patch.object(_errors.SLOT, "reporter", None))
|
||||
yield
|
||||
|
||||
|
||||
|
||||
@ -1,103 +0,0 @@
|
||||
"""CLI contract of ``scripts/check_patch_targets.py``: the package is an argument.
|
||||
|
||||
Other guard repos adopt the script by copying it into their own ``scripts/``,
|
||||
so each case copies it into a scratch repo next to a scratch package and runs
|
||||
it there as a subprocess -- the same shape an adopter gets. ``scripts/`` sits
|
||||
outside coverage ``source``, so the subprocess run is the whole check.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SCRIPT = ROOT / "scripts" / "check_patch_targets.py"
|
||||
|
||||
GOOD = 'from unittest import mock\nmock.patch("pkg_a.mod.VALUE", 1)\n'
|
||||
STALE = 'from unittest import mock\nmock.patch("pkg_a.mod.GONE", 1)\n'
|
||||
|
||||
|
||||
def _run(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
|
||||
"""Run the script with ``args`` from ``cwd``, as the pre-commit hook does."""
|
||||
return subprocess.run(
|
||||
[sys.executable, str(cwd / "scripts" / SCRIPT.name), *args],
|
||||
cwd=cwd,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
|
||||
def _scratch_repo(tmp_path: Path, test_source: str, tests_dir: str) -> Path:
|
||||
"""A repo with ``scripts/``, package ``pkg_a`` and one test file."""
|
||||
(tmp_path / "scripts").mkdir()
|
||||
shutil.copy(SCRIPT, tmp_path / "scripts" / SCRIPT.name)
|
||||
pkg = tmp_path / "pkg_a"
|
||||
pkg.mkdir()
|
||||
(pkg / "__init__.py").write_text("")
|
||||
(pkg / "mod.py").write_text("VALUE = 0\n")
|
||||
tests = tmp_path / tests_dir
|
||||
tests.mkdir(parents=True, exist_ok=True)
|
||||
(tests / "test_x.py").write_text(test_source)
|
||||
return tmp_path
|
||||
|
||||
|
||||
def test_missing_package_argument_is_a_usage_error(tmp_path: Path) -> None:
|
||||
"""No silent default: a bare run fails loudly instead of checking nothing."""
|
||||
repo = _scratch_repo(tmp_path, GOOD, "pkg_a/tests")
|
||||
result = _run(repo)
|
||||
assert result.returncode == 2
|
||||
assert "usage:" in result.stderr
|
||||
assert "package" in result.stderr
|
||||
|
||||
|
||||
def test_good_target_in_named_package_passes(tmp_path: Path) -> None:
|
||||
"""A resolvable target in ``<package>/tests`` exits 0 silently."""
|
||||
repo = _scratch_repo(tmp_path, GOOD, "pkg_a/tests")
|
||||
result = _run(repo, "pkg_a")
|
||||
assert (result.returncode, result.stderr) == (0, "")
|
||||
|
||||
|
||||
def test_stale_target_in_named_package_fails(tmp_path: Path) -> None:
|
||||
"""A target that no longer resolves names its file and line, and exits 1."""
|
||||
repo = _scratch_repo(tmp_path, STALE, "pkg_a/tests")
|
||||
result = _run(repo, "pkg_a")
|
||||
assert result.returncode == 1
|
||||
assert (
|
||||
"pkg_a/tests/test_x.py:2: patch target does not resolve: pkg_a.mod.GONE"
|
||||
in result.stderr
|
||||
)
|
||||
|
||||
|
||||
def test_tests_root_override_is_the_directory_checked(tmp_path: Path) -> None:
|
||||
"""``--tests-root`` replaces ``<package>/tests``, which may then not exist."""
|
||||
repo = _scratch_repo(tmp_path, STALE, "elsewhere")
|
||||
assert _run(repo, "pkg_a").returncode == 1 # default root is missing
|
||||
result = _run(repo, "pkg_a", "--tests-root", "elsewhere")
|
||||
assert result.returncode == 1
|
||||
assert "elsewhere/test_x.py:2:" in result.stderr
|
||||
|
||||
|
||||
def test_real_tree_passes_with_diet_guard_argument() -> None:
|
||||
"""The hook's own invocation is green on this repo."""
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(SCRIPT), "diet_guard"],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
timeout=60,
|
||||
)
|
||||
assert (result.returncode, result.stderr) == (0, "")
|
||||
|
||||
|
||||
def test_sibling_prefix_package_is_not_checked(tmp_path: Path) -> None:
|
||||
"""``pkg_a`` does not own ``pkg_ab``: a bare string prefix is not a package."""
|
||||
other = 'from unittest import mock\nmock.patch("pkg_ab.mod.GONE", 1)\n'
|
||||
repo = _scratch_repo(tmp_path, other, "pkg_a/tests")
|
||||
result = _run(repo, "pkg_a")
|
||||
assert (result.returncode, result.stderr) == (0, "")
|
||||
@ -1,65 +0,0 @@
|
||||
"""The gate's error reporting: installed once by the CLI, into the shared spool."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from diet_guard import _cli, _errors, _gatelock
|
||||
from diet_guard._gatelock import MealGate
|
||||
from diet_guard.tests._gate_fixtures import fake_tk
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_install_keeps_the_reporter_and_writes_the_spool(tmp_path: Path) -> None:
|
||||
"""The CLI's install names the gate app and its repo in every report."""
|
||||
rep = _errors.install()
|
||||
assert _errors.SLOT.reporter is rep
|
||||
assert rep.app == "diet-guard-gate"
|
||||
rep.report("uncaught.python", ValueError("deliberate"))
|
||||
line = (tmp_path / "app-errors-spool" / "diet-guard-gate.jsonl").read_text()
|
||||
entry = json.loads(line)
|
||||
assert entry["repo"] == "kuhyx/diet-guard"
|
||||
assert entry["error"] == "ValueError: deliberate"
|
||||
|
||||
|
||||
def test_cli_main_installs_before_dispatch(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Every CLI run hooks errors, the gate's included."""
|
||||
install = MagicMock()
|
||||
monkeypatch.setattr(_errors, "install", install)
|
||||
monkeypatch.setitem(_cli._COMMANDS, "status", lambda _args: 0)
|
||||
assert _cli.main(["status"]) == 0
|
||||
install.assert_called_once_with()
|
||||
|
||||
|
||||
def _run(gate: MealGate) -> None:
|
||||
"""Run the gate's start-up with its Tk loop stubbed out."""
|
||||
with (
|
||||
patch.object(gate, "_lock", MagicMock()),
|
||||
patch.object(_gatelock, "watch_hold"),
|
||||
):
|
||||
gate.run()
|
||||
|
||||
|
||||
def test_gate_watches_stalls_once_installed(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""A gate built after install reports its own freezes."""
|
||||
reporter = MagicMock()
|
||||
monkeypatch.setattr(_errors.SLOT, "reporter", reporter)
|
||||
with patch.object(_errors, "watch_stalls") as watch, fake_tk():
|
||||
gate = MealGate(demo_mode=True)
|
||||
watch.assert_not_called() # the turn wait while building is no stall
|
||||
_run(gate)
|
||||
watch.assert_called_once_with(gate.root, reporter)
|
||||
assert _gatelock._errors is _errors
|
||||
|
||||
|
||||
def test_gate_skips_the_watch_without_a_reporter() -> None:
|
||||
"""A gate built outside the CLI (tests, imports) never starts a watch."""
|
||||
with patch.object(_errors, "watch_stalls") as watch, fake_tk():
|
||||
_run(MealGate(demo_mode=True))
|
||||
watch.assert_not_called()
|
||||
@ -1,35 +0,0 @@
|
||||
"""The kuhy logo sits in the bottom-right corner of every gate surface."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tkinter as tk
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from kuhy_credit.tk import KuhyCredit
|
||||
import pytest
|
||||
|
||||
from diet_guard._gatelock_logo import place_logo
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pytest_xvfb import Xvfb
|
||||
|
||||
|
||||
def test_place_logo_anchors_bottom_right(xvfb: Xvfb | None) -> None:
|
||||
# Real Tk, so only ever on pytest-xvfb's private display -- never the user's.
|
||||
if xvfb is None:
|
||||
pytest.skip("needs pytest-xvfb's private display")
|
||||
assert os.environ["DISPLAY"] == f":{xvfb.display}"
|
||||
root = tk.Tk()
|
||||
try:
|
||||
root.withdraw()
|
||||
frame = tk.Frame(root)
|
||||
credit = place_logo(frame)
|
||||
assert isinstance(credit, KuhyCredit)
|
||||
assert credit.master is frame
|
||||
info = credit.place_info()
|
||||
assert info["anchor"] == "se"
|
||||
assert (info["relx"], info["rely"]) == ("1", "1")
|
||||
assert (info["x"], info["y"]) == ("-16", "-16")
|
||||
finally:
|
||||
root.destroy()
|
||||
@ -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() == ""
|
||||
@ -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."""
|
||||
|
||||
|
||||
@ -156,13 +156,6 @@ class TestAutologBeforeLock:
|
||||
assert autolog_due_delivery([].append) == 0
|
||||
fetch.assert_not_called()
|
||||
|
||||
def test_nothing_new_to_log_stays_silent(self) -> None:
|
||||
"""Dishes already logged: zero written, no report line."""
|
||||
self._go((DISHES, None))
|
||||
lines = self._go((DISHES, None))
|
||||
assert self.written == 0
|
||||
assert lines == []
|
||||
|
||||
def test_logging_error_is_swallowed(self) -> None:
|
||||
"""Even a disk error falls back to the lock instead of crashing the gate."""
|
||||
lines: list[str] = []
|
||||
|
||||
@ -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
|
||||
@ -1,34 +0,0 @@
|
||||
"""The rank this repo publishes matches its row in ``DOCS-lock-order.md``.
|
||||
|
||||
kuhy fixed the order of every lock on 2026-11-21 (workout, book, tutor, diet,
|
||||
focus, LeetCode last). Each repo keeps the rank as its own literal, so this
|
||||
test is what stops one repo drifting out of that order on its own.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
from diet_guard._constants import RANK_DIET_GUARD
|
||||
|
||||
_DOCS = Path(__file__).resolve().parents[2] / "DOCS-lock-order.md"
|
||||
_ROW = re.compile(r"^\| (\d+) \| [^|]+ \| (\w+) \| (\d+) \| [^|]+ \|$")
|
||||
|
||||
|
||||
def _documented_ranks() -> dict[str, int]:
|
||||
"""Map each gatelock app in the DOCS table to its rank."""
|
||||
rows = (_ROW.match(line) for line in _DOCS.read_text().splitlines())
|
||||
return {m[2]: int(m[3]) for m in rows if m}
|
||||
|
||||
|
||||
def test_the_rank_is_the_one_in_the_lock_order_table() -> None:
|
||||
"""A rank changed here without the table (or back) fails."""
|
||||
assert _documented_ranks()["diet_guard"] == RANK_DIET_GUARD
|
||||
|
||||
|
||||
def test_the_table_orders_the_locks_by_falling_rank() -> None:
|
||||
"""Rows run strongest first, and no two locks share a rank."""
|
||||
ranks = list(_documented_ranks().values())
|
||||
assert ranks == sorted(ranks, reverse=True)
|
||||
assert len(set(ranks)) == len(ranks)
|
||||
@ -1,86 +0,0 @@
|
||||
"""scripts/test_changed.sh runs flutter like a CI-mirror shard does.
|
||||
|
||||
A bare ``flutter test`` on the shared /tmp stalled a 3-file run to 67 s under
|
||||
the build queue (2026-11-21, perf.heavybuild) while the same files take ~4 s
|
||||
alone; the shards fixed that with a private TMPDIR and two isolates, and the
|
||||
targeted runner must do the same.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
GIT = shutil.which("git") or "git"
|
||||
BASH = shutil.which("bash") or "bash"
|
||||
FAKE_FLUTTER = """#!/bin/bash
|
||||
printf 'TMPDIR=%s\\n' "${TMPDIR:-}" >> "$FLUTTER_LOG"
|
||||
printf 'ARGS=%s\\n' "$*" >> "$FLUTTER_LOG"
|
||||
"""
|
||||
|
||||
|
||||
def _shared_tmp(tmp_path: Path) -> Path:
|
||||
"""Stand-in for the machine-wide /tmp the caller would pass down."""
|
||||
shared = tmp_path / "shared-tmp"
|
||||
shared.mkdir(exist_ok=True)
|
||||
return shared
|
||||
|
||||
|
||||
def _git(cwd: Path, *args: str) -> None:
|
||||
subprocess.run([GIT, *args], cwd=cwd, check=True, capture_output=True)
|
||||
|
||||
|
||||
def _run_test_changed(tmp_path: Path) -> dict[str, str]:
|
||||
repo = tmp_path / "repo"
|
||||
(repo / "scripts").mkdir(parents=True)
|
||||
(repo / "app" / "test").mkdir(parents=True)
|
||||
shutil.copy(REPO / "scripts" / "test_changed.sh", repo / "scripts")
|
||||
_git(repo, "init", "-q")
|
||||
_git(
|
||||
repo,
|
||||
"-c",
|
||||
"user.name=t",
|
||||
"-c",
|
||||
"user.email=t@t",
|
||||
"commit",
|
||||
"-q",
|
||||
"--allow-empty",
|
||||
"-m",
|
||||
"init",
|
||||
)
|
||||
(repo / "app" / "test" / "a_test.dart").write_text("void main() {}\n")
|
||||
bin_dir = tmp_path / "bin"
|
||||
bin_dir.mkdir()
|
||||
fake = bin_dir / "flutter"
|
||||
fake.write_text(FAKE_FLUTTER)
|
||||
fake.chmod(0o755)
|
||||
log = tmp_path / "flutter.log"
|
||||
env = {
|
||||
**os.environ,
|
||||
"PATH": f"{bin_dir}:{os.environ['PATH']}",
|
||||
"FLUTTER_LOG": str(log),
|
||||
"TMPDIR": str(_shared_tmp(tmp_path)),
|
||||
}
|
||||
subprocess.run(
|
||||
[BASH, "scripts/test_changed.sh"],
|
||||
cwd=repo,
|
||||
env=env,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
return dict(line.split("=", 1) for line in log.read_text().splitlines())
|
||||
|
||||
|
||||
def test_flutter_gets_a_private_tmpdir_that_is_removed(tmp_path: Path) -> None:
|
||||
seen = _run_test_changed(tmp_path)
|
||||
assert seen["TMPDIR"] not in {"", str(_shared_tmp(tmp_path))}
|
||||
assert not Path(seen["TMPDIR"]).exists()
|
||||
|
||||
|
||||
def test_flutter_runs_two_isolates_on_the_changed_file(tmp_path: Path) -> None:
|
||||
seen = _run_test_changed(tmp_path)
|
||||
assert "--concurrency=2" in seen["ARGS"]
|
||||
assert "test/a_test.dart" in seen["ARGS"]
|
||||
@ -3,7 +3,7 @@
|
||||
The phone sends a food description and/or a photo. A worker on the PC runs
|
||||
Claude on kuhy's Max subscription, **logs the meal at once (no review)** and
|
||||
answers the phone. Transport is Firebase RTDB through the shared
|
||||
`rtdb_relay` package (`kuhyx/utils`, tag `rtdb-relay-v0.2.0`), the same wire
|
||||
`rtdb_relay` package (`kuhyx/utils`, tag `rtdb-relay-v0.1.1`), the same wire
|
||||
format as the tutor app. No VPN, no open port, only kuhy's Google account.
|
||||
|
||||
This file is the contract both halves build against. The fixture
|
||||
|
||||
@ -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
|
||||
|
||||
@ -22,7 +22,7 @@ Until the first read of today's log the screen draws neither (no app-bar flash).
|
||||
|
||||
No slot picker. Due mode: both the check and the sparkle target the **oldest
|
||||
due slot** (`dueSlots.first`). Normal mode: `slotForLog` (nearest). The integer
|
||||
slot maths in `models/slot.dart` is untouched. A *future* date (the app bar's date icon,
|
||||
slot maths in `models/slot.dart` is untouched. A *future* date (the date row,
|
||||
normal mode only) keeps its own slot row, because it has no due slots to derive
|
||||
from.
|
||||
|
||||
@ -42,19 +42,6 @@ every state and `maxScrollExtent == 0`. Macro values of four digits must paint
|
||||
whole at 16 sp or more (`macro_input_row_test.dart` measures the digits; a
|
||||
`Row` of `Expanded` fields clips them without any exception).
|
||||
|
||||
## Date picker and the keyboard
|
||||
|
||||
- The "log for later" picker is the **leftmost app bar icon** (`Icons.edit_calendar`,
|
||||
`buildDateActions` in `log_meal_future_mixin.dart`); there is no date row above
|
||||
the field. A picked future date tints it gold (theme primary) with a small
|
||||
dot (`log-date-badge`) and adds a close icon back to today. No date text.
|
||||
- **NO COVER BY KEYBOARD EVER** (kuhy): while `viewInsetsOf(context).bottom > 0`
|
||||
the today-progress card and the logged rows are not built; they return when
|
||||
the keyboard closes. Field, suggestions, macros and action row sit fully
|
||||
above the keyboard with `maxScrollExtent == 0`, in normal and due mode, for
|
||||
a 320 dp and a 400 dp keyboard (`log_meal_keyboard_test.dart`). Do not fix
|
||||
an overflow by scrolling content under the keyboard.
|
||||
|
||||
## Logged rows and undo
|
||||
|
||||
After a Claude, check or catering log, a row (origin glyph, name, kcal and macro
|
||||
|
||||
@ -1,45 +0,0 @@
|
||||
# Patch-target gate (`scripts/check_patch_targets.py`)
|
||||
|
||||
`mock.patch("pkg.module.NAME", ...)` fails open. When a refactor moves `NAME`, the old path still
|
||||
imports, the patch redirects nothing, and the test stays green while it writes to real user state.
|
||||
The script reads every test file, finds each literal `patch("<package>....")` target, and exits 1
|
||||
when a target no longer resolves.
|
||||
|
||||
## Usage
|
||||
|
||||
Run it from the repo root:
|
||||
|
||||
```bash
|
||||
python3 scripts/check_patch_targets.py PACKAGE [--tests-root DIR]
|
||||
```
|
||||
|
||||
- `PACKAGE` is required. The script checks only targets inside it (`pkg` or `pkg.*`; `pkg_other`
|
||||
is not `pkg`). It has no default, because a silent default would check the wrong package and
|
||||
pass, which is the fail-open shape the gate exists to catch.
|
||||
- `--tests-root` defaults to `PACKAGE/tests`.
|
||||
- The package must be a flat package at the repo root (`./PACKAGE/__init__.py`). There is no
|
||||
`src/` layout support yet.
|
||||
- Exit codes: `0` clean, `1` stale targets (each printed as `file:line: patch target does not
|
||||
resolve: ...`), a package that will not import or a missing tests root, `2` usage error.
|
||||
|
||||
## Adopting it in another guard repo
|
||||
|
||||
Copy `scripts/check_patch_targets.py` into the repo's `scripts/`, then add this hook to
|
||||
`.pre-commit-config.yaml` under a `repo: local` block:
|
||||
|
||||
```yaml
|
||||
- id: patch-targets
|
||||
name: test patch targets resolve
|
||||
entry: python3 scripts/check_patch_targets.py <your_package>
|
||||
language: system
|
||||
pass_filenames: false
|
||||
files: ^<your_package>/
|
||||
```
|
||||
|
||||
The script puts the repo root on `sys.path` itself, so the hook works on a CI runner that never
|
||||
installed the package.
|
||||
|
||||
## Follow-up: a shared copy
|
||||
|
||||
Each adopter copies the script today. Moving it to a shared `~/src/utils/patch_targets/` package
|
||||
is a separate follow-up, done once a second repo actually adopts it.
|
||||
@ -19,9 +19,6 @@ and `test_gate_no_words_static.py` (Tk gate), `app/test/no_words_*_test.dart`
|
||||
|---|---|---|
|
||||
| `app/lib/main.dart` | `Diet Guard` | `MaterialApp.title`: task switcher and tab name |
|
||||
| `diet_guard/_gatelock.py` | `Diet Gate` | window title, an identifier under override-redirect |
|
||||
| `app/android/app/src/main/AndroidManifest.xml` | `DietGuard` | `android:label`: launcher name |
|
||||
| `app/desktop/install_desktop_entry.sh` | `DietGuard`, `Diet logging and budget companion` | `.desktop` Name and Comment: app-menu entry |
|
||||
| `packaging/aur/PKGBUILD` | `DietGuard`, `Diet logging and budget companion` | `.desktop` Name and Comment in the AUR package |
|
||||
|
||||
The launcher label and notification channel (`DietGuard`) live in
|
||||
`AndroidManifest.xml` and `notification_backend_io.dart`; a due-slot
|
||||
|
||||
@ -4,17 +4,16 @@ 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.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.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",
|
||||
"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.5#subdirectory=sickdays",
|
||||
"claude-agent-sdk==0.2.183",
|
||||
"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.1.1#subdirectory=rtdb_relay",
|
||||
]
|
||||
|
||||
# Optional extras. The `mcp` group is ONLY needed by the MCP server
|
||||
@ -24,9 +23,6 @@ dependencies = [
|
||||
# to import the MCP SDK.
|
||||
[project.optional-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"]
|
||||
|
||||
# Without this, setuptools' flat-layout auto-discovery treats the Flutter
|
||||
# app/ directory as a second top-level package and refuses to build.
|
||||
@ -178,6 +174,10 @@ addopts = [
|
||||
"--strict-markers",
|
||||
"--strict-config",
|
||||
"-ra",
|
||||
"--cov=diet_guard",
|
||||
"--cov-branch",
|
||||
"--cov-report=term-missing",
|
||||
"--cov-report=lcov",
|
||||
]
|
||||
filterwarnings = [
|
||||
"error",
|
||||
@ -203,6 +203,7 @@ omit = [
|
||||
]
|
||||
|
||||
[tool.coverage.report]
|
||||
fail_under = 100
|
||||
show_missing = true
|
||||
skip_covered = false
|
||||
exclude_lines = [
|
||||
|
||||
@ -1,21 +1,20 @@
|
||||
# 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.183
|
||||
codespell==2.4.3
|
||||
coverage==7.17.5
|
||||
coverage==7.17.3
|
||||
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.14.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.15
|
||||
mcp==2.3.0
|
||||
mypy==2.4.1
|
||||
pre-commit==4.7.0
|
||||
pydantic==2.14.4
|
||||
pydantic==2.14.3
|
||||
pylint==4.1.4
|
||||
pytest==9.2.0
|
||||
pytest-cov==7.1.0
|
||||
@ -24,6 +23,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
|
||||
ruff==0.17.6
|
||||
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays
|
||||
rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.1.1#subdirectory=rtdb_relay
|
||||
ruff==0.17.5
|
||||
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.5#subdirectory=sickdays
|
||||
|
||||
@ -10,20 +10,12 @@ suite writes to the real ``~/.local/share/diet_guard``, which
|
||||
That is why this gate exists rather than a note in CLAUDE.md: the failure it
|
||||
guards against is silent and green, so only a static check catches it.
|
||||
|
||||
Usage (from the repo root):
|
||||
python3 scripts/check_patch_targets.py PACKAGE [--tests-root DIR]
|
||||
|
||||
``PACKAGE`` is required: only patch targets starting with it are checked, and
|
||||
a silent default would be the same fail-open shape this script guards
|
||||
against. ``--tests-root`` defaults to ``PACKAGE/tests``. Only flat packages
|
||||
at the repo root are supported. Adopting it in another repo:
|
||||
docs/DOCS-patch-targets.md. A shared ``~/src/utils/patch_targets/`` package is
|
||||
a separate follow-up, once a second repo actually adopts this script.
|
||||
Usage:
|
||||
python3 scripts/check_patch_targets.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import ast
|
||||
import importlib
|
||||
import pathlib
|
||||
@ -33,6 +25,12 @@ from typing import TYPE_CHECKING
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
|
||||
#: Only paths into this package are checked; a patch of `requests` or `tk` is
|
||||
#: not ours to validate.
|
||||
PACKAGE = "diet_guard"
|
||||
|
||||
TESTS_ROOT = pathlib.Path(PACKAGE) / "tests"
|
||||
|
||||
# Running this as `python3 scripts/check_patch_targets.py` puts *scripts/* on
|
||||
# sys.path, not the repo root -- so `import diet_guard` fails unless the
|
||||
# package happens to be installed. It is not, on a CI runner that only
|
||||
@ -42,19 +40,8 @@ if TYPE_CHECKING:
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
|
||||
|
||||
|
||||
def _in_package(dotted: str, package: str) -> bool:
|
||||
"""Whether ``dotted`` is ``package`` or inside it (``pkg`` is not ``pkg_a``)."""
|
||||
return dotted == package or dotted.startswith(f"{package}.")
|
||||
|
||||
|
||||
def patch_targets(
|
||||
root: pathlib.Path, package: str
|
||||
) -> Iterator[tuple[pathlib.Path, int, str]]:
|
||||
"""Yield ``(file, lineno, dotted_target)`` for each literal target in ``package``.
|
||||
|
||||
Only paths into ``package`` are checked; a patch of ``requests`` or ``tk``
|
||||
is not ours to validate.
|
||||
"""
|
||||
def patch_targets(root: pathlib.Path) -> Iterator[tuple[pathlib.Path, int, str]]:
|
||||
"""Yield ``(file, lineno, dotted_target)`` for every literal patch target."""
|
||||
for path in sorted(root.rglob("*.py")):
|
||||
tree = ast.parse(path.read_text(), str(path))
|
||||
for node in ast.walk(tree):
|
||||
@ -67,30 +54,15 @@ def patch_targets(
|
||||
if (
|
||||
isinstance(first, ast.Constant)
|
||||
and isinstance(first.value, str)
|
||||
and _in_package(first.value, package)
|
||||
and first.value.startswith(PACKAGE)
|
||||
):
|
||||
yield path, node.lineno, first.value
|
||||
|
||||
|
||||
def _third_party_missing(exc: ImportError, package: str) -> bool:
|
||||
"""Whether ``exc`` is a missing dependency, not a missing ``package`` module."""
|
||||
def _third_party_missing(exc: ImportError) -> bool:
|
||||
"""Whether ``exc`` is a missing dependency, not a missing diet_guard module."""
|
||||
missing = getattr(exc, "name", None) or ""
|
||||
return isinstance(exc, ModuleNotFoundError) and not _in_package(missing, package)
|
||||
|
||||
|
||||
def _lazy_names(value: ast.expr | None) -> list[str]:
|
||||
"""The names a PEP 562 ``_LAZY_ATTRS`` table (dict keys or a tuple) serves."""
|
||||
if isinstance(value, ast.Dict):
|
||||
items: list[ast.expr | None] = list(value.keys)
|
||||
elif isinstance(value, (ast.Tuple, ast.List, ast.Set)):
|
||||
items = list(value.elts)
|
||||
else:
|
||||
return []
|
||||
return [
|
||||
i.value
|
||||
for i in items
|
||||
if isinstance(i, ast.Constant) and isinstance(i.value, str)
|
||||
]
|
||||
return isinstance(exc, ModuleNotFoundError) and not missing.startswith(PACKAGE)
|
||||
|
||||
|
||||
def defined_statically(parts: list[str], split: int) -> bool:
|
||||
@ -109,8 +81,6 @@ def defined_statically(parts: list[str], split: int) -> bool:
|
||||
elif isinstance(node, (ast.Assign, ast.AnnAssign)):
|
||||
targets = node.targets if isinstance(node, ast.Assign) else [node.target]
|
||||
names = [t.id for t in targets if isinstance(t, ast.Name)]
|
||||
if "_LAZY_ATTRS" in names:
|
||||
names += _lazy_names(node.value)
|
||||
elif isinstance(node, (ast.Import, ast.ImportFrom)):
|
||||
names = [(a.asname or a.name).split(".")[0] for a in node.names]
|
||||
else:
|
||||
@ -120,7 +90,7 @@ def defined_statically(parts: list[str], split: int) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def resolves(dotted: str, package: str) -> bool:
|
||||
def resolves(dotted: str) -> bool:
|
||||
"""Whether ``dotted`` names a real attribute reachable from a real module.
|
||||
|
||||
Tries the longest importable module prefix first, then walks the remaining
|
||||
@ -135,7 +105,7 @@ def resolves(dotted: str, package: str) -> bool:
|
||||
# worker's `rtdb_relay`, absent from the system python this hook
|
||||
# runs under) still has a source file: check the name statically
|
||||
# rather than call a present target stale.
|
||||
if _third_party_missing(exc, package) and defined_statically(parts, split):
|
||||
if _third_party_missing(exc) and defined_statically(parts, split):
|
||||
return True
|
||||
continue
|
||||
obj: object = module
|
||||
@ -147,25 +117,10 @@ def resolves(dotted: str, package: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _parse_args(argv: list[str] | None) -> argparse.Namespace:
|
||||
"""``package`` (required, no default) and ``--tests-root``."""
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("package", help="top-level package whose targets to check")
|
||||
parser.add_argument(
|
||||
"--tests-root",
|
||||
type=pathlib.Path,
|
||||
help="directory of tests to scan (default: PACKAGE/tests)",
|
||||
)
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
def main() -> int:
|
||||
"""Report every unresolvable patch target; return 1 if any were found."""
|
||||
args = _parse_args(argv)
|
||||
package: str = args.package
|
||||
tests_root: pathlib.Path = args.tests_root or pathlib.Path(package) / "tests"
|
||||
if not tests_root.is_dir():
|
||||
sys.stderr.write(f"Error: {tests_root} not found; run from the repo root.\n")
|
||||
if not TESTS_ROOT.is_dir():
|
||||
sys.stderr.write(f"Error: {TESTS_ROOT} not found; run from the repo root.\n")
|
||||
return 1
|
||||
|
||||
# Distinguish "this target moved" from "the package will not import at
|
||||
@ -173,10 +128,10 @@ def main(argv: list[str] | None = None) -> int:
|
||||
# target reports stale at once, which reads like a catastrophic refactor
|
||||
# and hides the real error (a missing dependency, a syntax error).
|
||||
try:
|
||||
importlib.import_module(package)
|
||||
importlib.import_module(PACKAGE)
|
||||
except ImportError as exc:
|
||||
sys.stderr.write(
|
||||
f"Error: cannot import {package} ({exc}); every patch target would "
|
||||
f"Error: cannot import {PACKAGE} ({exc}); every patch target would "
|
||||
f"be reported stale. Fix the import first -- this is an environment "
|
||||
f"problem, not a stale patch target.\n",
|
||||
)
|
||||
@ -184,8 +139,8 @@ def main(argv: list[str] | None = None) -> int:
|
||||
|
||||
stale = [
|
||||
(path, lineno, target)
|
||||
for path, lineno, target in patch_targets(tests_root, package)
|
||||
if not resolves(target, package)
|
||||
for path, lineno, target in patch_targets(TESTS_ROOT)
|
||||
if not resolves(target)
|
||||
]
|
||||
for path, lineno, target in stale:
|
||||
sys.stderr.write(f"{path}:{lineno}: patch target does not resolve: {target}\n")
|
||||
|
||||
@ -147,10 +147,7 @@ run_flutter_gates() {
|
||||
}
|
||||
|
||||
# Bucket I of N of the app's test files (every N-th, sorted), so the N buckets
|
||||
# partition the suite exactly. Each bucket stays under the 60 s action cap:
|
||||
# at 6 buckets of 25 files one took 39 s alone and 63-67 s when the machine
|
||||
# was busy (2026-11-21), so there are 12 (about 13 files each). Add hooks,
|
||||
# not files per hook, when the suite grows; a lone file costs about 3 s.
|
||||
# partition the suite exactly. Each bucket stays under the 60 s action cap.
|
||||
run_flutter_test_shard() {
|
||||
[[ ${1:-} =~ ^([0-9]+)/([1-9][0-9]*)$ ]] || fail "flutter-test --shard wants I/N, got '${1:-}'"
|
||||
local index=${BASH_REMATCH[1]} total=${BASH_REMATCH[2]} hooks i=0 file
|
||||
@ -167,18 +164,7 @@ run_flutter_test_shard() {
|
||||
done < <(find "$APP_DIR/test" -name '*_test.dart' | LC_ALL=C sort)
|
||||
((${#files[@]} > 0)) || fail "flutter test shard $index/$total has no test files"
|
||||
log "flutter test shard $index/$total (${#files[@]} files)"
|
||||
# A private TMPDIR per shard: on the shared /tmp a shard stalled at ~2 s of
|
||||
# CPU for 15+ minutes (2026-11-21, held a build slot past 60 s) while the
|
||||
# same shard with its own TMPDIR finished in well under a minute.
|
||||
# Two test isolates, not flutter's default of one per spare core: at the
|
||||
# default a shard peaked at 3.9 GiB and was OOM-killed inside capped.sh's
|
||||
# 2 GiB scope; at 4 it still hit 2 GiB and was killed now and then; at 2
|
||||
# it peaks at 1.8 GiB and runs in ~22 s (2026-11-21).
|
||||
local tmp status=0 concurrency=${FLUTTER_TEST_CONCURRENCY:-2}
|
||||
tmp="$(mktemp -d "${XDG_CACHE_HOME:-$HOME/.cache}/diet-guard-flutter-test.XXXXXX")"
|
||||
(cd "$APP_DIR" && TMPDIR="$tmp" flutter_clean_env test --concurrency="$concurrency" "${files[@]}") || status=$?
|
||||
rm -rf -- "$tmp"
|
||||
((status == 0)) || fail "flutter test shard $index/$total"
|
||||
(cd "$APP_DIR" && flutter_clean_env test "${files[@]}") || fail "flutter test shard $index/$total"
|
||||
}
|
||||
|
||||
# No phase argument (or pytest options) runs everything, exactly as CI does.
|
||||
|
||||
@ -1,49 +0,0 @@
|
||||
#!/bin/bash
|
||||
# ============================================================================
|
||||
# Deploy main everywhere it runs on this PC, then prove it.
|
||||
#
|
||||
# 1. Pull the durable clone the gate timer runs from (editable install).
|
||||
# 2. Reinstall it into system Python's user site: diet-guard-gate.service
|
||||
# runs /usr/bin/python, not a venv (CLAUDE.md, the 2026-06-19 outage).
|
||||
# 3. Rebuild and reinstall the desktop app package (app/install_arch.sh).
|
||||
# 4. Restart the long-running Claude worker so it loads the new code (the
|
||||
# gate is a oneshot timer and picks it up on its next tick).
|
||||
#
|
||||
# The phone APK ships through CI (release-apk.yml) and phone_deploy.sh.
|
||||
# Idempotent; exits non-zero unless every health check passes.
|
||||
# ============================================================================
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
readonly REPO="$HOME/src/diet-guard"
|
||||
readonly PY=/usr/bin/python3
|
||||
|
||||
fail() {
|
||||
echo "deploy: $*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
git -C "$REPO" pull --ff-only
|
||||
"$PY" -m pip install --user --break-system-packages -q -e "$REPO"
|
||||
(cd "$REPO/app" && bash install_arch.sh)
|
||||
readonly WORKER=diet-guard-claude.service
|
||||
worker_on=false
|
||||
if systemctl --user is-enabled --quiet "$WORKER"; then
|
||||
worker_on=true
|
||||
systemctl --user restart "$WORKER"
|
||||
fi
|
||||
|
||||
# Health: the gate's own interpreter imports the code the timer will run...
|
||||
"$PY" -c 'import diet_guard._cli, diet_guard._errors, diet_guard._gatelock' \
|
||||
|| fail "system python cannot import the gate"
|
||||
systemctl --user is-enabled --quiet diet-guard-gate.timer \
|
||||
|| fail "diet-guard-gate.timer is not enabled"
|
||||
if "$worker_on"; then
|
||||
sleep 3 # a worker that crashes on import dies within a second or two
|
||||
systemctl --user is-active --quiet "$WORKER" || fail "$WORKER did not stay up"
|
||||
fi
|
||||
# ...and the desktop package is the version this checkout builds.
|
||||
want="$(sed -n 's/^version:[[:space:]]*\([^+]*\).*/\1/p' "$REPO/app/pubspec.yaml")"
|
||||
have="$(pacman -Q diet-guard-app | awk '{print $2}')"
|
||||
[[ "$have" == "$want-1" ]] || fail "desktop app is $have, want $want-1"
|
||||
echo "deploy: ok (gate imports, timer enabled, worker restarted=$worker_on, desktop app $have)"
|
||||
@ -22,16 +22,8 @@ pytest_run() {
|
||||
}
|
||||
|
||||
# Dart changes map to app/test/<name>_test.dart; any other app/ change runs the app suite.
|
||||
# A private TMPDIR and two isolates, as each ci_mirror.sh shard does: on the
|
||||
# shared /tmp a 3-file run stalled to 67 s in the build queue (2026-11-21)
|
||||
# against ~4 s alone, and the default isolate count overruns capped.sh's 2 GiB.
|
||||
flutter_run() {
|
||||
local tmp status=0
|
||||
tmp="$(mktemp -d "${XDG_CACHE_HOME:-$HOME/.cache}/diet-guard-flutter-test.XXXXXX")"
|
||||
(cd app && TMPDIR="$tmp" flutter test --reporter=compact \
|
||||
--concurrency="${FLUTTER_TEST_CONCURRENCY:-2}" "$@") || status=$?
|
||||
rm -rf -- "$tmp"
|
||||
return "$status"
|
||||
(cd app && flutter test --reporter=compact "$@")
|
||||
}
|
||||
|
||||
if grep -qs testmon pyproject.toml requirements*.txt; then
|
||||
|
||||
Loading…
Reference in New Issue
Block a user