Drop gaming from credit toast and poke

Pin earned-time-v0.22.0. The toast and the poke reply show only the
shutdown gain; gaming_budget_minutes leaves the reply and the phone
app's result line (an older PC's field is ignored).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWViGJJaqBKGr1Hbppr
This commit is contained in:
Krzysztof Rudnicki 2026-11-16 16:13:46 +01:00
parent 8e52688138
commit ad849aff02
22 changed files with 55 additions and 160 deletions

View File

@ -143,7 +143,7 @@ repos:
# than merely an old one. # than merely an old one.
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.12.0#subdirectory=gatelock - gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.12.0#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync - crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.21.0#subdirectory=earned_time - earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.22.0#subdirectory=earned_time
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays - freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.4#subdirectory=sickdays - sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.4#subdirectory=sickdays
# Same pin as workout_app/tools/render_finish_chime.sh installs. # Same pin as workout_app/tools/render_finish_chime.sh installs.
@ -166,7 +166,7 @@ repos:
# than merely an old one. # than merely an old one.
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.12.0#subdirectory=gatelock - gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.12.0#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync - crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.21.0#subdirectory=earned_time - earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.22.0#subdirectory=earned_time
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays - freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.4#subdirectory=sickdays - sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.4#subdirectory=sickdays
- mcp>=2,<3 - mcp>=2,<3

View File

@ -1,7 +1,7 @@
# Workout poke: phone -> PC wire contract (v1) # Workout poke: phone -> PC wire contract (v1)
The phone sends a finished StrongLifts session straight to the PC over the The phone sends a finished StrongLifts session straight to the PC over the
home LAN, so the credit (shutdown time, gaming budget, notification) lands in home LAN, so the credit (shutdown time, notification) lands in
under a second instead of waiting for the GitHub/Firebase round trip. The under a second instead of waiting for the GitHub/Firebase round trip. The
normal sync push still runs in parallel; the PC dedups by record id, so a normal sync push still runs in parallel; the PC dedups by record id, so a
session that arrives both ways is credited once. session that arrives both ways is credited once.
@ -45,11 +45,13 @@ session that arrives both ways is credited once.
```json ```json
{"ok":<bool>,"credited":<bool>,"duplicate":<bool>,"sandbox":<bool>, {"ok":<bool>,"credited":<bool>,"duplicate":<bool>,"sandbox":<bool>,
"shutdown":"HH:MM"|null,"gaming_budget_minutes":<int|null>,"pc_ms":<int>, "shutdown":"HH:MM"|null,"pc_ms":<int>,
"reason":"<sentence a human can act on>"} "reason":"<sentence a human can act on>"}
``` ```
The phone must treat `shutdown` and `gaming_budget_minutes` as nullable. The phone must treat `shutdown` as nullable. `gaming_budget_minutes` was dropped
when the gaming budget was removed (2026-11-16); a phone ignores it if an older
PC still sends it.
Outcomes of a verified (200) request: Outcomes of a verified (200) request:
@ -64,8 +66,8 @@ Outcomes of a verified (200) request:
Refusals are never 200. Besides the four checks above, the PC may answer Refusals are never 200. Besides the four checks above, the PC may answer
`404` (wrong path), `405` (not POST), `411` (no Content-Length), `413` (body `404` (wrong path), `405` (not POST), `411` (no Content-Length), `413` (body
over 64 KiB) and `500` (internal error; the regular sync still credits). All over 64 KiB) and `500` (internal error; the regular sync still credits). All
of them carry the same JSON shape with `ok:false` and `shutdown` and of them carry the same JSON shape with `ok:false` and `shutdown`
`gaming_budget_minutes` both `null`. The PC answers a `413` without reading `null`. The PC answers a `413` without reading
the body, so the phone may see a connection reset instead of the reply. the body, so the phone may see a connection reset instead of the reply.
## Shared fixture ## Shared fixture

View File

@ -10,7 +10,7 @@ dependencies = [
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.14.0#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", "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", "freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays",
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.21.0#subdirectory=earned_time", "earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.22.0#subdirectory=earned_time",
"holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds", "holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds",
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.4#subdirectory=sickdays", "sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.4#subdirectory=sickdays",
] ]

View File

@ -4,7 +4,7 @@ bandit==1.9.4
codespell==2.4.3 codespell==2.4.3
coverage==7.17.3 coverage==7.17.3
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.21.0#subdirectory=earned_time earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.22.0#subdirectory=earned_time
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays 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 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 holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds

