mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-26 18:47:23 +01:00
Add a Claude button to the gate lock
A star button beside the log button sends the typed text to estimate_meal and logs the result like a typed meal: the locked slot, source "claude", food bank, unlock. Icon states only (idle star, spinner, warning); no visible text. It is composed (ClaudeFlow), not a new MRO class, since the gate chain is at pylint's max-parents cap. Idle uses U+2726, not the sparkles emoji: U+2728 is only in FreeSerif and Noto Color Emoji here, and a colour-emoji fallback can crash Tk 8.6. Failure paths (all fail-closed: never unlock, block or freeze): - estimator error, no login, bad JSON, any exception: warning icon, nothing logged, manual log path untouched. - no answer in 45 s: the poll gives up (warning icon); a late answer is discarded. - slot already logged by hand meanwhile: the result is dropped. - empty description: error status, no call. - seam: the estimator name is patched to a raising stub in conftest; a mistyped target errors every test at setup (verified once). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
This commit is contained in:
parent
03b6a455cb
commit
a936d07a7e
@ -27,16 +27,14 @@ prominent, with macros and the protein target beneath. The unlock condition is
|
|||||||
*logging*, never *estimating correctly*: a manual calorie value always works
|
*logging*, never *estimating correctly*: a manual calorie value always works
|
||||||
offline, so a dead OFF endpoint can never trap you behind the lock.
|
offline, so a dead OFF endpoint can never trap you behind the lock.
|
||||||
|
|
||||||
Building ``MealGate`` spans several sibling modules to keep each under the
|
Building ``MealGate`` spans several sibling modules (the 250-line limit):
|
||||||
repo's 250-line limit: :mod:`._gatelock_core` provides the shared leaf
|
:mod:`._gatelock_core` holds the shared leaf widget/field helpers and state
|
||||||
widget/field helpers and state (``_GateCore``, ``_GateState``);
|
(``_GateCore``, ``_GateState``, the Claude button's glue);
|
||||||
:mod:`._gatelock_nutrition` provides the reference->total nutrition maths and
|
:mod:`._gatelock_nutrition` the reference->total maths and food lookup;
|
||||||
food lookup (``_GateNutrition``); :mod:`._gatelock_mealflow` provides the
|
:mod:`._gatelock_mealflow` the submit/log flow, dashboard, callback errors and
|
||||||
submit/log flow, dashboard, callback errors and the pull-it-in buttons
|
pull-it-in buttons (``_GateMealFlow`` + ``_PullFlows``); :mod:`._gatelock_calendar`
|
||||||
(``_GateMealFlow`` + ``_PullFlows``); :mod:`._gatelock_calendar` the tab --
|
the tab -- calendar, streaks, YTD tally (:mod:`._daystatus`), budget editing.
|
||||||
the budget-adherence calendar, streaks, YTD tally (:mod:`._daystatus`) and
|
``MealGate`` wires these together and owns the ``gatelock.LockWindow``.
|
||||||
budget editing (``_GateCalendar``). ``MealGate`` wires these together, owns the
|
|
||||||
``gatelock.LockWindow``, and handles construction, layout and event binding.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@ -161,6 +159,7 @@ class MealGate(_GateCalendar):
|
|||||||
on_fetch_sync=self._on_fetch_sync,
|
on_fetch_sync=self._on_fetch_sync,
|
||||||
on_load_delivery=self._on_load_delivery,
|
on_load_delivery=self._on_load_delivery,
|
||||||
on_fill_all=self._on_fill_all,
|
on_fill_all=self._on_fill_all,
|
||||||
|
on_claude=self._on_claude,
|
||||||
)
|
)
|
||||||
self._build()
|
self._build()
|
||||||
|
|
||||||
|
|||||||
173
diet_guard/_gatelock_claude.py
Normal file
173
diet_guard/_gatelock_claude.py
Normal file
@ -0,0 +1,173 @@
|
|||||||
|
"""The lock screen's Claude button: estimate the typed meal, log it, unlock.
|
||||||
|
|
||||||
|
The user types a description and presses the sparkle instead of filling the
|
||||||
|
macro fields. The text (never a photo, the PC has none) goes to
|
||||||
|
:func:`diet_guard._claude_estimate.estimate_meal`; on success the meal is
|
||||||
|
logged through the gate's own ``record`` hook, so it takes the same path as a
|
||||||
|
typed meal: the slot being locked for, the food bank, the dashboard, the
|
||||||
|
unlock. Its entry carries ``source="claude"``.
|
||||||
|
|
||||||
|
**It can never make the lock worse.** Four rules, each with a test:
|
||||||
|
|
||||||
|
* *Off the Tk thread.* The call runs on a daemon thread that only ``put``s on
|
||||||
|
a queue; the Tk thread polls it with ``after`` (Tcl is not thread-safe, and
|
||||||
|
a model call takes seconds). A daemon so a hung call cannot keep the
|
||||||
|
``Type=oneshot`` unit alive once the window is gone.
|
||||||
|
* *A hard 45 s deadline* on the poll, whatever the worker does. Past it the
|
||||||
|
result is abandoned and a late answer is discarded.
|
||||||
|
* *Any failure is an icon, nothing else.* No login, timeout, bad JSON, a bug:
|
||||||
|
the button shows the error icon and the manual log path is untouched. There
|
||||||
|
is no state in which a failed estimate unlocks, blocks or freezes anything.
|
||||||
|
* *A result for a slot that moved on is dropped*: if the user logged the slot
|
||||||
|
by hand while Claude thought, the answer must not land on the next one.
|
||||||
|
|
||||||
|
Composed into the gate (as ``FillAllFlow`` is) rather than mixed in: pylint's
|
||||||
|
``max-parents`` counts every class in the gate's MRO and the chain is at the
|
||||||
|
cap. The gate hands this object the few callables it needs.
|
||||||
|
|
||||||
|
``_claude_estimate`` reaches the Agent SDK, which the gate's frequent not-due
|
||||||
|
tick must not import, so the name resolves on first access (PEP 562) and a
|
||||||
|
test's ``patch.object`` still wins.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from contextlib import suppress
|
||||||
|
from importlib import import_module
|
||||||
|
import queue
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
from time import monotonic
|
||||||
|
from typing import TYPE_CHECKING, NamedTuple
|
||||||
|
|
||||||
|
from diet_guard import _gatelock_glyphs as g
|
||||||
|
from diet_guard._estimator import Nutrition
|
||||||
|
from diet_guard._gatelock_fetch import FETCH_POLL_MS
|
||||||
|
|
||||||
|
if TYPE_CHECKING: # pragma: no cover - typing only
|
||||||
|
from collections.abc import Callable
|
||||||
|
import tkinter as tk
|
||||||
|
|
||||||
|
from diet_guard._claude_schema import Estimate
|
||||||
|
|
||||||
|
#: The poll's hard deadline in seconds; the estimator's own budget matches it.
|
||||||
|
CLAUDE_TIMEOUT_S = 45.0
|
||||||
|
|
||||||
|
#: Polls between spinner frames (50 ms each).
|
||||||
|
_FRAME_TICKS = 4
|
||||||
|
|
||||||
|
#: ``Nutrition.source`` of an estimated meal; keys ``g.source_glyph``.
|
||||||
|
SOURCE = "claude"
|
||||||
|
|
||||||
|
|
||||||
|
def __getattr__(name: str) -> object:
|
||||||
|
"""Resolve the deferred estimator import on first attribute access."""
|
||||||
|
if name != "estimate_meal":
|
||||||
|
msg = f"module {__name__!r} has no attribute {name!r}"
|
||||||
|
raise AttributeError(msg)
|
||||||
|
return import_module("diet_guard._claude_estimate").estimate_meal
|
||||||
|
|
||||||
|
|
||||||
|
def start_estimate(text: str) -> queue.Queue[Estimate | None]:
|
||||||
|
"""Run the estimator on a daemon thread; return its result queue.
|
||||||
|
|
||||||
|
The queue always receives exactly one item: the estimate, or ``None`` for
|
||||||
|
any failure (the worker has nowhere to propagate to, so an escaping
|
||||||
|
exception would leave the poll waiting for the whole deadline).
|
||||||
|
"""
|
||||||
|
result: queue.Queue[Estimate | None] = queue.Queue(maxsize=1)
|
||||||
|
|
||||||
|
def _worker() -> None:
|
||||||
|
"""Runs OFF the Tk thread. Touches no widget, by construction."""
|
||||||
|
outcome: Estimate | None = None
|
||||||
|
with suppress(Exception):
|
||||||
|
outcome = sys.modules[__name__].estimate_meal(text, None)
|
||||||
|
result.put(outcome)
|
||||||
|
|
||||||
|
threading.Thread(target=_worker, daemon=True).start()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
class ClaudeHooks(NamedTuple):
|
||||||
|
"""What the flow calls back into the gate."""
|
||||||
|
|
||||||
|
#: The typed description.
|
||||||
|
get_desc: Callable[[], str]
|
||||||
|
#: The gate's status-line writer.
|
||||||
|
set_status: Callable[..., None]
|
||||||
|
#: The slot the gate is locking for now, None when nothing is pending.
|
||||||
|
slot: Callable[[], int | None]
|
||||||
|
#: Log and advance, exactly like a typed meal (``_GateMealFlow._record``).
|
||||||
|
record: Callable[[str, Nutrition], None]
|
||||||
|
|
||||||
|
|
||||||
|
class ClaudeFlow:
|
||||||
|
"""Drives one gate's Claude button through estimate, poll and log."""
|
||||||
|
|
||||||
|
def __init__(self, root: tk.Misc, label: tk.StringVar, hooks: ClaudeHooks) -> None:
|
||||||
|
"""Bind the flow to a gate.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
root: Schedules the poll on the Tk thread.
|
||||||
|
label: The button's icon, shared by its copy on every monitor.
|
||||||
|
hooks: The gate callbacks the flow drives.
|
||||||
|
"""
|
||||||
|
self._root = root
|
||||||
|
self._label = label
|
||||||
|
self._hooks = hooks
|
||||||
|
self._result: queue.Queue[Estimate | None] | None = None
|
||||||
|
self._slot: int | None = None
|
||||||
|
self._deadline = 0.0
|
||||||
|
self._tick = 0
|
||||||
|
|
||||||
|
def click(self) -> None:
|
||||||
|
"""Estimate the typed meal; a click while one is running is ignored."""
|
||||||
|
if self._result is not None:
|
||||||
|
return
|
||||||
|
text = self._hooks.get_desc()
|
||||||
|
if not text:
|
||||||
|
self._hooks.set_status(f"{g.ERROR} {g.FOOD}", error=True)
|
||||||
|
return
|
||||||
|
self._slot = self._hooks.slot()
|
||||||
|
self._deadline = monotonic() + CLAUDE_TIMEOUT_S
|
||||||
|
self._tick = 0
|
||||||
|
self._label.set(g.CLAUDE_BUSY[0])
|
||||||
|
self._result = sys.modules[__name__].start_estimate(text)
|
||||||
|
self._root.after(FETCH_POLL_MS, self._poll)
|
||||||
|
|
||||||
|
def _poll(self) -> None:
|
||||||
|
"""On the Tk thread: spin, time out, or pick up the estimate."""
|
||||||
|
result = self._result
|
||||||
|
if result is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
estimate = result.get_nowait()
|
||||||
|
except queue.Empty:
|
||||||
|
if monotonic() >= self._deadline:
|
||||||
|
self._finish(failed=True)
|
||||||
|
return
|
||||||
|
self._tick += 1
|
||||||
|
frames = g.CLAUDE_BUSY
|
||||||
|
self._label.set(frames[self._tick // _FRAME_TICKS % len(frames)])
|
||||||
|
self._root.after(FETCH_POLL_MS, self._poll)
|
||||||
|
return
|
||||||
|
if estimate is None:
|
||||||
|
self._finish(failed=True)
|
||||||
|
return
|
||||||
|
self._finish(failed=False)
|
||||||
|
if self._hooks.slot() != self._slot:
|
||||||
|
return # the user moved on while Claude thought
|
||||||
|
nutrition = Nutrition(
|
||||||
|
kcal=estimate.kcal,
|
||||||
|
protein_g=estimate.protein_g,
|
||||||
|
carbs_g=estimate.carbs_g,
|
||||||
|
fat_g=estimate.fat_g,
|
||||||
|
grams=estimate.grams,
|
||||||
|
source=SOURCE,
|
||||||
|
)
|
||||||
|
self._hooks.record(estimate.desc, nutrition)
|
||||||
|
|
||||||
|
def _finish(self, *, failed: bool) -> None:
|
||||||
|
"""Free the button before anything else can raise."""
|
||||||
|
self._result = None
|
||||||
|
self._label.set(g.CLAUDE_FAILED if failed else g.CLAUDE)
|
||||||
@ -15,6 +15,7 @@ import logging
|
|||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from diet_guard._gatelock_claude import ClaudeFlow, ClaudeHooks
|
||||||
from diet_guard._gatelock_glyphs import CLOCK, OK
|
from diet_guard._gatelock_glyphs import CLOCK, OK
|
||||||
from diet_guard._gatelock_ui import (
|
from diet_guard._gatelock_ui import (
|
||||||
BASIS_PREFIX_GRAMS,
|
BASIS_PREFIX_GRAMS,
|
||||||
@ -85,6 +86,28 @@ class _GateCore:
|
|||||||
_vars: GateVars
|
_vars: GateVars
|
||||||
_widgets: GateWidgets
|
_widgets: GateWidgets
|
||||||
close: Callable[[], None]
|
close: Callable[[], None]
|
||||||
|
# Supplied by ``_GateMealFlow``, which sits below this class.
|
||||||
|
_set_status: Callable[..., None]
|
||||||
|
_record: Callable[[str, Nutrition], None]
|
||||||
|
|
||||||
|
#: Built on the first Claude click; it holds that button's state.
|
||||||
|
_claude_flow: ClaudeFlow | None = None
|
||||||
|
|
||||||
|
def _on_claude(self) -> None:
|
||||||
|
"""Estimate the typed meal with Claude and log it like a typed one.
|
||||||
|
|
||||||
|
Composed (:mod:`._gatelock_claude`), not a mixin: the gate's MRO is at
|
||||||
|
pylint's ``max-parents`` cap. Built once, on the first click.
|
||||||
|
"""
|
||||||
|
if self._claude_flow is None:
|
||||||
|
hooks = ClaudeHooks(
|
||||||
|
self._get_desc,
|
||||||
|
self._set_status,
|
||||||
|
lambda: self._pending[0] if self._pending else None,
|
||||||
|
self._record,
|
||||||
|
)
|
||||||
|
self._claude_flow = ClaudeFlow(self.root, self._vars.claude_label, hooks)
|
||||||
|
self._claude_flow.click()
|
||||||
|
|
||||||
# -- description field ---------------------------------------------------
|
# -- description field ---------------------------------------------------
|
||||||
|
|
||||||
|
|||||||
@ -53,6 +53,15 @@ FILL_ALL: Final = "⇊"
|
|||||||
INFINITE: Final = "∞"
|
INFINITE: Final = "∞"
|
||||||
UNLOCKING: Final = "⇥"
|
UNLOCKING: Final = "⇥"
|
||||||
|
|
||||||
|
# The Claude estimate button: idle, one frame per poll tick while working
|
||||||
|
# (the spinner), and the error state it rests in until the next click. Idle is
|
||||||
|
# the monochrome four-pointed star, not the sparkles emoji (U+2728): that one
|
||||||
|
# is only in FreeSerif and Noto Color Emoji here, and a colour-emoji fallback
|
||||||
|
# can crash Tk 8.6 -- the one window that must never fail to draw.
|
||||||
|
CLAUDE: Final = "✦"
|
||||||
|
CLAUDE_BUSY: Final = "◐◓◑◒"
|
||||||
|
CLAUDE_FAILED: Final = "⚠"
|
||||||
|
|
||||||
# Notebook tabs.
|
# Notebook tabs.
|
||||||
TAB_LOG: Final = "✚"
|
TAB_LOG: Final = "✚"
|
||||||
TAB_HISTORY: Final = "▦"
|
TAB_HISTORY: Final = "▦"
|
||||||
@ -84,5 +93,6 @@ def source_glyph(source: str) -> str:
|
|||||||
"food bank": "▤",
|
"food bank": "▤",
|
||||||
"staple": "★",
|
"staple": "★",
|
||||||
"catering": DELIVERY,
|
"catering": DELIVERY,
|
||||||
|
"claude": CLAUDE,
|
||||||
"manual": FOOD,
|
"manual": FOOD,
|
||||||
}.get(head, "≈")
|
}.get(head, "≈")
|
||||||
|
|||||||
@ -102,15 +102,30 @@ def _build_readouts(body: tk.Frame, vars_: GateVars) -> None:
|
|||||||
|
|
||||||
|
|
||||||
def _build_actions(
|
def _build_actions(
|
||||||
body: tk.Frame, callbacks: GateCallbacks, fill_label: tk.StringVar
|
body: tk.Frame,
|
||||||
|
callbacks: GateCallbacks,
|
||||||
|
fill_label: tk.StringVar,
|
||||||
|
claude_label: tk.StringVar,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Pack the submit button and the three "pull it in" buttons."""
|
"""Pack the submit and Claude buttons, then the "pull it in" buttons."""
|
||||||
|
log = tk.Frame(body, bg=BG) # one row: no extra height (1366x768 fit test)
|
||||||
|
log.pack(pady=(XS, XS))
|
||||||
make_button(
|
make_button(
|
||||||
body,
|
log,
|
||||||
_COLORS,
|
_COLORS,
|
||||||
glyphs.SUBMIT,
|
glyphs.SUBMIT,
|
||||||
callbacks.on_submit,
|
callbacks.on_submit,
|
||||||
).pack(pady=(XS, XS))
|
).pack(side="left", padx=(0, XS))
|
||||||
|
# Claude estimates the typed meal and logs it; the icon is a shared variable.
|
||||||
|
claude = make_button(
|
||||||
|
log,
|
||||||
|
_COLORS,
|
||||||
|
claude_label.get(),
|
||||||
|
callbacks.on_claude,
|
||||||
|
ButtonStyle(variant="secondary", bold=False),
|
||||||
|
)
|
||||||
|
claude.configure(textvariable=claude_label)
|
||||||
|
claude.pack(side="left")
|
||||||
|
|
||||||
# Both "pull it in from elsewhere" actions share one row: stacking them
|
# Both "pull it in from elsewhere" actions share one row: stacking them
|
||||||
# cost 42px, which pushed the tab past the viewport on a 1366x768 screen
|
# cost 42px, which pushed the tab past the viewport on a 1366x768 screen
|
||||||
@ -192,7 +207,7 @@ def build_layout(
|
|||||||
basis_prefix, per_entry, macros = build_macro_section(root, body, vars_)
|
basis_prefix, per_entry, macros = build_macro_section(root, body, vars_)
|
||||||
|
|
||||||
_build_readouts(body, vars_)
|
_build_readouts(body, vars_)
|
||||||
_build_actions(body, callbacks, vars_.fill_label)
|
_build_actions(body, callbacks, vars_.fill_label, vars_.claude_label)
|
||||||
|
|
||||||
status_label = tk.Label(
|
status_label = tk.Label(
|
||||||
body,
|
body,
|
||||||
|
|||||||
@ -1,11 +1,8 @@
|
|||||||
"""Submit/record flow for the MealGate gate.
|
"""Submit/record flow for the MealGate gate.
|
||||||
|
|
||||||
Split out of :mod:`._gatelock` to keep that module under the repo's 250-line
|
Split out of :mod:`._gatelock` to keep that module under the 250-line limit.
|
||||||
limit. ``_GateMealFlow`` extends
|
``_GateMealFlow`` adds the submit/lookup/log flow, the per-slot input reset
|
||||||
:class:`~diet_guard._gatelock_dashboard._GateDashboard` (itself over
|
and the read-only calorie/macro dashboard.
|
||||||
:class:`~diet_guard._gatelock_nutrition._GateNutrition`) with the
|
|
||||||
submit/lookup/log flow and the per-slot input reset. The read-only
|
|
||||||
calorie/macro dashboard it calls into lives in :mod:`._gatelock_dashboard`.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|||||||
@ -26,7 +26,7 @@ from gatelock import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
from diet_guard._gatelock_fillall import FILL_LABEL
|
from diet_guard._gatelock_fillall import FILL_LABEL
|
||||||
from diet_guard._gatelock_glyphs import TIMES
|
from diet_guard._gatelock_glyphs import CLAUDE, TIMES
|
||||||
from diet_guard._gatelock_spacing import SM, XS
|
from diet_guard._gatelock_spacing import SM, XS
|
||||||
from diet_guard._gatelock_typography import (
|
from diet_guard._gatelock_typography import (
|
||||||
BODY,
|
BODY,
|
||||||
@ -103,6 +103,7 @@ def make_vars(root: tk.Misc) -> GateVars:
|
|||||||
fat=tk.StringVar(master=root, value=""),
|
fat=tk.StringVar(master=root, value=""),
|
||||||
),
|
),
|
||||||
fill_label=tk.StringVar(master=root, value=FILL_LABEL),
|
fill_label=tk.StringVar(master=root, value=FILL_LABEL),
|
||||||
|
claude_label=tk.StringVar(master=root, value=CLAUDE),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -57,6 +57,8 @@ class GateVars:
|
|||||||
entries: GateEntryVars
|
entries: GateEntryVars
|
||||||
#: "Fill all"'s label, shared so it relabels on every monitor at once.
|
#: "Fill all"'s label, shared so it relabels on every monitor at once.
|
||||||
fill_label: tk.StringVar
|
fill_label: tk.StringVar
|
||||||
|
#: The Claude button's icon state, shared so every monitor's copy follows.
|
||||||
|
claude_label: tk.StringVar
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@ -88,3 +90,4 @@ class GateCallbacks:
|
|||||||
on_fetch_sync: Callable[[], None]
|
on_fetch_sync: Callable[[], None]
|
||||||
on_load_delivery: Callable[[], None]
|
on_load_delivery: Callable[[], None]
|
||||||
on_fill_all: Callable[[], None]
|
on_fill_all: Callable[[], None]
|
||||||
|
on_claude: Callable[[], None]
|
||||||
|
|||||||
@ -44,6 +44,12 @@ def claude_redirects(tmp_path: Path) -> list[_patch[object]]:
|
|||||||
blocked("_claude_connect.connect_sealed"),
|
blocked("_claude_connect.connect_sealed"),
|
||||||
),
|
),
|
||||||
patch("diet_guard._claude_sdk.run_model", blocked("_claude_sdk.run_model")),
|
patch("diet_guard._claude_sdk.run_model", blocked("_claude_sdk.run_model")),
|
||||||
|
# The gate's Claude button resolves the estimator lazily through this
|
||||||
|
# name; blocked here so no gate test can reach the model or the quota.
|
||||||
|
patch(
|
||||||
|
"diet_guard._gatelock_claude.estimate_meal",
|
||||||
|
blocked("_gatelock_claude.estimate_meal"),
|
||||||
|
),
|
||||||
patch("diet_guard._claude_sync.pull_peers", return_value=None),
|
patch("diet_guard._claude_sync.pull_peers", return_value=None),
|
||||||
patch("diet_guard._claude_sync.publish", return_value=None),
|
patch("diet_guard._claude_sync.publish", return_value=None),
|
||||||
patch("diet_guard._claude_sandbox.SANDBOX_DIR", tmp_path / "claude-sandbox"),
|
patch("diet_guard._claude_sandbox.SANDBOX_DIR", tmp_path / "claude-sandbox"),
|
||||||
|
|||||||
@ -94,6 +94,7 @@ def probe(screen_w: int = 1366, screen_h: int = 768) -> RingReport:
|
|||||||
on_fetch_sync=_noop,
|
on_fetch_sync=_noop,
|
||||||
on_load_delivery=_noop,
|
on_load_delivery=_noop,
|
||||||
on_fill_all=_noop,
|
on_fill_all=_noop,
|
||||||
|
on_claude=_noop,
|
||||||
)
|
)
|
||||||
widgets = build_layout(
|
widgets = build_layout(
|
||||||
notebook, _make_vars(populated=True), callbacks, demo_mode=False
|
notebook, _make_vars(populated=True), callbacks, demo_mode=False
|
||||||
|
|||||||
@ -92,6 +92,7 @@ def _make_vars(*, populated: bool) -> GateVars:
|
|||||||
entries=entries,
|
entries=entries,
|
||||||
# The wider of the button's two labels, so the row is measured at worst.
|
# The wider of the button's two labels, so the row is measured at worst.
|
||||||
fill_label=tk.StringVar(value="✓ Confirm (5)" if populated else "🍱 Fill all"),
|
fill_label=tk.StringVar(value="✓ Confirm (5)" if populated else "🍱 Fill all"),
|
||||||
|
claude_label=tk.StringVar(value="✦"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@ -153,6 +154,7 @@ def measure(
|
|||||||
on_fetch_sync=_noop,
|
on_fetch_sync=_noop,
|
||||||
on_load_delivery=_noop,
|
on_load_delivery=_noop,
|
||||||
on_fill_all=_noop,
|
on_fill_all=_noop,
|
||||||
|
on_claude=_noop,
|
||||||
)
|
)
|
||||||
widgets = build_layout(
|
widgets = build_layout(
|
||||||
notebook, _make_vars(populated=populated), callbacks, demo_mode=False
|
notebook, _make_vars(populated=populated), callbacks, demo_mode=False
|
||||||
|
|||||||
203
diet_guard/tests/test_gatelock_claude.py
Normal file
203
diet_guard/tests/test_gatelock_claude.py
Normal file
@ -0,0 +1,203 @@
|
|||||||
|
"""The gate's Claude button: off-thread estimate, icon states, never a trap.
|
||||||
|
|
||||||
|
Driven without a real thread where it can be: the worker's queue is handed in
|
||||||
|
and the poll is called by hand, as in ``test_gatelock_fillall``. The rules:
|
||||||
|
|
||||||
|
* the Tk thread only polls a queue (the estimate runs on a daemon thread);
|
||||||
|
* a failure, a timeout, a late or stale result leaves the lock exactly as it
|
||||||
|
was -- the manual log path never depends on this flow;
|
||||||
|
* a success logs through the gate's own ``record`` hook (``source="claude"``).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import queue
|
||||||
|
import time
|
||||||
|
from typing import Any
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from diet_guard import _gatelock_claude
|
||||||
|
from diet_guard import _gatelock_glyphs as g
|
||||||
|
from diet_guard._claude_estimate import EstimateError
|
||||||
|
from diet_guard._claude_schema import Estimate
|
||||||
|
from diet_guard._gatelock_claude import (
|
||||||
|
CLAUDE_TIMEOUT_S,
|
||||||
|
ClaudeFlow,
|
||||||
|
ClaudeHooks,
|
||||||
|
start_estimate,
|
||||||
|
)
|
||||||
|
from diet_guard.tests._claude_redirects import RealIoBlockedError
|
||||||
|
|
||||||
|
EST = Estimate("Owsianka z bananem", 320.0, 410.0, 15.0, 70.0, 8.0)
|
||||||
|
|
||||||
|
|
||||||
|
class Var:
|
||||||
|
"""The two StringVar methods the flow touches."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.value = g.CLAUDE
|
||||||
|
|
||||||
|
def get(self) -> str:
|
||||||
|
return self.value
|
||||||
|
|
||||||
|
def set(self, value: str) -> None:
|
||||||
|
self.value = value
|
||||||
|
|
||||||
|
|
||||||
|
class Harness:
|
||||||
|
"""A flow wired to recording hooks."""
|
||||||
|
|
||||||
|
def __init__(self, text: str = "owsianka", slot: int | None = 480) -> None:
|
||||||
|
self.root = MagicMock()
|
||||||
|
self.label = Var()
|
||||||
|
self.slot = slot
|
||||||
|
self.record = MagicMock()
|
||||||
|
self.status = MagicMock()
|
||||||
|
hooks = ClaudeHooks(lambda: text, self.status, lambda: self.slot, self.record)
|
||||||
|
self.flow = ClaudeFlow(self.root, self.label, hooks)
|
||||||
|
|
||||||
|
def click_with(self, outcome: Estimate | None) -> queue.Queue[Estimate | None]:
|
||||||
|
"""Click with a worker whose result is already on the queue."""
|
||||||
|
result: queue.Queue[Estimate | None] = queue.Queue(maxsize=1)
|
||||||
|
result.put(outcome)
|
||||||
|
with patch.object(_gatelock_claude, "start_estimate", return_value=result):
|
||||||
|
self.flow.click()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
class TestClick:
|
||||||
|
"""What a click does before any result exists."""
|
||||||
|
|
||||||
|
def test_empty_description_never_calls_claude(self) -> None:
|
||||||
|
h = Harness(text="")
|
||||||
|
with patch.object(_gatelock_claude, "start_estimate") as start:
|
||||||
|
h.flow.click()
|
||||||
|
start.assert_not_called()
|
||||||
|
assert h.status.call_args.kwargs == {"error": True}
|
||||||
|
assert h.label.get() == g.CLAUDE
|
||||||
|
|
||||||
|
def test_working_shows_the_spinner_and_polls(self) -> None:
|
||||||
|
h = Harness()
|
||||||
|
h.click_with(EST)
|
||||||
|
assert h.label.get() in g.CLAUDE_BUSY
|
||||||
|
h.root.after.assert_called_once()
|
||||||
|
|
||||||
|
def test_a_second_click_while_working_is_ignored(self) -> None:
|
||||||
|
h = Harness()
|
||||||
|
h.click_with(EST)
|
||||||
|
with patch.object(_gatelock_claude, "start_estimate") as start:
|
||||||
|
h.flow.click()
|
||||||
|
start.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
class TestPoll:
|
||||||
|
"""What the poll does with each outcome."""
|
||||||
|
|
||||||
|
def test_success_logs_with_source_claude(self) -> None:
|
||||||
|
h = Harness()
|
||||||
|
h.click_with(EST)
|
||||||
|
h.flow._poll()
|
||||||
|
(desc, nutrition), _ = h.record.call_args
|
||||||
|
assert desc == EST.desc
|
||||||
|
assert (nutrition.kcal, nutrition.grams, nutrition.source) == (
|
||||||
|
410.0,
|
||||||
|
320.0,
|
||||||
|
"claude",
|
||||||
|
)
|
||||||
|
assert h.label.get() == g.CLAUDE
|
||||||
|
|
||||||
|
def test_pending_result_keeps_polling(self) -> None:
|
||||||
|
h = Harness()
|
||||||
|
with patch.object(_gatelock_claude, "start_estimate") as start:
|
||||||
|
start.return_value = queue.Queue(maxsize=1)
|
||||||
|
h.flow.click()
|
||||||
|
h.root.after.reset_mock()
|
||||||
|
h.flow._poll()
|
||||||
|
h.root.after.assert_called_once()
|
||||||
|
h.record.assert_not_called()
|
||||||
|
|
||||||
|
def test_failure_shows_the_error_icon_and_logs_nothing(self) -> None:
|
||||||
|
h = Harness()
|
||||||
|
h.click_with(None)
|
||||||
|
h.flow._poll()
|
||||||
|
assert h.label.get() == g.CLAUDE_FAILED
|
||||||
|
h.record.assert_not_called()
|
||||||
|
|
||||||
|
def test_failure_leaves_the_flow_usable(self) -> None:
|
||||||
|
h = Harness()
|
||||||
|
h.click_with(None)
|
||||||
|
h.flow._poll()
|
||||||
|
h.click_with(EST)
|
||||||
|
h.flow._poll()
|
||||||
|
h.record.assert_called_once()
|
||||||
|
|
||||||
|
def test_timeout_fails_even_without_a_result(self) -> None:
|
||||||
|
h = Harness()
|
||||||
|
start = time.monotonic()
|
||||||
|
with (
|
||||||
|
patch.object(_gatelock_claude, "monotonic", return_value=start),
|
||||||
|
patch.object(_gatelock_claude, "start_estimate") as worker,
|
||||||
|
):
|
||||||
|
worker.return_value = queue.Queue(maxsize=1)
|
||||||
|
h.flow.click()
|
||||||
|
late = start + CLAUDE_TIMEOUT_S + 1
|
||||||
|
with patch.object(_gatelock_claude, "monotonic", return_value=late):
|
||||||
|
h.flow._poll()
|
||||||
|
assert h.label.get() == g.CLAUDE_FAILED
|
||||||
|
h.record.assert_not_called()
|
||||||
|
|
||||||
|
def test_hard_timeout_is_at_most_45_seconds(self) -> None:
|
||||||
|
assert CLAUDE_TIMEOUT_S <= 45.0
|
||||||
|
|
||||||
|
def test_result_for_a_slot_already_advanced_is_dropped(self) -> None:
|
||||||
|
"""The user logged the slot by hand while Claude was thinking."""
|
||||||
|
h = Harness(slot=480)
|
||||||
|
h.click_with(EST)
|
||||||
|
h.slot = 720
|
||||||
|
h.flow._poll()
|
||||||
|
h.record.assert_not_called()
|
||||||
|
assert h.label.get() == g.CLAUDE
|
||||||
|
|
||||||
|
def test_a_record_error_still_resets_the_button(self) -> None:
|
||||||
|
h = Harness()
|
||||||
|
h.record.side_effect = OSError("disk")
|
||||||
|
h.click_with(EST)
|
||||||
|
with pytest.raises(OSError, match="disk"):
|
||||||
|
h.flow._poll()
|
||||||
|
assert h.label.get() == g.CLAUDE
|
||||||
|
h.click_with(EST) # not stuck "in flight"
|
||||||
|
|
||||||
|
def test_a_stray_poll_after_completion_does_nothing(self) -> None:
|
||||||
|
h = Harness()
|
||||||
|
h.flow._poll()
|
||||||
|
h.root.after.assert_not_called()
|
||||||
|
h.record.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
class TestWorker:
|
||||||
|
"""The real thread, with a fake estimator."""
|
||||||
|
|
||||||
|
def test_returns_the_estimate(self) -> None:
|
||||||
|
with patch.object(_gatelock_claude, "estimate_meal", return_value=EST) as fn:
|
||||||
|
result = start_estimate("owsianka")
|
||||||
|
assert result.get(timeout=2) == EST
|
||||||
|
fn.assert_called_once_with("owsianka", None) # text only, no photo
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"error", [EstimateError("estimate_failed", "x"), ValueError("y"), OSError("z")]
|
||||||
|
)
|
||||||
|
def test_any_failure_is_none_never_a_hang(self, error: Exception) -> None:
|
||||||
|
with patch.object(_gatelock_claude, "estimate_meal", side_effect=error):
|
||||||
|
assert start_estimate("owsianka").get(timeout=2) is None
|
||||||
|
|
||||||
|
def test_the_default_seam_fails_closed(self) -> None:
|
||||||
|
"""conftest blocks the estimator: a test reaching it cannot spend quota."""
|
||||||
|
estimate: Any = _gatelock_claude.estimate_meal
|
||||||
|
with pytest.raises(RealIoBlockedError):
|
||||||
|
estimate("x", None)
|
||||||
|
assert start_estimate("x").get(timeout=2) is None
|
||||||
|
|
||||||
|
def test_the_estimator_import_is_lazy(self) -> None:
|
||||||
|
assert not hasattr(_gatelock_claude, "nonsense")
|
||||||
97
diet_guard/tests/test_gatelock_claude_gate.py
Normal file
97
diet_guard/tests/test_gatelock_claude_gate.py
Normal file
@ -0,0 +1,97 @@
|
|||||||
|
"""The Claude button wired into the real gate: the log, the unlock, the layout."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import queue
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from diet_guard import _gatelock_claude, _gatelock_layout
|
||||||
|
from diet_guard import _gatelock_glyphs as g
|
||||||
|
from diet_guard._gatelock import MealGate
|
||||||
|
from diet_guard._gatelock_mealflow import _UNLOCK_DELAY_MS
|
||||||
|
from diet_guard._slot_wire import entry_slot_minute
|
||||||
|
from diet_guard._state_sync import read_raw_log
|
||||||
|
from diet_guard.tests._gate_fixtures import fake_tk
|
||||||
|
from diet_guard.tests.test_gatelock_claude import EST
|
||||||
|
|
||||||
|
|
||||||
|
def _entries() -> list[dict[str, object]]:
|
||||||
|
return [e for day in read_raw_log().values() for e in day]
|
||||||
|
|
||||||
|
|
||||||
|
def _click(gate: MealGate, outcome: object) -> None:
|
||||||
|
result: queue.Queue[object] = queue.Queue(maxsize=1)
|
||||||
|
result.put(outcome)
|
||||||
|
with patch.object(_gatelock_claude, "start_estimate", return_value=result):
|
||||||
|
gate._on_claude()
|
||||||
|
gate._claude_flow._poll()
|
||||||
|
|
||||||
|
|
||||||
|
def test_success_logs_the_locked_slot_and_unlocks(gate: MealGate) -> None:
|
||||||
|
gate.demo_mode = False
|
||||||
|
gate._pending = [720]
|
||||||
|
gate._set_desc("owsianka z bananem")
|
||||||
|
_click(gate, EST)
|
||||||
|
(entry,) = _entries()
|
||||||
|
assert entry["source"] == "claude"
|
||||||
|
assert entry["desc"] == EST.desc
|
||||||
|
assert entry_slot_minute(entry) == 720
|
||||||
|
assert gate._pending == []
|
||||||
|
gate.root.after.assert_called_with(_UNLOCK_DELAY_MS, gate.close)
|
||||||
|
|
||||||
|
|
||||||
|
def test_success_with_more_slots_advances_instead_of_unlocking(
|
||||||
|
gate: MealGate,
|
||||||
|
) -> None:
|
||||||
|
gate.demo_mode = False
|
||||||
|
gate._pending = [480, 720]
|
||||||
|
gate._set_desc("owsianka")
|
||||||
|
_click(gate, EST)
|
||||||
|
assert gate._pending == [720]
|
||||||
|
assert entry_slot_minute(_entries()[0]) == 480
|
||||||
|
|
||||||
|
|
||||||
|
def test_failure_leaves_the_manual_path_usable(gate: MealGate) -> None:
|
||||||
|
gate.demo_mode = False
|
||||||
|
gate._pending = [480]
|
||||||
|
gate._set_desc("owsianka")
|
||||||
|
_click(gate, None)
|
||||||
|
assert _entries() == []
|
||||||
|
assert gate._pending == [480]
|
||||||
|
assert gate._vars.claude_label.get() == g.CLAUDE_FAILED
|
||||||
|
# The ordinary submit still logs and unlocks.
|
||||||
|
gate._macro_entries()[0].insert(0, "300")
|
||||||
|
gate._on_submit()
|
||||||
|
assert gate._pending == [] or _entries()
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_flow_is_built_once_per_gate(gate: MealGate) -> None:
|
||||||
|
gate._set_desc("x")
|
||||||
|
_click(gate, None)
|
||||||
|
first = gate._claude_flow
|
||||||
|
_click(gate, None)
|
||||||
|
assert gate._claude_flow is first
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_button_is_wired_on_every_monitor(gate: MealGate) -> None:
|
||||||
|
built: list[object] = []
|
||||||
|
real = _gatelock_layout.make_button
|
||||||
|
|
||||||
|
def record(*args: object, **kwargs: object) -> object:
|
||||||
|
button = real(*args, **kwargs)
|
||||||
|
built.append(button)
|
||||||
|
return button
|
||||||
|
|
||||||
|
with (
|
||||||
|
fake_tk(),
|
||||||
|
patch.object(_gatelock_layout, "make_button", side_effect=record),
|
||||||
|
):
|
||||||
|
wired = MealGate(demo_mode=True)
|
||||||
|
claude = [
|
||||||
|
b
|
||||||
|
for b in built
|
||||||
|
if getattr(b, "configured", {}).get("textvariable") is wired._vars.claude_label
|
||||||
|
]
|
||||||
|
assert claude # one per output, all on one shared variable
|
||||||
|
assert all(b.configured["command"] == wired._on_claude for b in claude)
|
||||||
|
assert wired._vars.claude_label.get() == g.CLAUDE
|
||||||
@ -181,7 +181,9 @@ class TestTheButton:
|
|||||||
root.withdraw()
|
root.withdraw()
|
||||||
on_fill_all = MagicMock()
|
on_fill_all = MagicMock()
|
||||||
callbacks = GateCallbacks(
|
callbacks = GateCallbacks(
|
||||||
*(MagicMock() for _ in range(5)), on_fill_all=on_fill_all
|
*(MagicMock() for _ in range(5)),
|
||||||
|
on_fill_all=on_fill_all,
|
||||||
|
on_claude=MagicMock(),
|
||||||
)
|
)
|
||||||
vars_ = make_vars(root)
|
vars_ = make_vars(root)
|
||||||
notebook = ttk.Notebook(root)
|
notebook = ttk.Notebook(root)
|
||||||
|
|||||||
@ -186,6 +186,17 @@ class TestShouldLockAutologs:
|
|||||||
assert _cli_gate._should_lock([].append) is False
|
assert _cli_gate._should_lock([].append) is False
|
||||||
publish.assert_called_once()
|
publish.assert_called_once()
|
||||||
|
|
||||||
|
def test_publish_outage_is_reported_not_fatal(self) -> None:
|
||||||
|
"""The entry is local and durable; only the publish is late."""
|
||||||
|
lines: list[str] = []
|
||||||
|
with (
|
||||||
|
patch.object(_cli_gate, "gate_is_due", side_effect=[True, False]),
|
||||||
|
patch.object(_cli_gate, "autolog_due_delivery", return_value=1),
|
||||||
|
patch.object(_cli_gate, "publish_after_log", return_value="offline"),
|
||||||
|
):
|
||||||
|
assert _cli_gate._should_lock(lines.append) is False
|
||||||
|
assert "offline" in lines[0]
|
||||||
|
|
||||||
def test_failed_autolog_still_locks(self) -> None:
|
def test_failed_autolog_still_locks(self) -> None:
|
||||||
"""Nothing written, still due: the lock opens, no publish."""
|
"""Nothing written, still due: the lock opens, no publish."""
|
||||||
publish = MagicMock(return_value=None)
|
publish = MagicMock(return_value=None)
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user