View File

@ -6,11 +6,8 @@ that credits a workout ends in
:meth:`~screen_locker._workout_credit.WorkoutCreditMixin._apply_credit_for_written_entry`, :meth:`~screen_locker._workout_credit.WorkoutCreditMixin._apply_credit_for_written_entry`,
which calls :func:`notify_workout_credit` once per newly earned credit slot. which calls :func:`notify_workout_credit` once per newly earned credit slot.
The gaming figure is ``earned_time.resolve`` over screen-locker's own answers The body shows the shutdown only: the gaming budget is gone (earned_time
(:func:`screen_locker._shutdown_target.gather` -- the same sum the daily reset 0.22.0), so there is no second figure to feel.
writes), so no budget math lives here. steam-backlog-enforcer resolves the
same registry with its own transports and holds a day's high-water mark, so
its figure can sit above this one, never below on a normal day.
A notification is a courtesy, never part of crediting: any failure (no DBus, A notification is a courtesy, never part of crediting: any failure (no DBus,
no notify-send, a hang) is logged at warning and swallowed. no notify-send, a hang) is logged at warning and swallowed.
@ -22,52 +19,27 @@ from datetime import date
import logging import logging
import shutil import shutil
import subprocess import subprocess
from typing import TYPE_CHECKING, Final from typing import Final
from screen_locker._day import today_str from screen_locker._day import today_str
from screen_locker._earned import hhmm, span from screen_locker._earned import hhmm, span
from screen_locker._grace_floor import tonight_minutes from screen_locker._grace_floor import tonight_minutes
from screen_locker._shutdown_target import gather
if TYPE_CHECKING:
from pathlib import Path
_logger: Final = logging.getLogger(__name__) _logger: Final = logging.getLogger(__name__)
# textgate: glyphs + numbers (colour emoji are safe in the notification # textgate: glyphs + numbers (colour emoji are safe in the notification
# daemon, unlike Tk). Was "Workout credited 💪" / "Shutdown 23:00 (+2h) · # daemon, unlike Tk). Was "Workout credited 💪" / "Shutdown 23:00 (+2h)" /
# gaming 7.0h" / "Credit applied (details unavailable)". # "Credit applied (details unavailable)".
TITLE: Final = "\N{FLEXED BICEPS} \N{CHECK MARK}" TITLE: Final = "\N{FLEXED BICEPS} \N{CHECK MARK}"
_SHUTDOWN: Final = "\N{POWER SYMBOL}" _SHUTDOWN: Final = "\N{POWER SYMBOL}"
_GAMING: Final = "\N{VIDEO GAME}"
_NOTIFY_TIMEOUT_SECONDS: Final = 5 _NOTIFY_TIMEOUT_SECONDS: Final = 5
_MINUTES_PER_HOUR: Final = 60.0
def gaming_minutes_today(log_file: Path | None) -> int | None:
"""Today's gaming budget per the earned_time registry, or ``None``.
``None`` (logged) when the inputs cannot be read; the notification then
shows the shutdown time alone.
"""
try:
target = gather(date.fromisoformat(today_str()), log_file)
except (OSError, ValueError, KeyError) as exc:
_logger.warning(
"Could not compute today's gaming budget for the credit "
"notification (%s) — showing the shutdown time only",
exc,
)
return None
return int(target.resolution.gaming_minutes)
def credit_body( def credit_body(
before: tuple[int, int, int] | None, before: tuple[int, int, int] | None,
after: tuple[int, int, int] | None, after: tuple[int, int, int] | None,
gaming_minutes: int | None,
) -> str: ) -> str:
"""``⏻ 23:00 (+2h) · 🎮 7.0h`` -- whichever parts are known. """``⏻ 23:00 (+2h)`` -- whichever parts are known.
``before``/``after`` are the shutdown config around the credit; the delta ``before``/``after`` are the shutdown config around the credit; the delta
is tonight's actual move, so a capped or rest-day credit shows ``+0h``. is tonight's actual move, so a capped or rest-day credit shows ``+0h``.
@ -86,8 +58,6 @@ def credit_body(
moved = max(0, tonight - tonight_minutes(before, day)) moved = max(0, tonight - tonight_minutes(before, day))
text += f" (+{span(moved)})" text += f" (+{span(moved)})"
parts.append(text) parts.append(text)
if gaming_minutes is not None:
parts.append(f"{_GAMING} {gaming_minutes / _MINUTES_PER_HOUR:.1f}h")
return " \N{MIDDLE DOT} ".join(parts) or "\N{CHECK MARK}" return " \N{MIDDLE DOT} ".join(parts) or "\N{CHECK MARK}"
@ -123,8 +93,7 @@ def send_notification(title: str, body: str) -> bool:
def notify_workout_credit( def notify_workout_credit(
before: tuple[int, int, int] | None, before: tuple[int, int, int] | None,
after: tuple[int, int, int] | None, after: tuple[int, int, int] | None,
log_file: Path | None,
) -> bool: ) -> bool:
"""Notify a newly earned workout credit. Never raises.""" """Notify a newly earned workout credit. Never raises."""
body = credit_body(before, after, gaming_minutes_today(log_file)) body = credit_body(before, after)
return send_notification(TITLE, body) return send_notification(TITLE, body)

View File

@ -25,7 +25,6 @@ from screen_locker._constants import (
SHUTDOWN_BASE_FILE, SHUTDOWN_BASE_FILE,
SHUTDOWN_CONFIG_FILE, SHUTDOWN_CONFIG_FILE,
) )
from screen_locker._credit_notify import gaming_minutes_today
from screen_locker._day import today_str from screen_locker._day import today_str
from screen_locker._earned import hhmm from screen_locker._earned import hhmm
from screen_locker._extra_benefits import process_week_transition from screen_locker._extra_benefits import process_week_transition
@ -38,7 +37,6 @@ from screen_locker.screen_lock import ScreenLocker
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Iterable, Mapping from collections.abc import Iterable, Mapping
from pathlib import Path
from screen_locker._workout_credit import WorkoutCreditResult from screen_locker._workout_credit import WorkoutCreditResult
@ -49,7 +47,6 @@ __all__ = [
"credit_manual_workouts", "credit_manual_workouts",
"credit_session", "credit_session",
"credit_sessions", "credit_sessions",
"current_gaming_minutes",
"current_shutdown", "current_shutdown",
] ]
@ -120,11 +117,6 @@ def current_shutdown() -> str | None:
return hhmm(tonight_minutes(config, date.fromisoformat(today_str()))) return hhmm(tonight_minutes(config, date.fromisoformat(today_str())))
def current_gaming_minutes(log_file: Path) -> int | None:
"""Today's gaming budget (``None`` and a warning when it cannot be summed)."""
return gaming_minutes_today(log_file)
def _precheck(record_id: str, payload: Mapping[str, object]) -> str | None: def _precheck(record_id: str, payload: Mapping[str, object]) -> str | None:
"""Why the session can never count, or ``None`` if it can. """Why the session can never count, or ``None`` if it can.

View File

@ -46,21 +46,19 @@ def _reply(
outcome: _poke_credit.PokeOutcome, outcome: _poke_credit.PokeOutcome,
*, *,
sandbox: bool = False, sandbox: bool = False,
snapshot: tuple[str | None, int | None] = (None, None), shutdown: str | None = None,
) -> dict[str, object]: ) -> dict[str, object]:
"""The contract's response shape; ``pc_ms`` is filled in by the handler. """The contract's response shape; ``pc_ms`` is filled in by the handler.
``snapshot`` is (tonight's shutdown ``HH:MM``, gaming minutes); refusals ``shutdown`` is tonight's shutdown ``HH:MM``; refusals leave it null
leave it null rather than tell an unverified caller anything. rather than tell an unverified caller anything.
""" """
shutdown, gaming = snapshot
return { return {
"ok": outcome.ok, "ok": outcome.ok,
"credited": outcome.credited, "credited": outcome.credited,
"duplicate": outcome.duplicate, "duplicate": outcome.duplicate,
"sandbox": sandbox, "sandbox": sandbox,
"shutdown": shutdown, "shutdown": shutdown,
"gaming_budget_minutes": gaming,
"pc_ms": 0, "pc_ms": 0,
"reason": outcome.reason, "reason": outcome.reason,
} }
@ -77,7 +75,6 @@ def _refused(reason: str) -> dict[str, object]:
def _process(request: PokeRequest) -> dict[str, object]: def _process(request: PokeRequest) -> dict[str, object]:
"""Credit (or, for a sandbox request, only answer) one verified poke.""" """Credit (or, for a sandbox request, only answer) one verified poke."""
locker = _poke_credit.fresh_locker()
if request.sandbox: if request.sandbox:
outcome = _poke_credit.PokeOutcome( outcome = _poke_credit.PokeOutcome(
ok=True, ok=True,
@ -90,10 +87,7 @@ def _process(request: PokeRequest) -> dict[str, object]:
return _reply( return _reply(
outcome, outcome,
sandbox=request.sandbox, sandbox=request.sandbox,
snapshot=( shutdown=_poke_credit.current_shutdown(),
_poke_credit.current_shutdown(),
_poke_credit.current_gaming_minutes(locker.log_file),
),
) )

View File

@ -182,7 +182,7 @@ class WorkoutCreditMixin:
batch uncredited, so every exception is logged and dropped here. batch uncredited, so every exception is logged and dropped here.
""" """
try: try:
_credit_notify.notify_workout_credit(before, after, self.log_file) _credit_notify.notify_workout_credit(before, after)
except Exception: # pylint: disable=broad-exception-caught # notification must never fail the credit except Exception: # pylint: disable=broad-exception-caught # notification must never fail the credit
_logger.exception( _logger.exception(
"Workout credit notification failed — the credit itself is " "Workout credit notification failed — the credit itself is "

View File

@ -87,10 +87,8 @@ def main(argv: list[str] | None = None) -> int:
except (OSError, ValueError) as exc: except (OSError, ValueError) as exc:
_logger.critical("Refusing to start: bad poke key (%s); %s", exc, _KEYGEN_HINT) _logger.critical("Refusing to start: bad poke key (%s); %s", exc, _KEYGEN_HINT)
return 1 return 1
# Warm the budget sum (registry, ledgers) and the conf read once, so the # Warm the conf read once, so the first poke costs what every later one does.
# first poke costs what every later one does.
_poke_credit.current_shutdown() _poke_credit.current_shutdown()
_poke_credit.current_gaming_minutes(_poke_credit.fresh_locker().log_file)
try: try:
server = PokeServer((args.bind, args.port), key) server = PokeServer((args.bind, args.port), key)
except OSError as exc: except OSError as exc:

View File

@ -9,7 +9,6 @@ from __future__ import annotations
import logging import logging
import subprocess import subprocess
from types import SimpleNamespace
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
@ -20,7 +19,6 @@ from screen_locker.tests.conftest import create_locker
# The toast's glyphs (textgate): the module's own constants, not words. # The toast's glyphs (textgate): the module's own constants, not words.
_SHUTDOWN = _credit_notify._SHUTDOWN _SHUTDOWN = _credit_notify._SHUTDOWN
_GAMING = _credit_notify._GAMING
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Iterator from collections.abc import Iterator
@ -44,54 +42,34 @@ def _warned(caplog: pytest.LogCaptureFixture, needle: str) -> bool:
) )
class TestGamingMinutes:
"""The budget figure, or None when its inputs cannot be read."""
def test_returns_the_registry_figure(self) -> None:
"""gather's resolution is shown as whole minutes."""
target = SimpleNamespace(resolution=SimpleNamespace(gaming_minutes=420.0))
with patch(f"{_MOD}.gather", return_value=target):
assert _credit_notify.gaming_minutes_today(None) == 420
def test_unreadable_inputs_warn_and_return_none(
self, caplog: pytest.LogCaptureFixture
) -> None:
"""A broken ledger costs the figure, not the notification."""
with patch(f"{_MOD}.gather", side_effect=OSError("ledger gone")):
assert _credit_notify.gaming_minutes_today(None) is None
assert _warned(caplog, "ledger gone")
class TestCreditBody: class TestCreditBody:
"""Whichever parts are known end up in the body.""" """Whichever parts are known end up in the body."""
def test_full_body(self) -> None: def test_full_body(self) -> None:
"""Shutdown time, tonight's move and the gaming budget.""" """Shutdown time and tonight's move; no gaming figure any more."""
body = _credit_notify.credit_body((0, 1200, 0), (0, 1320, 0), 420) body = _credit_notify.credit_body((0, 1200, 0), (0, 1320, 0))
assert body == f"{_SHUTDOWN} 22:00 (+2h) \N{MIDDLE DOT} {_GAMING} 7.0h" assert body == f"{_SHUTDOWN} 22:00 (+2h)"
def test_a_capped_credit_shows_plus_zero(self) -> None: def test_a_capped_credit_shows_plus_zero(self) -> None:
"""No backwards move is ever shown: the delta floors at zero.""" """No backwards move is ever shown: the delta floors at zero."""
body = _credit_notify.credit_body((0, 1380, 0), (0, 1320, 0), None) body = _credit_notify.credit_body((0, 1380, 0), (0, 1320, 0))
assert body == f"{_SHUTDOWN} 22:00 (+0h)" assert body == f"{_SHUTDOWN} 22:00 (+0h)"
def test_unknown_before_drops_the_delta(self) -> None: def test_unknown_before_drops_the_delta(self) -> None:
"""Without the old config there is no move to show.""" """Without the old config there is no move to show."""
assert ( assert _credit_notify.credit_body(None, (0, 1320, 0)) == f"{_SHUTDOWN} 22:00"
_credit_notify.credit_body(None, (0, 1320, 0), None) == f"{_SHUTDOWN} 22:00"
)
def test_unreadable_after_warns_and_shows_gaming_only( def test_unreadable_after_warns_and_shows_the_check_mark(
self, caplog: pytest.LogCaptureFixture self, caplog: pytest.LogCaptureFixture
) -> None: ) -> None:
"""An unreadable config is said out loud, not silently omitted.""" """An unreadable config is said out loud, not silently omitted."""
assert _credit_notify.credit_body(None, None, 90) == f"{_GAMING} 1.5h" assert _credit_notify.credit_body(None, None) == "\N{CHECK MARK}"
assert _warned(caplog, "unreadable") assert _warned(caplog, "unreadable")
def test_nothing_known_still_says_something(self) -> None: def test_the_gaming_figure_is_gone(self) -> None:
"""An empty body would read as a glitch; say the credit happened.""" """No budget exists any more: the body never mentions gaming."""
body = _credit_notify.credit_body(None, None, None) assert not hasattr(_credit_notify, "gaming_minutes_today")
assert body == "\N{CHECK MARK}" assert not hasattr(_credit_notify, "_GAMING")
class TestSendNotification: class TestSendNotification:
@ -152,13 +130,10 @@ class TestSendNotification:
def test_notify_workout_credit_sends_the_composed_body() -> None: def test_notify_workout_credit_sends_the_composed_body() -> None:
"""The real entry point composes the body and sends it once.""" """The real entry point composes the body and sends it once."""
with ( with (
patch(f"{_MOD}.gaming_minutes_today", return_value=60),
patch(f"{_MOD}.send_notification", return_value=True) as send, patch(f"{_MOD}.send_notification", return_value=True) as send,
): ):
assert _real_notify((0, 1200, 0), (0, 1260, 0), None) assert _real_notify((0, 1200, 0), (0, 1260, 0))
send.assert_called_once_with( send.assert_called_once_with(_credit_notify.TITLE, f"{_SHUTDOWN} 21:00 (+1h)")
_credit_notify.TITLE, f"{_SHUTDOWN} 21:00 (+1h) \N{MIDDLE DOT} {_GAMING} 1.0h"
)
class TestCreditSideOfTheNotifier: class TestCreditSideOfTheNotifier:

View File

@ -129,7 +129,7 @@ class TestSlotCreditMinutes:
result, notify = _credit(locker, []) result, notify = _credit(locker, [])
assert result.shutdown_adjusted is True assert result.shutdown_adjusted is True
assert locker._read_shutdown_config() == (1320, 1320, 300) assert locker._read_shutdown_config() == (1320, 1320, 300)
notify.assert_called_once_with(_START, (1320, 1320, 300), locker.log_file) notify.assert_called_once_with(_START, (1320, 1320, 300))
def test_distinct_slot_earns_one_hour( def test_distinct_slot_earns_one_hour(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path

View File

@ -84,7 +84,7 @@ class TestStartTheDay:
class TestSnapshots: class TestSnapshots:
"""Groups the shutdown and gaming-minutes values snapshotted into poke replies.""" """Groups the shutdown value snapshotted into poke replies."""
def test_current_shutdown_renders_tonights_time( def test_current_shutdown_renders_tonights_time(
self, monkeypatch: pytest.MonkeyPatch self, monkeypatch: pytest.MonkeyPatch
@ -102,18 +102,3 @@ class TestSnapshots:
with caplog.at_level(logging.WARNING): with caplog.at_level(logging.WARNING):
assert _poke_credit.current_shutdown() is None assert _poke_credit.current_shutdown() is None
assert "shutdown=null" in caplog.text assert "shutdown=null" in caplog.text
def test_current_gaming_minutes_delegates(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""current_gaming_minutes returns what gaming_minutes_today reports for the log."""
seen: list[Path] = []
def minutes(log: Path) -> int:
"""Record the log path asked about and return 90 minutes."""
seen.append(log)
return 90
monkeypatch.setattr(_poke_credit, "gaming_minutes_today", minutes)
assert _poke_credit.current_gaming_minutes(tmp_path / "log.json") == 90
assert seen == [tmp_path / "log.json"]

View File

@ -54,7 +54,6 @@ def _daemon_stubs(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
locker.log_file = tmp_path / "log.json" locker.log_file = tmp_path / "log.json"
monkeypatch.setattr(_poke_credit, "fresh_locker", lambda: locker) monkeypatch.setattr(_poke_credit, "fresh_locker", lambda: locker)
monkeypatch.setattr(_poke_credit, "current_shutdown", MagicMock()) monkeypatch.setattr(_poke_credit, "current_shutdown", MagicMock())
monkeypatch.setattr(_poke_credit, "current_gaming_minutes", MagicMock())
monkeypatch.setattr(poke_server, "PokeServer", FakeServer) monkeypatch.setattr(poke_server, "PokeServer", FakeServer)

View File

@ -49,7 +49,6 @@ def pc_fixture(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> dict[str, Mag
monkeypatch.setattr(_poke_credit, "ingest_session_records", spies["ingest"]) monkeypatch.setattr(_poke_credit, "ingest_session_records", spies["ingest"])
monkeypatch.setattr(_poke_credit, "credit_session", spies["credit"]) monkeypatch.setattr(_poke_credit, "credit_session", spies["credit"])
monkeypatch.setattr(_poke_credit, "current_shutdown", lambda: "20:30") monkeypatch.setattr(_poke_credit, "current_shutdown", lambda: "20:30")
monkeypatch.setattr(_poke_credit, "current_gaming_minutes", lambda _p: 75)
return spies return spies
@ -63,7 +62,7 @@ def test_sandbox_replies_ok_with_the_snapshot_and_nothing_credited(
assert reply["credited"] is False assert reply["credited"] is False
assert reply["duplicate"] is False assert reply["duplicate"] is False
assert reply["shutdown"] == "20:30" assert reply["shutdown"] == "20:30"
assert reply["gaming_budget_minutes"] == 75 assert "gaming_budget_minutes" not in reply
assert "nothing written or credited" in str(reply["reason"]) assert "nothing written or credited" in str(reply["reason"])

View File

@ -70,7 +70,6 @@ def credit_fixture(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> MagicMock
locker.log_file = tmp_path / "log.json" locker.log_file = tmp_path / "log.json"
monkeypatch.setattr(_poke_credit, "fresh_locker", lambda: locker) monkeypatch.setattr(_poke_credit, "fresh_locker", lambda: locker)
monkeypatch.setattr(_poke_credit, "current_shutdown", lambda: "20:30") monkeypatch.setattr(_poke_credit, "current_shutdown", lambda: "20:30")
monkeypatch.setattr(_poke_credit, "current_gaming_minutes", lambda _p: 75)
spy = MagicMock( spy = MagicMock(
return_value=_poke_credit.PokeOutcome( return_value=_poke_credit.PokeOutcome(
ok=True, credited=True, duplicate=False, reason="workout credited" ok=True, credited=True, duplicate=False, reason="workout credited"
@ -130,7 +129,7 @@ class TestCredit:
assert reply["duplicate"] is False assert reply["duplicate"] is False
assert reply["sandbox"] is False assert reply["sandbox"] is False
assert reply["shutdown"] == "20:30" assert reply["shutdown"] == "20:30"
assert reply["gaming_budget_minutes"] == 75 assert "gaming_budget_minutes" not in reply
assert isinstance(reply["pc_ms"], int) assert isinstance(reply["pc_ms"], int)
credit.assert_called_once_with( credit.assert_called_once_with(
"rec-1", {"date": "2026-10-09", "note": "zażółć"} "rec-1", {"date": "2026-10-09", "note": "zażółć"}

View File

@ -78,8 +78,9 @@ class TestRouting:
def test_reply_for_a_refusal_leaves_the_snapshot_null() -> None: def test_reply_for_a_refusal_leaves_the_snapshot_null() -> None:
"""A refusal reply carries no shutdown or gaming-budget snapshot.""" """A refusal reply carries no shutdown snapshot."""
reply = _poke_server._refused("nope") reply = _poke_server._refused("nope")
assert reply["ok"] is False assert reply["ok"] is False
assert (reply["shutdown"], reply["gaming_budget_minutes"]) == (None, None) assert reply["shutdown"] is None
assert "gaming_budget_minutes" not in reply
assert reply["reason"] == "nope" assert reply["reason"] == "nope"

View File

@ -37,15 +37,13 @@ class PokeResult {
required this.outcome, required this.outcome,
required this.reason, required this.reason,
this.shutdown, this.shutdown,
this.gamingBudgetMinutes,
this.roundTripMs, this.roundTripMs,
}); });
/// A failure that never got a usable reply. /// A failure that never got a usable reply.
const PokeResult.failed(this.reason, {this.roundTripMs}) const PokeResult.failed(this.reason, {this.roundTripMs})
: outcome = PokeOutcome.failed, : outcome = PokeOutcome.failed,
shutdown = null, shutdown = null;
gamingBudgetMinutes = null;
/// Parses the PC's JSON reply. Any shape the contract does not allow is a /// Parses the PC's JSON reply. Any shape the contract does not allow is a
/// [PokeOutcome.failed] naming what was wrong, not an exception. /// [PokeOutcome.failed] naming what was wrong, not an exception.
@ -81,8 +79,8 @@ class PokeResult {
roundTripMs: roundTripMs, roundTripMs: roundTripMs,
); );
} }
// shutdown / gaming_budget_minutes may be null (refusals): never assumed. // shutdown may be null (refusals): never assumed. An older PC also sends
final budget = decoded['gaming_budget_minutes']; // gaming_budget_minutes; the budget is gone, so the field is ignored.
final shutdown = decoded['shutdown']; final shutdown = decoded['shutdown'];
final PokeOutcome outcome; final PokeOutcome outcome;
if (decoded['ok'] != true) { if (decoded['ok'] != true) {
@ -100,7 +98,6 @@ class PokeResult {
outcome: outcome, outcome: outcome,
reason: reason, reason: reason,
shutdown: shutdown is String ? shutdown : null, shutdown: shutdown is String ? shutdown : null,
gamingBudgetMinutes: budget is int ? budget : null,
roundTripMs: roundTripMs, roundTripMs: roundTripMs,
); );
} }
@ -114,9 +111,6 @@ class PokeResult {
/// The PC's shutdown time after this poke, `HH:MM`. /// The PC's shutdown time after this poke, `HH:MM`.
final String? shutdown; final String? shutdown;
/// Today's gaming budget after this poke, in minutes.
final int? gamingBudgetMinutes;
/// Measured phone-side round trip, when a request was actually sent. /// Measured phone-side round trip, when a request was actually sent.
final int? roundTripMs; final int? roundTripMs;
@ -126,11 +120,7 @@ class PokeResult {
case PokeOutcome.credited: case PokeOutcome.credited:
final parts = <String>['PC ✓']; final parts = <String>['PC ✓'];
if (shutdown != null) parts.add('shutdown $shutdown'); if (shutdown != null) parts.add('shutdown $shutdown');
final minutes = gamingBudgetMinutes; return parts.join(' ');
final gaming = minutes == null
? ''
: ' · gaming ${(minutes / 60).toStringAsFixed(1)}h';
return '${parts.join(' ')}$gaming';
case PokeOutcome.duplicate: case PokeOutcome.duplicate:
return 'PC: already credited'; return 'PC: already credited';
case PokeOutcome.sandbox: case PokeOutcome.sandbox:

View File

@ -63,7 +63,6 @@ class PcPokeLine extends StatelessWidget {
PokeOutcome.failed => Icons.schedule, PokeOutcome.failed => Icons.schedule,
}; };
final style = TextStyle(color: color, fontSize: AppTextSize.caption); final style = TextStyle(color: color, fontSize: AppTextSize.caption);
final minutes = result.gamingBudgetMinutes;
return Semantics( return Semantics(
label: result.label, label: result.label,
excludeSemantics: true, excludeSemantics: true,
@ -80,11 +79,6 @@ class PcPokeLine extends StatelessWidget {
Icon(Icons.power_settings_new, size: 14, color: color), Icon(Icons.power_settings_new, size: 14, color: color),
Text(' ${result.shutdown}', style: style), Text(' ${result.shutdown}', style: style),
], ],
if (minutes != null) ...[
const SizedBox(width: AppSpacing.sm),
Icon(Icons.sports_esports, size: 14, color: color),
Text(' ${(minutes / 60).toStringAsFixed(1)}h', style: style),
],
], ],
// Sandbox: the round trip in milliseconds behind a timer glyph. // Sandbox: the round trip in milliseconds behind a timer glyph.
if (result.outcome == PokeOutcome.sandbox) ...[ if (result.outcome == PokeOutcome.sandbox) ...[

View File

@ -24,10 +24,11 @@ String _reply({
}); });
void main() { void main() {
test('credited shows shutdown and gaming hours', () { // A PC older than 2026-11-16 still sends gaming_budget_minutes: ignored.
test('credited shows the shutdown only', () {
final r = PokeResult.fromReply(200, _reply(credited: true), 40); final r = PokeResult.fromReply(200, _reply(credited: true), 40);
expect(r.outcome, PokeOutcome.credited); expect(r.outcome, PokeOutcome.credited);
expect(r.label, 'PC ✓ shutdown 21:00 · gaming 1.5h'); expect(r.label, 'PC ✓ shutdown 21:00');
}); });
test('credited with null shutdown/budget still renders', () { test('credited with null shutdown/budget still renders', () {

View File

@ -92,7 +92,7 @@ void main() {
final result = await _service(client, sandbox: false).poke(_session()); final result = await _service(client, sandbox: false).poke(_session());
expect(result.outcome, PokeOutcome.credited); expect(result.outcome, PokeOutcome.credited);
expect(result.label, 'PC ✓ shutdown 22:00 · gaming 2.0h'); expect(result.label, 'PC ✓ shutdown 22:00');
expect(result.roundTripMs, isNotNull); expect(result.roundTripMs, isNotNull);
expect(seen.url.toString(), 'http://10.0.0.7:$kPcPokePort$kPcPokePath'); expect(seen.url.toString(), 'http://10.0.0.7:$kPcPokePort$kPcPokePath');
expect( expect(
@ -119,13 +119,12 @@ void main() {
expect(result.label, startsWith('PC ✓ (sandbox, not credited) · ')); expect(result.label, startsWith('PC ✓ (sandbox, not credited) · '));
}); });
test('null shutdown and budget are carried as null, not guessed', () async { test('null shutdown is carried as null, not guessed', () async {
final client = MockClient( final client = MockClient(
(_) async => http.Response(_reply(credited: true), 200), (_) async => http.Response(_reply(credited: true), 200),
); );
final result = await _service(client).poke(_session()); final result = await _service(client).poke(_session());
expect(result.shutdown, isNull); expect(result.shutdown, isNull);
expect(result.gamingBudgetMinutes, isNull);
expect(result.label, 'PC ✓'); expect(result.label, 'PC ✓');
}); });

View File

@ -51,7 +51,6 @@ void main() {
outcome: PokeOutcome.credited, outcome: PokeOutcome.credited,
reason: 'credited', reason: 'credited',
shutdown: '22:00', shutdown: '22:00',
gamingBudgetMinutes: 90,
), ),
PokeResult(outcome: PokeOutcome.duplicate, reason: 'dup'), PokeResult(outcome: PokeOutcome.duplicate, reason: 'dup'),
PokeResult(outcome: PokeOutcome.sandbox, reason: 'sb', roundTripMs: 40), PokeResult(outcome: PokeOutcome.sandbox, reason: 'sb', roundTripMs: 40),

View File

@ -88,7 +88,7 @@ void main() {
expect(colorOf(tester), status.warning); expect(colorOf(tester), status.warning);
}); });
testWidgets('a credit shows the new shutdown and gaming hours', ( testWidgets('a credit shows the new shutdown and no gaming figure', (
tester, tester,
) async { ) async {
await show( await show(
@ -98,12 +98,11 @@ void main() {
outcome: PokeOutcome.credited, outcome: PokeOutcome.credited,
reason: 'credited', reason: 'credited',
shutdown: '22:00', shutdown: '22:00',
gamingBudgetMinutes: 90,
), ),
), ),
); );
expect(find.text(' 22:00'), findsOneWidget); expect(find.text(' 22:00'), findsOneWidget);
expect(find.text(' 1.5h'), findsOneWidget); expect(find.byIcon(Icons.sports_esports), findsNothing);
expect(find.byIcon(Icons.power_settings_new), findsOneWidget); expect(find.byIcon(Icons.power_settings_new), findsOneWidget);
expect(colorOf(tester), status.success); expect(colorOf(tester), status.success);
}); });