Compare commits

...

6 Commits

Author SHA1 Message Date
19ccad6978 deps: freedays 0.3.1 (pins crdt-sync 0.9.2); pre-commit hook pins back in step
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
freedays 0.3.0 pinned crdt-sync v0.9.1 exactly, which a clean venv could
not resolve next to screen-locker's own crdt-sync 0.9.2. The pylint hook
environments had also drifted from pyproject.toml (crdt-sync 0.9.1,
earned-time 0.3.0).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018RHwVPyiiQMPh4M3JQwQku
2026-10-09 20:56:32 +02:00
52fd8217f5 test: pin credit time in TestRealLedgers so the grace floor can't win after 19:00
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018RHwVPyiiQMPh4M3JQwQku
2026-10-09 19:24:34 +02:00
965b9c4ebb Sync: Firebase only — drop the GitHub transport (kuhyx/syncs stays a frozen archive)
The PC push aborted before it ever tried Firebase whenever the GitHub PAT
was missing ("Workouts NOT synced: no sync token"), so once the PAT was lost
this machine published nothing although Firebase was configured and live.
The phone has not written the GitHub repo since 2026-08-21.

- sync_client() / sync_client_or_reason(): firebase_client_for("screen_locker")
  only, proven with can_access_remote(), healed once from a sibling app's
  session, else a warning naming what will not sync (push AND pull) plus a
  recorded degraded source. No config -> warning, no fallback.
- _manual_push and scripts/tombstone_sync_record.py take their client from
  sync_client_or_reason(); the push result carries the reason.
- Deleted: read_sync_token, remote_client, the mirror client, _push_outcome
  (the half-landed-push case no longer exists), SYNC_TOKEN_FILE and
  SYNC_REPO_OWNER/NAME, the sync_token test fixture. Status backend is
  "firebase" or "none".
- crdt-sync pinned to v0.9.2 in pyproject, requirements.txt and
  install_systemd.sh (the installer still said v0.9.0).

kuhyx/syncs/screen-locker-sync is left untouched as an archive; no code
reads it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018RHwVPyiiQMPh4M3JQwQku
2026-10-09 19:18:56 +02:00
2dac472331 workout_app: send finished workout to the PC instantly; PC link pairing; summary <100 ms
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018RHwVPyiiQMPh4M3JQwQku
2026-10-09 19:08:22 +02:00
a826cfa166 workout-poke: instant phone credit over LAN (signed POST :8773) and Firebase stream
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018RHwVPyiiQMPh4M3JQwQku
2026-10-09 19:05:51 +02:00
aedfdbc7f5 Credit: one reward per workout slot, desktop notification, --help, runnerup-watch ignores re-pulls
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018RHwVPyiiQMPh4M3JQwQku
2026-10-09 19:05:08 +02:00
112 changed files with 7181 additions and 746 deletions

View File

@ -133,9 +133,9 @@ repos:
# the manifest becomes an unresolvable hook environment rather
# than merely an old one.
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.9.0#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.1#subdirectory=crdt-sync
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.3.0#subdirectory=earned_time
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.3.0#subdirectory=freedays
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.4.0#subdirectory=earned_time
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.3.1#subdirectory=freedays
- mcp>=2,<3
- pydantic
- id: pylint
@ -154,9 +154,9 @@ repos:
# the manifest becomes an unresolvable hook environment rather
# than merely an old one.
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.9.0#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.1#subdirectory=crdt-sync
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.3.0#subdirectory=earned_time
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.3.0#subdirectory=freedays
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.4.0#subdirectory=earned_time
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.3.1#subdirectory=freedays
- mcp>=2,<3
- pydantic

View File

@ -0,0 +1,6 @@
{
"_comment": "Shared literal fixture for the phone->PC workout poke (v1). Both the Python receiver and the Dart sender test against THESE bytes. body_utf8 is the exact request body; signature = hex(HMAC-SHA256(bytes.fromhex(key_hex), body_utf8.encode('utf-8'))). Never re-serialize before verifying.",
"key_hex": "7f3c9a1e5b2d4f6081a3c5e7092b4d6f8a1c3e5072946b8d0f2a4c6e8013579b",
"body_utf8": "{\"v\":1,\"sent_at_ms\":1791558449000,\"nonce\":\"0b1e6c2a-9f4d-4c1b-8e7a-3d5f6a7b8c9d\",\"sandbox\":false,\"record_id\":\"2026-10-09T15:10:40.953\",\"payload\":{\"date\":\"2026-10-09\",\"start_time\":\"2026-10-09T15:10:40.953\",\"workout_type\":\"A\",\"duration_seconds\":7020.5,\"succeeded\":true,\"exercises\":[{\"name\":\"Squat\",\"weight_kg\":100.0,\"sets\":[5,5,5,5,5]}],\"note\":\"zażółć gęślą jaźń\"}}",
"signature_hex": "98b0b80fe717079c800e79562f669fd0189d89c3578a5bbf973761a0e7a3a3f5"
}

View File

@ -0,0 +1,75 @@
# Workout poke: phone -> PC wire contract (v1)
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
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
session that arrives both ways is credited once.
## Transport
- `POST http://<pc-host>:8773/v1/workout`, `Content-Type: application/json`.
- `<pc-host>` is a phone setting, default `192.168.1.43` (static on the PC).
LAN only: the PC firewall accepts tcp/8773 from `192.168.1.0/24` and nothing
else. No WireGuard. Off the home LAN the poke fails fast and the regular
sync is the only path.
- Header `X-Poke-Signature: <hex HMAC-SHA256(key, raw body bytes)>`.
The PC verifies the MAC over the bytes **as received** and only then parses
them. Neither side may re-serialize JSON to compute or check the MAC.
- Key: 32 random bytes, hex, PC copy at `~/.config/workout_poke/key`
(mode 600); phone copy in the Android keystore, put there by
`scripts/pair_phone.sh` over adb.
## Request body
```json
{"v":1,"sent_at_ms":<int epoch ms>,"nonce":"<uuid4>","sandbox":<bool>,
"record_id":"<sync record id>","payload":{<session exactly as synced>}}
```
- `payload` is the same map the phone puts in its sync log for the session;
the PC feeds `(record_id, payload)` to `ingest_session_records`, which
re-validates it (never trusts `succeeded`).
- `sandbox` is inside the signed body. A sandbox request is verified, timed
and answered, but **never written anywhere** and never credited.
## PC checks, in order (each rejection is logged at warning)
1. Signature matches -> else `401`.
2. `|now - sent_at_ms| <= 120 s` -> else `401` (replay window).
3. `nonce` not seen within the window -> else `409`.
4. `v == 1` and fields present -> else `400`.
## Response (always JSON)
```json
{"ok":<bool>,"credited":<bool>,"duplicate":<bool>,"sandbox":<bool>,
"shutdown":"HH:MM"|null,"gaming_budget_minutes":<int|null>,"pc_ms":<int>,
"reason":"<sentence a human can act on>"}
```
The phone must treat `shutdown` and `gaming_budget_minutes` as nullable.
Outcomes of a verified (200) request:
| case | ok | credited | duplicate |
|---|---|---|---|
| newly credited | true | true | false |
| already in `log.json` (e.g. the sync got there first) | true | false | true |
| logged, but today's credit slot was already paid by another copy of the same workout | true | false | false |
| signed but does not count (too short, no date): `reason` says why | false | false | false |
| sandbox | true | false | false |
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
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
`gaming_budget_minutes` both `null`. The PC answers a `413` without reading
the body, so the phone may see a connection reset instead of the reply.
## Shared fixture
`contracts/workout_poke_v1.json` holds a literal key, body and expected
signature (with a float and non-ASCII text, the usual cross-language traps).
The Python receiver and the Dart sender both test against it, so a drift on
either side fails that side's tests.

View File

@ -2,6 +2,14 @@
## Status
**Superseded (2026-10-09): screen-locker sync is Firebase RTDB only.** The
phone stopped writing the GitHub repo on 2026-08-21, and from 2026-10-09 the
PC does not use it either: the push, `sync_client()` and
`scripts/tombstone_sync_record.py` all use `firebase_client_for("screen_locker")`,
and the sync_token / GitHub client / mirror code paths are deleted.
`kuhyx/syncs/screen-locker-sync` stays as a frozen archive that no code reads
and nothing deletes. The rest of this document is the historical design record.
**Blocked on Workstream D** (2026-07-04 user decision — see "Sequencing
decision" below). No code has been written for this workstream. The design
questions below (sync pattern, repo name, scope) have been pre-decided so the

View File

@ -16,6 +16,7 @@ SYNC_TIMER_NAME="workout-sync.timer"
BONUS_SERVICE_NAME="earner-bonus.service"
BONUS_PATH_NAME="earner-bonus.path"
RUNNERUP_WATCH_NAME="runnerup-watch.service"
WORKOUT_POKE_NAME="workout-poke.service"
# Runtime dependencies. screen_lock.py imports tkinter at module scope. On Arch
# the tkinter MODULE ships inside the `python` package, but the shared library
@ -72,7 +73,7 @@ ensure_runtime_deps() {
_pip_runtime_dep gatelock \
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.9.0#subdirectory=gatelock"
_pip_runtime_dep crdt_sync \
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.0#subdirectory=crdt-sync"
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync"
}
ensure_runtime_deps
@ -140,6 +141,12 @@ PYTHONPATH="$SCRIPT_DIR" python3 -m screen_locker._earner_units "$USER_SERVICE_D
# workout-sync at once instead of waiting for the next timer tick.
cp "$SCRIPT_DIR/$RUNNERUP_WATCH_NAME" "$USER_SERVICE_DIR/$RUNNERUP_WATCH_NAME"
# The phone's LAN poke: a finished StrongLifts session is credited within a
# second instead of at the next sync. The key must exist before the unit
# starts, or it refuses to (docs/DOCS-workout-poke-contract.md).
bash "$SCRIPT_DIR/scripts/workout_poke_keygen.sh"
cp "$SCRIPT_DIR/$WORKOUT_POKE_NAME" "$USER_SERVICE_DIR/$WORKOUT_POKE_NAME"
# Update paths in the service file to use absolute paths
REPO_ROOT="$SCRIPT_DIR"
sed -i "s|WorkingDirectory=.*|WorkingDirectory=$REPO_ROOT|" "$USER_SERVICE_DIR/$SERVICE_NAME"
@ -168,6 +175,10 @@ systemctl --user enable --now "$BONUS_PATH_NAME"
systemctl --user enable "$RUNNERUP_WATCH_NAME"
systemctl --user restart "$RUNNERUP_WATCH_NAME"
# Enable the LAN workout poke listener (restart picks up new code)
systemctl --user enable "$WORKOUT_POKE_NAME"
systemctl --user restart "$WORKOUT_POKE_NAME"
# Verify enforcement is actually armed. enable can silently no-op when systemd
# breaks an ordering cycle by deleting the timer's job -- exactly what happened
# on 2026-08-04 -- so a successful `enable` is NOT proof the locker will run.

View File

@ -4,12 +4,12 @@ version = "1.0.0"
description = "Tkinter/systemd screen locker with workout tracking, sick-day management, and wake-alarm integration"
requires-python = ">=3.14"
# gatelock: shared lock-window/HMAC backend, also used by diet_guard and wake_alarm
# crdt-sync: shared CRDT merge scheme + GitHub-Contents-API sync transport,
# also used by diet_guard; here for phone-workout GitHub sync (Workstream C)
# crdt-sync: shared CRDT merge scheme + sync transports, also used by
# diet_guard; here for phone-workout sync, Firebase RTDB only since 2026-10-09
dependencies = [
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.9.0#subdirectory=gatelock",
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.1#subdirectory=crdt-sync",
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.3.0#subdirectory=freedays",
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync",
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.3.1#subdirectory=freedays",
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.4.0#subdirectory=earned_time",
]

View File

@ -16,6 +16,7 @@ UNITS=(
"earner-bonus.path"
"earner-bonus.service"
"runnerup-watch.service"
"workout-poke.service"
)
for unit in "${UNITS[@]}"; do

View File

@ -3,9 +3,9 @@
bandit==1.9.4
codespell==2.4.3
coverage==7.16.2
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.1#subdirectory=crdt-sync
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync
earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.4.0#subdirectory=earned_time
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.3.0#subdirectory=freedays
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.3.1#subdirectory=freedays
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.9.0#subdirectory=gatelock
mcp==2.3.0
mypy==2.4.0
@ -22,3 +22,7 @@ pytest-xdist==3.8.0
requests==2.34.2
ruff==0.16.10
types-requests==2.33.0.20261006
# Direct dependency since the Firebase session stream (_session_stream) catches
# urllib3's own errors on the long-lived SSE read; requests pulls it in, but
# the module imports it itself, so it is declared rather than assumed.
urllib3==2.8.0

View File

@ -33,6 +33,60 @@ _LOG_MANUAL_FLAG = "--log-manual-workout"
_REST_DAY_FLAG = "--declare-rest-day"
_BACKFILL_FLAG = "--backfill-workout-ledger"
# Subcommands that own every argument after them (each has its own argparse,
# which also answers its own --help).
_TRAILING_ARG_FLAGS = (_LOG_MANUAL_FLAG, _REST_DAY_FLAG, _BACKFILL_FLAG)
_MODE_FLAGS = frozenset(
{"--status", "--sync-only", "--apply-bonuses", "--production", "--verify-workout"}
)
_HELP_FLAGS = frozenset({"-h", "--help"})
_EXIT_USAGE = 2
_USAGE = """\
usage: python3 -m screen_locker.screen_lock [MODE]
With no mode: the demo lock screen (Tk). Modes:
--production the real lock screen (what workout-locker.service runs)
--verify-workout lock screen in verify-only mode
--status print this week's workout status and exit
--sync-only headless: pull synced workouts, apply credit, exit
--apply-bonuses headless: apply newly earned flat bonuses, exit
--log-manual-workout ARGS headless manual workout log (see its --help)
--declare-rest-day ARGS sign a future rest day (see its --help)
--backfill-workout-ledger ARGS
backfill the workout ledger (see its --help)
-h, --help show this help and exit
"""
def _own_args(argv: list[str]) -> list[str]:
"""``argv[1:]`` up to the first subcommand that owns the rest."""
args = argv[1:]
for index, arg in enumerate(args):
if arg in _TRAILING_ARG_FLAGS:
return args[:index]
return args
def _handle_help_and_unknown(argv: list[str]) -> None:
"""Exit 0 on ``--help``; exit 2 on an unknown argument.
Before this, ``--help`` matched no branch and fell through to building
the demo lock screen, and a typo'd flag did the same silently.
"""
own = _own_args(argv)
if _HELP_FLAGS & set(own):
# The usage on stdout IS the work --help asked for, so exiting 0 here
# abandons nothing. SystemExit is raised directly, not via sys.exit:
# the suite stubs sys.exit process-wide, and a help request must never
# fall through to building the lock screen even then.
sys.stdout.write(_USAGE)
raise SystemExit(0)
unknown = [arg for arg in own if arg not in _MODE_FLAGS]
if unknown:
sys.stderr.write(f"error: unknown argument(s): {' '.join(unknown)}\n{_USAGE}")
sys.exit(_EXIT_USAGE)
def _headless_locker(locker_cls: type[ScreenLocker]) -> ScreenLocker:
"""A ScreenLocker with ``__init__`` bypassed, for the no-UI subcommands.
@ -49,6 +103,7 @@ def _headless_locker(locker_cls: type[ScreenLocker]) -> ScreenLocker:
def main(locker_cls: type[ScreenLocker], argv: list[str]) -> None:
"""Dispatch on ``argv`` and run the requested mode."""
_handle_help_and_unknown(argv)
# Configure logging for EVERY mode, not just --sync-only. This used to sit
# inside the --sync-only branch, so `--production` -- the mode systemd
# actually runs -- had no handler and fell back to lastResort, which drops

View File

@ -186,15 +186,12 @@ RUNNERUP_WEBDAV_DIRS: tuple[Path, ...] = (
)
# ---------------------------------------------------------------------------
# Sync (phone workout data) — Workstream C, built on the shared crdt-sync
# library. GitHub is used purely as dumb file storage via the REST Contents
# API (not a git clone), same pattern as diet_guard's cross-device sync. The
# phone app pushes to devices/<SYNC_PHONE_DEVICE_ID>/log.json; the PC reads
# every device's log and pushes its OWN manual workouts to devices/pc/log.json
# (see _manual_push) — which needs a token with contents:write, not read-only.
# Sync (phone workout data) — built on the shared crdt-sync library, Firebase
# RTDB only since 2026-10-09 (the shared ~/.config/crdt-sync/ credential). The
# old GitHub repo kuhyx/syncs/screen-locker-sync is a frozen archive: nothing
# reads or writes it. Every device pushes to devices/<device id>/log.json; the
# PC reads every device's log and pushes its OWN workouts (see _manual_push).
# ---------------------------------------------------------------------------
SYNC_REPO_OWNER: str = "kuhyx"
SYNC_REPO_NAME: str = "syncs"
# The phone's pre-uuid device id. Still read (the phone may not have migrated
# yet), but no longer the only path the reader knows about -- it discovers
# every device directory.
@ -209,12 +206,6 @@ SYNC_LEGACY_DEVICE_ID: str | None = "pc"
SYNC_DEVICE_ID_FILE: Path = (
Path.home() / ".local" / "share" / "screen_locker" / ".device_id"
)
# A fine-grained GitHub PAT, scoped to just SYNC_REPO_NAME's contents. The
# user creates this once via github.com and saves it here, mode 600. Never
# committed — this path is outside the repo entirely. Unlike diet_guard,
# this file being absent is a normal, expected state (sync is optional here).
SYNC_TOKEN_FILE: Path = Path.home() / ".config" / "screen_locker" / "sync_token"
# Revision cache for cross-device sync. Without it every push re-uploads and
# every pull re-downloads regardless of change, which is the traffic the
# Firebase free tier's monthly budget depends on not happening.

View File

@ -0,0 +1,125 @@
"""Desktop notification the moment a workout earns its credit.
The reward is the point: a workout should be *felt* as paid the second the PC
credits it, not discovered at the next look at the status window. Every path
that credits a workout ends in
:meth:`~screen_locker._workout_credit.WorkoutCreditMixin._apply_credit_for_written_entry`,
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
(:func:`screen_locker._shutdown_target.gather` -- the same sum the daily reset
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,
no notify-send, a hang) is logged at warning and swallowed.
"""
from __future__ import annotations
from datetime import date
import logging
import shutil
import subprocess
from typing import TYPE_CHECKING, Final
from screen_locker._day import today_str
from screen_locker._earned import hhmm, span
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__)
TITLE: Final = "Workout credited \N{FLEXED BICEPS}"
_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(
before: tuple[int, int, int] | None,
after: tuple[int, int, int] | None,
gaming_minutes: int | None,
) -> str:
"""``Shutdown 23:00 (+2h) · gaming 7.0h`` -- whichever parts are known.
``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``.
"""
parts: list[str] = []
if after is None:
_logger.warning(
"Shutdown config unreadable after a workout credit — the "
"notification shows no shutdown time"
)
else:
day = date.fromisoformat(today_str())
tonight = tonight_minutes(after, day)
text = f"Shutdown {hhmm(tonight)}"
if before is not None:
moved = max(0, tonight - tonight_minutes(before, day))
text += f" (+{span(moved)})"
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 "Credit applied (details unavailable)"
def send_notification(title: str, body: str) -> bool:
"""Show a desktop notification via ``notify-send``; False (logged) on failure."""
binary = shutil.which("notify-send")
if binary is None:
_logger.warning("notify-send not found — no desktop notification: %s", body)
return False
try:
result = subprocess.run(
[binary, "--app-name=screen-locker", title, body],
capture_output=True,
text=True,
timeout=_NOTIFY_TIMEOUT_SECONDS,
check=False,
)
except (OSError, subprocess.TimeoutExpired) as exc:
_logger.warning("Desktop notification failed (%s): %s", exc, body)
return False
if result.returncode != 0:
_logger.warning(
"notify-send exited %d (%s) — no desktop notification: %s",
result.returncode,
result.stderr.strip() or "no stderr; is a DBus session reachable?",
body,
)
return False
_logger.info("Desktop notification: %s — %s", title, body)
return True
def notify_workout_credit(
before: tuple[int, int, int] | None,
after: tuple[int, int, int] | None,
log_file: Path | None,
) -> bool:
"""Notify a newly earned workout credit. Never raises."""
body = credit_body(before, after, gaming_minutes_today(log_file))
return send_notification(TITLE, body)

View File

@ -0,0 +1,86 @@
"""Which credit a newly written workout earns, decided by slot like the reset.
The live credit path used to ask "was any counted workout already logged
today?" -- so the two StrongLifts ingestion paths of ONE session
(``pc_workout_verified`` from the session sync, ``phone_verified`` from the
early-bird auto-upgrade) earned the first-unit +2h and then a further-unit +1h
(2026-10-09; also 07-17 and 07-27 in ``duplicate_credits.json``). The daily
reset counts the same day with :func:`~screen_locker._weekly_check.count_day_credits`,
which collapses them onto one slot. Deciding the live credit with that same
counter makes the two agree by construction.
"""
from __future__ import annotations
from contextlib import ExitStack, contextmanager
import enum
import logging
from typing import TYPE_CHECKING, Any, Final
from screen_locker._bonus_lock import bonus_lock
from screen_locker._weekly_check import count_day_credits
if TYPE_CHECKING:
from collections.abc import Iterator, Mapping
from pathlib import Path
_logger: Final = logging.getLogger(__name__)
# count_day_credits only uses the date to build slot keys, and both counts
# below are taken over the same day, so any fixed label is equivalent.
_SAME_DAY: Final = "day"
class CreditSlot(enum.Enum):
"""What the newest entry of a day earns."""
NONE = "earns no credit (not a counted workout type)"
FIRST = "first credit slot of the day"
FURTHER = "a new, distinct credit slot after the first"
OCCUPIED = "a slot an earlier entry of the day already credited"
def credit_slot(
prior_entries: list[dict[str, Any]], workout_data: Mapping[str, Any]
) -> CreditSlot:
"""Classify ``workout_data`` against the day's entries written before it.
Args:
prior_entries: The day's log entries before the new one, as returned
by the write chokepoint (snapshotted under the log lock).
workout_data: The new entry's ``workout_data``.
"""
new_entry = {"workout_data": dict(workout_data)}
day = [e for e in prior_entries if isinstance(e, dict)]
before = count_day_credits(_SAME_DAY, day)
with_new = count_day_credits(_SAME_DAY, [*day, new_entry])
if with_new == before:
# No new slot: either it earns nothing at all, or its slot is taken.
return CreditSlot.OCCUPIED if _counts_alone(new_entry) else CreditSlot.NONE
return CreditSlot.FIRST if before == 0 else CreditSlot.FURTHER
def _counts_alone(entry: Mapping[str, Any]) -> bool:
"""Whether ``entry`` would earn a credit on an otherwise empty day."""
return count_day_credits(_SAME_DAY, [entry]) == 1
@contextmanager
def locked_shutdown_state(state_file: Path) -> Iterator[None]:
"""Hold :func:`bonus_lock` on ``state_file``; on failure, warn and go on.
The reset and the flat-bonus pass hold the same lock, so a credit can no
longer lose its minutes to their read-add-write. Never nest inside them:
a second flock on a new fd in the same process deadlocks.
"""
with ExitStack() as stack:
try:
stack.enter_context(bonus_lock(state_file))
except OSError as exc:
_logger.warning(
"Could not lock %s (%s) — applying the workout credit without "
"it; a reset running at the same moment could overwrite it",
state_file,
exc,
)
yield

View File

@ -146,7 +146,8 @@ def plan_absorb(minutes: int, state_file: Path | None = None) -> tuple[int, int]
return max(0, minutes - lift), max(0, lift - minutes)
def _tonight(config: tuple[int, int, int], day: date) -> int:
def tonight_minutes(config: tuple[int, int, int], day: date) -> int:
"""``day``'s shutdown from a (mon_wed, thu_sun, morning_end) config."""
mon_wed, thu_sun, _ = config
return mon_wed if day.weekday() in _MON_WED else thu_sun
@ -184,7 +185,7 @@ class GraceFloorMixin:
if config is None:
_logger.warning("Grace floor: shutdown config unreadable; not applied")
return False
current = _tonight(config, day)
current = tonight_minutes(config, day)
if current >= floor:
return False
mon_wed, thu_sun, morning = config

View File

@ -1,7 +1,7 @@
"""Push the PC's workouts to the shared sync repo.
"""Push the PC's workouts to the shared Firebase sync store.
``log.json`` is the single source of truth: this module derives the
crdt-sync log directly from it and pushes to ``devices/pc/log.json``, so the
crdt-sync log directly from it and pushes to this device's log, so the
phone converges on the SAME history the PC has — manual workouts *and*
machine-verified ones (StrongLifts sessions, RunnerUp runs).
@ -10,11 +10,11 @@ workout is published automatically no matter when or how it was recorded,
including entries logged before this module existed. Idempotence comes from two
properties: the record id is the workout's own stable ``workout_id``, and its
HLC is derived deterministically from the entry's own timestamp — so re-pushing
an unchanged log produces a byte-identical record set and no repo churn.
an unchanged log produces a byte-identical record set and no store churn.
This reverses the old "the PC only ever reads, never pushes" invariant (it had
no data of its own to contribute). Pushing needs a sync token with
**contents:write** on the repo — a read-only token 403s. Nothing here fails
no data of its own to contribute). Firebase is the only transport since
2026-10-09; the old GitHub mirror is a frozen archive. Nothing here fails
silently: every path returns a :class:`PushResult` whose ``reason`` says exactly
what happened, and logs it.
"""
@ -29,33 +29,23 @@ from typing import TYPE_CHECKING
from crdt_sync import (
FileSyncStateStore,
GitHubSyncClient,
GitHubSyncError,
Hlc,
LogCodec,
Record,
RemoteSyncError,
RepoNotFoundError,
RevisionTracking,
SyncTarget,
sync_log,
)
from screen_locker._constants import (
SYNC_REPO_NAME,
SYNC_REPO_OWNER,
SYNC_STATE_FILE,
SYNC_TIMEOUT_SECONDS,
SYNC_TOKEN_FILE,
)
from screen_locker._constants import SYNC_STATE_FILE
from screen_locker._device import device_identity
from screen_locker._log_io import load_workout_log
from screen_locker._log_mixin import _derive_workout_id
from screen_locker._push_outcome import describe_push
from screen_locker._sync_retry import with_sync_retry
from screen_locker._sync_tombstones import tombstone_records
from screen_locker._weekly_check import COUNTED_WORKOUT_TYPES
from screen_locker._workout_sync import _DEVICES_PREFIX, read_sync_token, remote_client
from screen_locker._workout_sync import _DEVICES_PREFIX, sync_client_or_reason
if TYPE_CHECKING:
from pathlib import Path
@ -172,32 +162,20 @@ def push_pc_workouts(log_file: Path) -> PushResult:
the returned :class:`PushResult` and a WARNING say why a push did not happen.
"""
identity = device_identity()
token = read_sync_token()
if token is None:
reason = f"no sync token at {SYNC_TOKEN_FILE}"
_logger.warning(
"Workouts NOT synced: %s — create a fine-grained GitHub PAT with "
"contents:write on %s/%s and save it there (chmod 600)",
reason,
SYNC_REPO_OWNER,
SYNC_REPO_NAME,
)
return PushResult(pushed=False, record_count=0, reason=reason)
log = records_from_workout_log(log_file)
if not log:
reason = f"no counted workouts in {log_file}"
_logger.warning("Workouts NOT synced: %s", reason)
return PushResult(pushed=False, record_count=0, reason=reason)
client = remote_client(
GitHubSyncClient(
SYNC_REPO_OWNER,
SYNC_REPO_NAME,
token,
timeout_seconds=SYNC_TIMEOUT_SECONDS,
client, reason = sync_client_or_reason()
if client is None:
# sync_client_or_reason has already said why, in full; this line
# ties that cause to the records it just stranded.
_logger.warning(
"Workouts NOT synced: %d workout(s) stay local — %s", len(log), reason
)
)
return PushResult(pushed=False, record_count=len(log), reason=reason)
try:
with_sync_retry(
lambda: sync_log(
@ -218,32 +196,14 @@ def push_pc_workouts(log_file: Path) -> PushResult:
),
description="push PC workouts",
)
except (GitHubSyncError, RemoteSyncError) as exc:
except RemoteSyncError as exc:
# Report what actually happened, nothing more: this used to assert
# "a 403 means the token lacks contents:write" for every failure,
# including a plain network error, which sent a 2026-07-20
# investigation chasing a permissions bug that did not exist.
reason = f"sync error: {exc}"
# Report what actually happened. This used to assert "a 403 here means
# the token lacks contents:write" for *every* failure, including a
# plain network error — which sent a 2026-07-20 investigation chasing a
# permissions bug that did not exist (the token could write fine; the
# network was simply not up yet). Only RepoNotFoundError actually
# implicates the repo or the token.
if isinstance(exc, RepoNotFoundError):
_logger.warning(
"Workout sync push FAILED for %d workout(s): %s — check the "
"token has contents:write on %s/%s",
len(log),
exc,
SYNC_REPO_OWNER,
SYNC_REPO_NAME,
)
else:
_logger.warning(
"Workout sync push FAILED for %d workout(s): %s",
len(log),
exc,
)
_logger.warning("Workout sync push FAILED for %d workout(s): %s", len(log), exc)
return PushResult(pushed=False, record_count=len(log), reason=reason)
# Delegated so a half-landed push can never be logged as a clean one;
# see _push_outcome for why that distinction is load-bearing.
_, reason = describe_push(len(log))
return PushResult(pushed=True, record_count=len(log), reason=reason)
_logger.info("Synced %d workout(s) to Firebase", len(log))
return PushResult(pushed=True, record_count=len(log), reason="pushed")

View File

@ -23,8 +23,8 @@ Safety invariants (do not break when adding tools):
calls must never write to stdout. All logging is routed to STDERR below,
and no tool calls ``screen_lock.py`` / ``status_view.main`` (which
``print`` / open Tk windows / ``sys.exit``).
* **No secret ever leaves.** No tool returns the sync token
(``~/.config/screen_locker/sync_token``) or any HMAC key; the predicates
* **No secret ever leaves.** No tool returns the Firebase session
(``~/.config/screen_locker/firebase_auth.json``) or any HMAC key; the predicates
load only status/state and return booleans, and the status snapshot
carries no secret material.
"""

View File

@ -1,4 +1,4 @@
"""Phone workout verification: GitHub sync first, ADB/HTTP as fallback."""
"""Phone workout verification: Firebase sync first, ADB/HTTP as fallback."""
from __future__ import annotations
@ -144,7 +144,7 @@ class PhoneVerificationMixin(AdbTransportMixin, HttpWorkoutFetchMixin):
# ── HTTP fallback (no ADB / developer options required) ───────────────────
def _verify_phone_workout(self) -> tuple[str, str]:
"""Verify today's workout: GitHub sync first, ADB/HTTP as fallback.
"""Verify today's workout: Firebase sync first, ADB/HTTP as fallback.
Returns (status, message). Status values:
verified / too_short / not_verified / no_phone / sync_failed /
@ -154,7 +154,7 @@ class PhoneVerificationMixin(AdbTransportMixin, HttpWorkoutFetchMixin):
if not clock_ok:
return "clock_tampered", clock_msg
# GitHub sync is the primary channel — it works without the phone
# Firebase sync is the primary channel — it works without the phone
# being on the same network as the PC. Only a *verified* sync result
# short-circuits ADB/HTTP: a stale/incomplete cloud entry (e.g. the
# phone's last push predates today, or a later push failed offline)
@ -174,7 +174,7 @@ class PhoneVerificationMixin(AdbTransportMixin, HttpWorkoutFetchMixin):
)
elif sync_error is not None:
_logger.info(
"GitHub sync unavailable (%s) — trying ADB/HTTP...", sync_error
"Firebase sync unavailable (%s) — trying ADB/HTTP...", sync_error
)
# Prefer ADB when a device is visible, but if the pull yields no usable

View File

@ -0,0 +1,213 @@
"""Credit one poked StrongLifts session: the sync's ingest, minus the network.
The phone POSTs a finished session straight to the PC
(``docs/DOCS-workout-poke-contract.md``); this applies it through exactly the
path a synced session takes -- :func:`ingest_session_records`, which
re-validates and dedups under ``log.lock``, then the shared
:meth:`~screen_locker._workout_credit.WorkoutCreditMixin._apply_credit_for_written_entry`
(slot-based credit, shutdown push, debt, the "Workout credited" notification).
Nothing here computes a reward of its own.
Each call builds a FRESH headless locker, the same object
``--sync-only`` uses, so no state leaks from one request into the next.
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
import logging
from typing import TYPE_CHECKING, Final, cast
from screen_locker._cli import _headless_locker
from screen_locker._constants import (
EXTRA_BENEFITS_FILE,
SHUTDOWN_BASE_FILE,
SHUTDOWN_CONFIG_FILE,
SICK_DAY_STATE_FILE,
)
from screen_locker._credit_notify import gaming_minutes_today
from screen_locker._day import today_str
from screen_locker._earned import hhmm
from screen_locker._extra_benefits import process_week_transition
from screen_locker._grace_floor import tonight_minutes
from screen_locker._session_sync import ingest_session_records, validate_session
from screen_locker._shutdown import read_shutdown_config
from screen_locker._shutdown_base import reset_to_base_if_new_day
from screen_locker.screen_lock import ScreenLocker
if TYPE_CHECKING:
from collections.abc import Iterable, Mapping
from pathlib import Path
from screen_locker._workout_credit import WorkoutCreditResult
__all__ = [
"BatchOutcome",
"PokeOutcome",
"credit_session",
"credit_sessions",
"current_gaming_minutes",
"current_shutdown",
]
_logger: Final = logging.getLogger(__name__)
@dataclass(frozen=True)
class PokeOutcome:
"""What crediting one poked session did; ``reason`` is for the phone's UI."""
ok: bool
credited: bool
duplicate: bool
reason: str
@dataclass(frozen=True)
class BatchOutcome:
"""What one batch did: newly logged ids, and how many of those earned time."""
ingested: tuple[str, ...]
credited: int
class PokeLocker(ScreenLocker):
"""The headless locker plus the two steps a poke needs, as public calls."""
def start_the_day(self) -> None:
"""Run the new-day reset the locker's startup runs, in the same order.
Mirrors ``StartupChecksMixin._check_non_verify_exits``, not
``sync_now`` (which never resets): the week transition must be
processed BEFORE the reset, and the weekly bonus layered on only when
this call did the reset. If the poke stamped the day without them, the
locker's own reset later would be a no-op and that day's streak bonus
would be lost.
"""
for reward in process_week_transition(self.log_file, EXTRA_BENEFITS_FILE):
_logger.info("Weekly reward: %s", reward)
if reset_to_base_if_new_day(
SHUTDOWN_BASE_FILE,
self,
sick_day_state_file=SICK_DAY_STATE_FILE,
log_file=self.log_file,
):
self._apply_weekly_shutdown_bonus()
def credit_written(
self, entry: dict[str, str], prior_entries: list[dict[str, object]]
) -> WorkoutCreditResult:
"""``SyncMixin._credit_ingested_workout``, keeping the result."""
self.workout_data = entry
return self._apply_credit_for_written_entry(prior_entries)
def fresh_locker() -> PokeLocker:
"""The ``--sync-only`` headless locker: no Tk, no window, no lock."""
return cast("PokeLocker", _headless_locker(PokeLocker))
def current_shutdown() -> str | None:
"""Tonight's shutdown from ``/etc/shutdown-schedule.conf`` as ``HH:MM``."""
config = read_shutdown_config(SHUTDOWN_CONFIG_FILE)
if config is None:
_logger.warning(
"Workout poke: shutdown config unreadable, replying shutdown=null"
)
return None
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:
"""Why the session can never count, or ``None`` if it can.
``ingest_session_records`` applies the same rules but only returns what
it ingested, so a rejection would be indistinguishable from a duplicate.
"""
day = payload.get("date")
if not isinstance(day, str) or not day:
return f"session {record_id} has no usable date ({day!r}), so it cannot count"
valid, detail = validate_session(payload)
if not valid:
return f"session {record_id} does not count: {detail}"
return None
def credit_session(record_id: str, payload: Mapping[str, object]) -> PokeOutcome:
"""Reset the day if new, then ingest and credit one session.
The caller serialises calls; the ingest also holds ``log.lock`` and the
credit the shutdown-state lock, so a concurrent sync or locker pass is safe.
"""
locker = fresh_locker()
locker.start_the_day()
problem = _precheck(record_id, payload)
if problem is not None:
_logger.warning("Workout poke not credited: %s", problem)
return PokeOutcome(ok=False, credited=False, duplicate=False, reason=problem)
results: list[WorkoutCreditResult] = []
def on_ingested(
entry: dict[str, str], prior_entries: list[dict[str, object]]
) -> None:
results.append(locker.credit_written(entry, prior_entries))
ingested = ingest_session_records(
locker.log_file, [(record_id, payload)], on_ingested=on_ingested
)
if not ingested or not results:
reason = (
f"session {record_id} is already in the PC's log (the sync or an "
"earlier poke got there first); nothing new to credit"
)
_logger.info("Workout poke duplicate: %s", reason)
return PokeOutcome(ok=True, credited=False, duplicate=True, reason=reason)
if results[0].already_counted_today:
reason = (
f"session {record_id} was logged, but today's slot for it was already "
"paid by another copy of the same workout; no extra time"
)
_logger.warning("Workout poke not credited: %s", reason)
return PokeOutcome(ok=True, credited=False, duplicate=False, reason=reason)
_logger.info("Workout poke credited session %s", record_id)
return PokeOutcome(
ok=True, credited=True, duplicate=False, reason="workout credited"
)
def credit_sessions(
records: Iterable[tuple[str, Mapping[str, object]]],
) -> BatchOutcome:
"""Reset the day if new, then ingest and credit a batch of synced sessions.
``SyncMixin._ingest_synced_sessions`` with one fresh locker for the whole
batch -- what the Firebase stream (:mod:`screen_locker._session_stream`)
runs per event. Already-logged ids cost one ``log.json`` read and write
nothing; invalid ones are warned about by the ingest itself.
"""
locker = fresh_locker()
locker.start_the_day()
results: list[WorkoutCreditResult] = []
def on_ingested(
entry: dict[str, str], prior_entries: list[dict[str, object]]
) -> None:
results.append(locker.credit_written(entry, prior_entries))
ingested = ingest_session_records(locker.log_file, records, on_ingested=on_ingested)
credited = sum(not result.already_counted_today for result in results)
if len(results) > credited:
_logger.warning(
"%d streamed session(s) were logged but earned no time: today's slot "
"was already paid by another copy of the same workout",
len(results) - credited,
)
return BatchOutcome(ingested=tuple(ingested), credited=credited)

View File

@ -0,0 +1,218 @@
"""The resident LAN listener that credits a phone workout within a second.
``workout-poke.service`` runs ``python3 -m screen_locker.poke_server``: a
stdlib ``ThreadingHTTPServer`` on ``0.0.0.0:8773`` (the firewall admits only
192.168.1.0/24) answering ``POST /v1/workout`` per
``docs/DOCS-workout-poke-contract.md``. Every import -- the locker, the
earned-time registry, gatelock -- is paid once at startup, so a request costs
only the credit itself.
The wire checks are pure (:mod:`screen_locker._poke_wire`); the crediting is
the sync's own ingest (:mod:`screen_locker._poke_credit`). One lock serialises
the nonce cache and every credit in this process; cross-process safety comes
from the locks the ingest and credit already hold.
"""
from __future__ import annotations
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import logging
import threading
import time
from typing import TYPE_CHECKING, Final
from screen_locker import _poke_credit
from screen_locker._poke_wire import (
NonceCache,
Rejection,
check_request,
)
if TYPE_CHECKING:
from screen_locker._poke_wire import PokeRequest
__all__ = ["MAX_BODY_BYTES", "POKE_PATH", "PokeServer"]
_logger: Final = logging.getLogger(__name__)
MAX_BODY_BYTES: Final = 64 * 1024
POKE_PATH: Final = "/v1/workout"
_HANDLER_TIMEOUT_S: Final = 10
def _reply(
outcome: _poke_credit.PokeOutcome,
*,
sandbox: bool = False,
snapshot: tuple[str | None, int | None] = (None, None),
) -> dict[str, object]:
"""The contract's response shape; ``pc_ms`` is filled in by the handler.
``snapshot`` is (tonight's shutdown ``HH:MM``, gaming minutes); refusals
leave it null rather than tell an unverified caller anything.
"""
shutdown, gaming = snapshot
return {
"ok": outcome.ok,
"credited": outcome.credited,
"duplicate": outcome.duplicate,
"sandbox": sandbox,
"shutdown": shutdown,
"gaming_budget_minutes": gaming,
"pc_ms": 0,
"reason": outcome.reason,
}
def _refused(reason: str) -> dict[str, object]:
"""A refusal's reply: not ok, nothing credited."""
return _reply(
_poke_credit.PokeOutcome(
ok=False, credited=False, duplicate=False, reason=reason
)
)
def _process(request: PokeRequest) -> dict[str, object]:
"""Credit (or, for a sandbox request, only answer) one verified poke."""
locker = _poke_credit.fresh_locker()
if request.sandbox:
outcome = _poke_credit.PokeOutcome(
ok=True,
credited=False,
duplicate=False,
reason="sandbox request verified; nothing written or credited",
)
else:
outcome = _poke_credit.credit_session(request.record_id, request.payload)
return _reply(
outcome,
sandbox=request.sandbox,
snapshot=(
_poke_credit.current_shutdown(),
_poke_credit.current_gaming_minutes(locker.log_file),
),
)
class PokeServer(ThreadingHTTPServer):
"""Holds the key, the nonce cache and the one credit lock."""
daemon_threads = True
def __init__(self, address: tuple[str, int], key: bytes) -> None:
"""Bind ``address`` and serve :class:`PokeHandler` with ``key``."""
super().__init__(address, PokeHandler)
self.key = key
self.nonces = NonceCache()
self.gate = threading.Lock()
class PokeHandler(BaseHTTPRequestHandler):
"""``POST /v1/workout``; anything else is answered 404/405 in JSON."""
server: PokeServer
timeout = _HANDLER_TIMEOUT_S
server_version = "workout-poke/1"
# The default access log (one stderr line per request) is kept: the
# journal is where it lands, and every refusal is also logged at warning.
def do_GET(self) -> None:
"""Only POST exists."""
self._send(
*self._refusal(
Rejection(
HTTPStatus.METHOD_NOT_ALLOWED, f"only POST {POKE_PATH} exists"
)
)
)
def do_POST(self) -> None:
"""Verify, credit and answer one poke; never let an error go unanswered."""
started = time.perf_counter()
try:
status, reply = self._handle()
except Exception:
_logger.exception("Workout poke from %s crashed", self.client_address[0])
status = HTTPStatus.INTERNAL_SERVER_ERROR
reply = _refused(
"the PC hit an internal error (see its journal); the "
"regular sync will still credit this session"
)
reply["pc_ms"] = round((time.perf_counter() - started) * 1000)
self._send(status, reply)
def _refusal(self, rejection: Rejection) -> tuple[HTTPStatus, dict[str, object]]:
"""Log a refusal at warning; the reply carries the same reason."""
_logger.warning(
"Workout poke from %s rejected (%d): %s",
self.client_address[0],
rejection.status,
rejection.reason,
)
return rejection.status, _refused(rejection.reason)
def _read_body(self) -> bytes | Rejection:
"""Exactly Content-Length bytes of ``POST /v1/workout``, capped.
Over :data:`MAX_BODY_BYTES` is refused before reading a byte of it.
"""
if self.path != POKE_PATH:
return Rejection(
HTTPStatus.NOT_FOUND, f"unknown path {self.path!r}; use {POKE_PATH}"
)
raw = self.headers.get("Content-Length")
if raw is None:
return Rejection(HTTPStatus.LENGTH_REQUIRED, "Content-Length is required")
length = int(raw) if raw.strip().isdigit() else -1
if length < 0:
return Rejection(HTTPStatus.BAD_REQUEST, f"bad Content-Length {raw!r}")
if length > MAX_BODY_BYTES:
return Rejection(
HTTPStatus.REQUEST_ENTITY_TOO_LARGE,
f"body is {length} bytes; the limit is {MAX_BODY_BYTES}",
)
body = self.rfile.read(length)
if len(body) != length:
return Rejection(
HTTPStatus.BAD_REQUEST,
f"body ended after {len(body)} of {length} bytes",
)
return body
def _handle(self) -> tuple[HTTPStatus, dict[str, object]]:
"""Run the contract's checks, then credit; returns (status, reply)."""
body = self._read_body()
if isinstance(body, Rejection):
return self._refusal(body)
with self.server.gate:
verdict = check_request(
self.server.key,
body,
self.headers.get("X-Poke-Signature"),
self.server.nonces,
now_ms=time.time_ns() // 1_000_000,
)
if isinstance(verdict, Rejection):
return self._refusal(verdict)
reply = _process(verdict)
_logger.info(
"Workout poke %s (sandbox=%s): %s",
verdict.record_id,
verdict.sandbox,
reply["reason"],
)
return HTTPStatus.OK, reply
def _send(self, status: HTTPStatus, reply: dict[str, object]) -> None:
"""Write ``reply`` as a JSON response and close the connection."""
data = json.dumps(reply, ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.send_header("Connection", "close")
self.end_headers()
self.wfile.write(data)

218
screen_locker/_poke_wire.py Normal file
View File

@ -0,0 +1,218 @@
"""Phone -> PC workout poke: the wire checks, pure and stdlib-only.
The binding contract is ``docs/DOCS-workout-poke-contract.md`` and its literal
fixture ``contracts/workout_poke_v1.json``. Everything here is a pure function
of its inputs (``now_ms`` is a parameter, never read from a clock), so the
shared-fixture test can feed it the fixture's bytes as-is. The HTTP plumbing
lives in :mod:`screen_locker._poke_server`, the crediting in
:mod:`screen_locker._poke_credit`.
The MAC is computed over the raw body bytes *as received*; nothing here ever
re-serializes JSON, because a Dart and a Python encoder disagree on floats and
non-ASCII escaping.
"""
from __future__ import annotations
from dataclasses import dataclass
import hashlib
import hmac
from http import HTTPStatus
import json
import logging
from typing import Final
__all__ = [
"REPLAY_WINDOW_MS",
"NonceCache",
"PokeRequest",
"Rejection",
"check_request",
"parse_key",
"verify_signature",
]
PROTOCOL_VERSION: Final = 1
REPLAY_WINDOW_MS: Final = 120_000
KEY_HEX_LENGTH: Final = 64
_logger: Final = logging.getLogger(__name__)
@dataclass(frozen=True)
class PokeRequest:
"""A request that passed every contract check.
Attributes:
sent_at_ms: The phone's send time, epoch milliseconds.
nonce: The request's one-time id.
sandbox: Verify and answer, but write and credit nothing.
record_id: The session's sync record id.
payload: The session exactly as the phone synced it.
"""
sent_at_ms: int
nonce: str
sandbox: bool
record_id: str
payload: dict[str, object]
@dataclass(frozen=True)
class Rejection:
"""Why a request was refused, and with which HTTP status."""
status: HTTPStatus
reason: str
def parse_key(text: str) -> bytes:
"""Decode the shared key file's content (64 hex chars, 32 bytes).
Raises:
ValueError: With a sentence saying what is wrong with the key.
"""
stripped = text.strip()
if len(stripped) != KEY_HEX_LENGTH:
msg = f"key must be {KEY_HEX_LENGTH} hex characters, got {len(stripped)}"
raise ValueError(msg)
try:
return bytes.fromhex(stripped)
except ValueError as exc:
msg = f"key is not valid hex ({exc})"
raise ValueError(msg) from exc
def verify_signature(key: bytes, body: bytes, signature_header: str | None) -> bool:
"""True iff ``signature_header`` is hex HMAC-SHA256(key, body).
Compared as bytes: the header arrives latin-1 decoded, and
``hmac.compare_digest`` raises on a non-ASCII ``str``.
"""
if not signature_header:
return False
expected = hmac.new(key, body, hashlib.sha256).hexdigest().encode("ascii")
given = signature_header.strip().lower().encode("latin-1", errors="replace")
return hmac.compare_digest(expected, given)
class NonceCache:
"""Nonces seen inside the replay window, pruned by their ``sent_at``.
Pruned by the request's own send time, not by when it arrived: a request
stamped up to 120 s in the future stays acceptable until ``sent_at + 120
s``, so its nonce must be remembered at least that long.
"""
def __init__(self) -> None:
"""Start empty; the window is :data:`REPLAY_WINDOW_MS`."""
self._seen: dict[str, int] = {}
def check_and_add(self, nonce: str, sent_at_ms: int, now_ms: int) -> bool:
"""Record ``nonce``; False if it was already seen inside the window."""
self._seen = {
seen: sent
for seen, sent in self._seen.items()
if now_ms - sent <= REPLAY_WINDOW_MS
}
if nonce in self._seen:
return False
self._seen[nonce] = sent_at_ms
return True
def __len__(self) -> int:
"""How many nonces are remembered right now."""
return len(self._seen)
def _is_int(value: object) -> bool:
"""An ``int`` that is not a ``bool`` (JSON ``true`` decodes to one)."""
return isinstance(value, int) and not isinstance(value, bool)
def _schema_error(doc: dict[str, object]) -> str | None:
"""The first missing or mistyped field after the replay checks, if any."""
if not _is_int(doc.get("v")) or doc.get("v") != PROTOCOL_VERSION:
return f"unsupported protocol version {doc.get('v')!r}; expected 1"
if not isinstance(doc.get("sandbox"), bool):
return "field 'sandbox' must be true or false"
record_id = doc.get("record_id")
if not isinstance(record_id, str) or not record_id:
return "field 'record_id' must be a non-empty string"
if not isinstance(doc.get("payload"), dict):
return "field 'payload' must be a JSON object"
return None
def _decode(body: bytes) -> dict[str, object] | Rejection:
"""The verified body as a JSON object, or a 400."""
try:
doc = json.loads(body.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
# Signed by the key holder yet unparsable: a sender bug, not noise.
_logger.warning("Poke body is signed but not UTF-8 JSON: %s", exc)
return Rejection(HTTPStatus.BAD_REQUEST, f"body is not UTF-8 JSON ({exc})")
if not isinstance(doc, dict):
return Rejection(HTTPStatus.BAD_REQUEST, "body is not a JSON object")
return doc
def _replay_check(
doc: dict[str, object], nonces: NonceCache, now_ms: int
) -> tuple[int, str] | Rejection:
"""Checks 2 and 3: fresh enough (401), nonce unseen (409).
Returns ``(sent_at_ms, nonce)``; a missing or mistyped field either check
needs is a 400 at that point.
"""
sent_at = doc.get("sent_at_ms")
if not isinstance(sent_at, int) or isinstance(sent_at, bool):
return Rejection(HTTPStatus.BAD_REQUEST, "field 'sent_at_ms' must be an int")
if abs(now_ms - sent_at) > REPLAY_WINDOW_MS:
return Rejection(
HTTPStatus.UNAUTHORIZED,
f"request is stale: sent_at_ms is {(now_ms - sent_at) / 1000:+.0f} s "
"off the PC clock (+ = in the past), the window is 120 s; check "
"the phone's clock",
)
nonce = doc.get("nonce")
if not isinstance(nonce, str) or not nonce:
return Rejection(HTTPStatus.BAD_REQUEST, "field 'nonce' must be a string")
if not nonces.check_and_add(nonce, sent_at, now_ms):
return Rejection(HTTPStatus.CONFLICT, f"nonce {nonce} was already used")
return sent_at, nonce
def check_request(
key: bytes,
body: bytes,
signature_header: str | None,
nonces: NonceCache,
now_ms: int,
) -> PokeRequest | Rejection:
"""Run the contract's checks in order; the first failure wins.
1. signature -> 401, 2. ``|now - sent_at| <= 120 s`` -> 401,
3. nonce unseen -> 409, 4. ``v == 1`` and fields present -> 400.
JSON is parsed only after the MAC over the raw bytes matched.
"""
if not verify_signature(key, body, signature_header):
return Rejection(HTTPStatus.UNAUTHORIZED, "signature does not match the key")
doc = _decode(body)
if isinstance(doc, Rejection):
return doc
replay = _replay_check(doc, nonces, now_ms)
if isinstance(replay, Rejection):
return replay
problem = _schema_error(doc)
if problem is not None:
return Rejection(HTTPStatus.BAD_REQUEST, problem)
sent_at, nonce = replay
payload = doc["payload"]
return PokeRequest(
sent_at_ms=sent_at,
nonce=nonce,
sandbox=doc["sandbox"] is True,
record_id=str(doc["record_id"]),
payload=dict(payload) if isinstance(payload, dict) else {},
)

View File

@ -1,54 +0,0 @@
"""Turning a completed push into an honest result.
Split out of :mod:`screen_locker._manual_push` to keep every file under the
250-line cap.
A push that the primary backend refused still reaches the GitHub mirror, and
the records are not lost -- the phone reads the union of both. What must not
happen is that half-landed push logging the same line as a whole one, which is
how weeks of broken Firebase pushes looked healthy in the journal.
"""
from __future__ import annotations
import logging
from screen_locker._constants import SYNC_REPO_NAME, SYNC_REPO_OWNER
from screen_locker._degraded_sources import degraded_sources
_logger = logging.getLogger(__name__)
def describe_push(record_count: int) -> tuple[bool, str]:
"""Report whether every backend received the records, and say so.
Args:
record_count: How many records the push carried.
Returns:
``(complete, reason)`` -- ``reason`` reads like a sentence either way,
because it is what ``PushResult`` carries back to the caller.
"""
missing = [source.name for source in degraded_sources()]
if not missing:
_logger.info(
"Synced %d workout(s) to %s/%s",
record_count,
SYNC_REPO_OWNER,
SYNC_REPO_NAME,
)
return True, "pushed"
names = ", ".join(missing)
reason = (
f"pushed to {SYNC_REPO_OWNER}/{SYNC_REPO_NAME} only; "
f"{names} did NOT receive these records"
)
_logger.warning(
"Workout sync push INCOMPLETE for %d workout(s): %s — the phone reads "
"both backends, so this still syncs, but %s is broken and must be "
"fixed before it is the only path left",
record_count,
reason,
names,
)
return False, reason

View File

@ -0,0 +1,119 @@
"""Pure parsing for a Firebase RTDB REST stream of the device-log node.
``GET <db>/screen-locker-sync/devices.json`` with ``Accept: text/event-stream``
answers with Server-Sent Events: ``put``/``patch`` carry
``{"path": ..., "data": ...}`` relative to the streamed node, plus
``keep-alive``, ``cancel`` and ``auth_revoked``. Everything here is network-free
so it can be unit-tested; the connection itself is
:mod:`screen_locker._session_stream`.
Each device log is ONE JSON-string leaf at ``<device>/log~2Ejson``
(``crdt_sync._fbkeys`` escapes the dot), so an event normalises to "these
devices now hold this text (or nothing)".
"""
from __future__ import annotations
from dataclasses import dataclass
import json
from typing import TYPE_CHECKING, Final
from crdt_sync._firebase import decode_key
if TYPE_CHECKING:
from collections.abc import Iterable, Iterator
__all__ = ["LOG_LEAF", "SseEvent", "device_updates", "parse_sse"]
LOG_LEAF: Final = "log.json"
@dataclass(frozen=True)
class SseEvent:
"""One Server-Sent Event: its name and its (joined) data lines."""
name: str
data: str
def parse_sse(lines: Iterable[str]) -> Iterator[SseEvent]:
"""Yield events from decoded SSE lines; a blank line ends each event."""
name = ""
data: list[str] = []
for line in lines:
if not line:
if name or data:
yield SseEvent(name or "message", "\n".join(data))
name, data = "", []
elif line.startswith("event:"):
name = line[len("event:") :].strip()
elif line.startswith("data:"):
data.append(line[len("data:") :].lstrip())
def _segments(path: str) -> list[str]:
"""``/a/b~2Ec`` -> ``["a", "b.c"]`` (decoded, empty segments dropped)."""
return [decode_key(part) for part in path.split("/") if part]
def _texts_under(segments: list[str], data: object) -> dict[str, str | None]:
"""Device -> log text for a ``put`` of ``data`` at ``segments``.
``None`` means that device's log is gone (deleted, or not a text blob --
the latter is the caller's to warn about, see :func:`device_updates`).
Raises:
TypeError: The data does not have the device-node shape at all.
"""
if not segments: # the whole node: {device: {leaf: text}}
if data is None:
return {}
if not isinstance(data, dict):
msg = f"devices node is {type(data).__name__}, not an object"
raise TypeError(msg)
return {decode_key(key): _leaf_text(value) for key, value in data.items()}
device = segments[0]
if len(segments) == 1:
return {device: _leaf_text(data)}
if segments[1:] == [LOG_LEAF]:
return {device: data if isinstance(data, str) else None}
return {} # something below a device that is not its log: irrelevant
def _leaf_text(device_node: object) -> str | None:
"""The log text inside one ``{leaf: text}`` device node, if any."""
if not isinstance(device_node, dict):
return None
for key, value in device_node.items():
if decode_key(key) == LOG_LEAF and isinstance(value, str):
return value
return None
def device_updates(event: SseEvent) -> tuple[bool, dict[str, str | None]]:
"""Normalise a ``put``/``patch`` into ``(is_full_snapshot, updates)``.
``updates`` maps a device id to its log's new full text, or ``None`` when
it no longer has one. A ``put`` at ``/`` is a full snapshot: the caller
must REPLACE its cache, since devices missing from it are gone. A
``patch`` carries several children whose keys may be multi-segment paths.
Raises:
ValueError: The data is not JSON.
TypeError: The JSON is not the documented ``{path, data}`` shape.
"""
body = json.loads(event.data)
if not isinstance(body, dict) or not isinstance(body.get("path"), str):
msg = f"{event.name} event without a path: {event.data[:120]!r}"
raise TypeError(msg)
base = _segments(body["path"])
if event.name == "put":
return not base, _texts_under(base, body.get("data"))
children = body.get("data")
if not isinstance(children, dict):
msg = f"patch data is {type(children).__name__}, not an object"
raise TypeError(msg)
updates: dict[str, str | None] = {}
for key, value in children.items():
updates.update(_texts_under([*base, *_segments(key)], value))
return False, updates

View File

@ -0,0 +1,232 @@
"""Off-LAN instant credit: hold a Firebase RTDB stream of the device logs.
Off the home LAN the phone's only transport is Firebase, so without this a
finished session waits up to 15 minutes for ``workout-sync.timer``. This
thread, inside ``workout-poke.service``, keeps ``GET
<db>/screen-locker-sync/devices.json`` open as Server-Sent Events and credits
each newly streamed session within about a second
(:class:`screen_locker._stream_cache.DeviceLogCache`).
Free-tier budget (Spark: 10 GB/month download, no per-read quota). Every
(re)connect downloads the whole devices node once: 375,755 bytes measured on
2026-10-09 (18 device dirs; logged with each snapshot, after transfer
decoding, so an upper bound on the wire). The ID token lives one hour, so
that is ~24 snapshots a day, ~9 MB: less than the 15-min sync, which fetches
every device log on every tick. After the snapshot, a write streams only the
written device's whole log: ~83 KB for the current phone, ~43 KB for each PC
push. RTDB sends NO event for a byte-identical write (observed), and the
phone's home-screen ``syncNow`` skips the write when its log is unchanged, so
no-op syncs cost nothing. Nothing here issues a read beyond the stream.
Every failure is logged at warning or above with what it means, the thread
backs off (1 s doubling to 60 s, jittered) and never touches the HTTP
listener. The sync stays the safety net: the stream only makes credit faster.
"""
from __future__ import annotations
from datetime import UTC, datetime
import logging
import random
import threading
import time
from typing import TYPE_CHECKING, Final
import requests
import urllib3
from screen_locker._device import device_identity
from screen_locker._rtdb_stream import parse_sse
from screen_locker._stream_auth import StreamError, stream_auth
from screen_locker._stream_cache import DeviceLogCache
from screen_locker._workout_sync import _DEVICES_PREFIX
if TYPE_CHECKING:
from collections.abc import Iterator
from screen_locker._rtdb_stream import SseEvent
__all__ = ["SessionStream"]
_logger: Final = logging.getLogger(__name__)
_FALLBACK: Final = (
"off-LAN workouts will only be credited by the 15-min workout-sync until "
"this recovers"
)
_BACKOFF_MIN_S: Final = 1.0
_BACKOFF_MAX_S: Final = 60.0
# RTDB sends a keep-alive every ~30 s; silence past this means a dead socket.
_TIMEOUT_S: Final = (10, 90)
_LOGGED_KEEPALIVES: Final = 3
_HTTP_AUTH_REJECTED: Final = (401, 403)
# A connection that ends sooner than this pays a backoff even when the end was
# planned (auth_revoked, renewal): no path may reconnect in a tight loop, and
# each reconnect re-downloads the snapshot.
_MIN_LIFETIME_S: Final = 300.0
_STREAM_ERRORS: Final = (
requests.RequestException,
urllib3.exceptions.HTTPError,
OSError,
)
_JITTER: Final = random.SystemRandom()
class SessionStream:
"""A daemon thread holding the stream; one connection at a time."""
def __init__(self, gate: threading.Lock) -> None:
"""``gate`` is the poke server's credit lock, so credits never race."""
identity = device_identity()
self._cache = DeviceLogCache(
_DEVICES_PREFIX,
frozenset({identity.device_id, identity.legacy_id}),
gate,
)
self._http = requests.Session()
self._stop = threading.Event()
self._got_snapshot = False
def start(self) -> threading.Thread:
"""Run :meth:`run_forever` on a daemon thread and return it."""
thread = threading.Thread(
target=self.run_forever, name="firebase-session-stream", daemon=True
)
thread.start()
return thread
def stop(self) -> None:
"""Ask the loop to exit after the current connection."""
self._stop.set()
def run_forever(self) -> None:
"""Connect, stream, back off on failure; never raise out of the thread."""
delay = _BACKOFF_MIN_S
while not self._stop.is_set():
self._got_snapshot = False
opened = time.monotonic()
planned = self._run_one()
lived = time.monotonic() - opened >= _MIN_LIFETIME_S
if self._got_snapshot and lived:
delay = _BACKOFF_MIN_S
if planned and lived:
continue # a long-lived connection ending on schedule
pause = delay * _JITTER.uniform(0.5, 1.0)
delay = min(delay * 2, _BACKOFF_MAX_S)
_logger.warning("Reconnecting the session stream in %.1f s", pause)
self._stop.wait(pause)
def _run_one(self) -> bool:
"""One connection; True if it ended on purpose (renewal, auth_revoked)."""
try:
self._connect_once()
except StreamError as exc:
_logger.warning("Firebase session stream failed: %s; %s", exc, _FALLBACK)
return False
except Exception:
_logger.exception("Firebase session stream crashed; %s", _FALLBACK)
return False
return True
def _connect_once(self) -> None:
"""One connection; returns only when it ended on purpose.
Raises:
StreamError: Auth, HTTP or protocol failure.
"""
auth = stream_auth(_DEVICES_PREFIX)
try:
response = self._http.get(
auth.url,
params={"auth": auth.token},
headers={"Accept": "text/event-stream"},
stream=True,
timeout=_TIMEOUT_S,
)
except _STREAM_ERRORS as exc:
msg = f"network error opening the stream: {exc}"
raise StreamError(msg) from exc
with response:
if not response.ok:
kind = (
"rejected (token or rules)"
if response.status_code in _HTTP_AUTH_REJECTED
else "failed"
)
msg = (
f"stream {kind}: HTTP {response.status_code} {response.text[:200]}"
)
raise StreamError(msg)
_logger.info("Firebase session stream connected to %s", _DEVICES_PREFIX)
self._consume(response, auth.renew_at)
def _consume(self, response: requests.Response, renew_at: datetime) -> None:
"""Dispatch events until the server or the renew deadline ends it.
Raises:
StreamError: The stream broke, was cancelled or closed unasked.
"""
meter = _ByteMeter()
keepalives = 0
try:
for event in parse_sse(meter.lines(response)):
if event.name == "keep-alive":
keepalives += 1
if keepalives <= _LOGGED_KEEPALIVES:
_logger.info("Session stream keep-alive #%d", keepalives)
elif event.name in {"put", "patch"}:
self._dispatch(event, meter.total)
elif event.name == "auth_revoked":
_logger.warning(
"Session stream token revoked/expired (%s); reconnecting",
event.data,
)
return
elif event.name == "cancel":
msg = f"the database cancelled the stream ({event.data})"
raise StreamError(msg)
else:
_logger.warning("Session stream ignored event %r", event.name)
if datetime.now(UTC) >= renew_at:
_logger.info("Session stream renewing its ID token before expiry")
return
except _STREAM_ERRORS as exc:
msg = f"stream broke after {meter.total} bytes: {exc}"
raise StreamError(msg) from exc
msg = f"the server closed the stream after {meter.total} bytes"
raise StreamError(msg)
def _dispatch(self, event: SseEvent, total_bytes: int) -> None:
"""Hand one put/patch to the cache and log what it did."""
try:
result = self._cache.handle(event)
except (ValueError, TypeError) as exc:
_logger.warning("Session stream event undecodable (%s); %s", exc, _FALLBACK)
return
self._got_snapshot |= result.snapshot
_logger.info(
"Session stream %s (%d bytes read on this connection): %s",
"snapshot" if result.snapshot else event.name,
total_bytes,
result.summary,
)
class _ByteMeter:
"""Splits the raw stream into lines as bytes arrive, counting them."""
def __init__(self) -> None:
self.total = 0
def lines(self, response: requests.Response) -> Iterator[str]:
"""Yield decoded lines without waiting for a full read buffer.
``iter_lines`` reads fixed-size chunks and would sit on a 30-byte
keep-alive until more data came; ``read1`` returns what has arrived.
"""
pending = b""
while chunk := response.raw.read1(65536):
self.total += len(chunk)
*complete, pending = (pending + chunk).split(b"\n")
for line in complete:
yield line.rstrip(b"\r").decode("utf-8")

View File

@ -44,7 +44,7 @@ def describe_staleness(
"""Return a finding when *name*'s newest record is too old, else None.
Args:
name: The backend, as the user would name it ("GitHub mirror").
name: The backend, as the user would name it ("Firebase").
newest: Timestamp of the most recent record it returned, or None when
it returned nothing at all.
now: Injected for tests.

View File

@ -0,0 +1,93 @@
"""The ID token and URL for the Firebase session stream.
Split out of :mod:`screen_locker._session_stream` for the 250-line cap.
Reuses crdt_sync's own token provider and the screen_locker credential cache
(``~/.config/screen_locker/firebase_auth.json``); it never signs in with the
password, which is stale -- only the cached refresh token authenticates. A
missing session is healed the way the sync heals it,
:func:`screen_locker._sync_client.try_recover_firebase_session`.
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import Final
from crdt_sync import (
ConfigError,
FirebaseAuthError,
FirebaseConfig,
FirebaseTokenProvider,
credential_store_for,
)
from crdt_sync._firebase import encode_path
from screen_locker._sync_client import try_recover_firebase_session
__all__ = ["StreamAuth", "StreamError", "stream_auth"]
_APP: Final = "screen_locker"
# Inside crdt_sync's 5-minute refresh skew, so the reconnect mints a new token
# instead of being handed the dying one back.
_RENEW_BEFORE_EXPIRY: Final = timedelta(minutes=4)
_ASSUMED_LIFETIME: Final = timedelta(hours=1)
class StreamError(Exception):
"""One stream connection failed in a way that warrants backing off."""
@dataclass(frozen=True)
class StreamAuth:
"""Where to stream from, with which token, and when to renew it."""
url: str
token: str
renew_at: datetime
def _provider(config: FirebaseConfig) -> FirebaseTokenProvider:
"""A provider over the cached session, recovering one if there is none.
Raises:
StreamError: No cached session, and recovery failed too.
"""
store = credential_store_for(_APP)
auth = FirebaseTokenProvider(config.api_key, store)
if auth.has_session():
return auth
recovery = try_recover_firebase_session()
if not recovery.recovered:
msg = f"no cached Firebase session and recovery failed: {recovery.reason}"
raise StreamError(msg)
return FirebaseTokenProvider(config.api_key, store)
def stream_auth(path: str) -> StreamAuth:
"""A fresh token for streaming ``path`` (a logical RTDB path).
A new provider per call re-reads the cache, so a token the 15-min sync
refreshed in the meantime is picked up rather than refreshed again.
Raises:
StreamError: The config, the session or the token is unusable.
"""
try:
config = FirebaseConfig.load()
except ConfigError as exc:
msg = f"Firebase config unusable: {exc}"
raise StreamError(msg) from exc
auth = _provider(config)
try:
token = auth.id_token()
except FirebaseAuthError as exc:
msg = f"could not get an ID token: {exc}"
raise StreamError(msg) from exc
saved = credential_store_for(_APP).load()
expires = saved.expires_at if saved else datetime.now(UTC) + _ASSUMED_LIFETIME
return StreamAuth(
url=f"{config.database_url.rstrip('/')}/{encode_path(path)}.json",
token=token,
renew_at=expires - _RENEW_BEFORE_EXPIRY,
)

View File

@ -0,0 +1,153 @@
"""What the Firebase stream does with one ``put``/``patch``: cache, merge, credit.
Holds every device's last-seen log text, so each event recomputes the
cross-device union with the sync's OWN decoder and tombstone rule
(:func:`screen_locker._sync_records.merge_device_texts`) without a single
extra Firebase read. The PC's own log stays in the union -- it carries the
tombstones ``_manual_push`` re-publishes every tick, and dropping it would
let a retracted session be credited again -- but an event that touched only
this PC's log never triggers a pass.
Crediting is :func:`screen_locker._poke_credit.credit_sessions` under the
same in-process lock as the LAN poke handler. ``write_signed_entry`` already
dedups by workout id; the ``seen`` set here only spares the file I/O for
records this daemon has already handed to the ingest.
"""
from __future__ import annotations
from dataclasses import dataclass
import logging
import time
from typing import TYPE_CHECKING, Final
from screen_locker import _poke_credit
from screen_locker._rtdb_stream import LOG_LEAF, device_updates
from screen_locker._sync_records import _session_records, merge_device_texts
if TYPE_CHECKING:
import threading
from screen_locker._rtdb_stream import SseEvent
__all__ = ["DeviceLogCache", "EventResult"]
_logger: Final = logging.getLogger(__name__)
@dataclass(frozen=True)
class EventResult:
"""What one event did, as a sentence for the journal."""
snapshot: bool
summary: str
class DeviceLogCache:
"""Every device's last-streamed log text, plus records already ingested."""
def __init__(
self, prefix: str, own_ids: frozenset[str], gate: threading.Lock
) -> None:
"""Cache logs under ``prefix``; ``own_ids`` are this PC's device dirs."""
self._prefix = prefix
self._own_ids = own_ids
self._gate = gate
self._texts: dict[str, str] = {}
self._seen: set[tuple[str, str]] = set()
def _apply(self, updates: dict[str, str | None], *, full: bool) -> set[str]:
"""Fold ``updates`` into the cache; return the devices that changed."""
if full:
fresh = {dev: text for dev, text in updates.items() if text is not None}
changed = {
dev
for dev in fresh.keys() | self._texts.keys()
if fresh.get(dev) != self._texts.get(dev)
}
self._texts = fresh
return changed
changed = set()
for dev, text in updates.items():
if text == self._texts.get(dev):
continue # byte-identical rewrite: nothing to read or credit
changed.add(dev)
if text is None:
self._texts.pop(dev, None)
else:
self._texts[dev] = text
return changed
def _pending(self) -> list[tuple[str, dict[str, object], str]]:
"""Union records this daemon has not yet handed to the ingest."""
union = merge_device_texts(
(
(f"{self._prefix}/{dev}/{LOG_LEAF}", text)
for dev, text in sorted(self._texts.items())
),
_session_records,
"sessions",
)
return [
(rid, payload, str(hlc))
for rid, (payload, hlc) in sorted(union.items())
if (rid, str(hlc)) not in self._seen
]
def handle(self, event: SseEvent) -> EventResult:
"""Apply one ``put``/``patch`` and credit whatever it newly brought.
Raises:
ValueError: The event's data is not JSON.
TypeError: The JSON is not the documented ``{path, data}`` shape.
"""
started = time.perf_counter()
full, updates = device_updates(event)
changed = self._apply(updates, full=full)
devices = ", ".join(sorted(changed)) or "none"
if not full and not changed:
return EventResult(
snapshot=False, summary="byte-identical rewrite; nothing to do"
)
foreign = changed - self._own_ids
if not full and not foreign:
return EventResult(
snapshot=False,
summary=f"only this PC's own log changed ({devices}); no credit",
)
pending = self._pending()
if not pending:
return EventResult(
snapshot=full,
summary=f"{len(self._texts)} device log(s) cached, changed: {devices}; "
f"every session already handed to the ingest -- no-op, no file I/O "
f"({_ms(started)} ms)",
)
try:
with self._gate:
outcome = _poke_credit.credit_sessions(
[(rid, payload) for rid, payload, _hlc in pending]
)
except Exception:
# Not a stream problem: keep the connection (a reconnect would
# re-download the snapshot and fail the same way). Nothing is
# marked seen, so the next event retries.
_logger.exception(
"Crediting %d streamed session(s) failed; the next stream event "
"retries, and the 15-min workout-sync still covers them",
len(pending),
)
return EventResult(snapshot=full, summary="crediting failed (see above)")
self._seen.update((rid, hlc) for rid, _payload, hlc in pending)
return EventResult(
snapshot=full,
summary=f"{len(self._texts)} device log(s) cached, changed: {devices}; "
f"{len(pending)} session(s) checked, {len(outcome.ingested)} newly "
f"logged {list(outcome.ingested)}, {outcome.credited} credited "
f"({_ms(started)} ms)",
)
def _ms(started: float) -> int:
"""Milliseconds since ``started`` (a ``perf_counter`` reading)."""
return round((time.perf_counter() - started) * 1000)

View File

@ -1,4 +1,4 @@
"""Building the sync client: read the token, pick Firebase or the GitHub mirror.
"""Building the sync client: Firebase only, proven live before it is returned.
Split out of :mod:`screen_locker._workout_sync` to keep every file under the
250-line cap. Re-exported from there, so callers and their patch targets are
@ -6,6 +6,12 @@ unchanged.
``sync_client`` returning None means sync is OFF -- and says why in the log,
because a silent None here is exactly how the PC stopped syncing for weeks.
Firebase is the only transport since 2026-10-09. The GitHub mirror
(``kuhyx/syncs/screen-locker-sync``) is a frozen archive: nothing here reads
or writes it, and nothing deletes it. The PC used to refuse to push at all
without a GitHub PAT, even with Firebase configured -- so when the PAT was
lost, this machine silently published nothing.
"""
from __future__ import annotations
@ -17,24 +23,16 @@ from pathlib import Path
from crdt_sync import (
CONFIG_FILE,
ConfigError,
FirebaseAuthError,
FirebaseConfig,
FirebaseCredentials,
GitHubSyncClient,
RemoteStore,
RemoteSyncError,
credential_store_for,
firebase_client_for,
mirror_client_for,
)
import requests
from screen_locker._constants import (
SYNC_REPO_NAME,
SYNC_REPO_OWNER,
SYNC_TIMEOUT_SECONDS,
SYNC_TOKEN_FILE,
)
from screen_locker._constants import SYNC_TIMEOUT_SECONDS
from screen_locker._credential_recovery import RecoveryResult, recover_session
from screen_locker._degraded_sources import (
DegradedSource,
@ -53,9 +51,8 @@ __all__ = [
"DegradedSource",
"clear_degraded_sources",
"degraded_sources",
"read_sync_token",
"remote_client",
"sync_client",
"sync_client_or_reason",
"try_recover_firebase_session",
]
@ -96,27 +93,22 @@ def try_recover_firebase_session() -> RecoveryResult:
)
def read_sync_token() -> str | None:
"""Return the saved sync PAT, or None if sync isn't configured.
Unlike diet_guard's equivalent, an absent or empty token file is a
normal state here -- sync is an optional primary channel, not something
the app requires to function.
"""
if not SYNC_TOKEN_FILE.exists():
return None
token = SYNC_TOKEN_FILE.read_text().strip()
return token or None
# What a missing or broken Firebase costs, in both directions -- named in every
# warning so the journal says what is lost, not just that something failed.
_CONSEQUENCE = (
"this PC's workouts will NOT be pushed and phone-logged workouts will "
"NOT be pulled, so only ADB/HTTP can verify a phone workout here"
)
def _live_mirror_client(github: RemoteStore) -> tuple[RemoteStore | None, str]:
"""Build the mirrored client, but only return one that actually answers.
def _live_firebase_client() -> tuple[RemoteStore | None, str]:
"""Build the Firebase client, but only return one that actually answers.
Constructing is not proving. ``mirror_client_for`` only asks
Constructing is not proving. ``firebase_client_for`` only asks
``has_session()``, which reads the cached JSON off disk and never touches
the network, so a credential that is *present but rejected* builds
perfectly and then 401s on every single read and write. That is exactly
what happened on 2026-08-27: the recovery below was wired to construction
what happened on 2026-08-27: the recovery was wired to construction
failures, the construction succeeded, and so the self-heal never fired
while every operation was being refused.
@ -129,117 +121,66 @@ def _live_mirror_client(github: RemoteStore) -> tuple[RemoteStore | None, str]:
``(client, "")`` when Firebase answered, else ``(None, reason)``.
"""
try:
client = mirror_client_for("screen_locker", github)
except (ConfigError, FirebaseAuthError, RemoteSyncError) as exc:
client = firebase_client_for(
"screen_locker", timeout_seconds=SYNC_TIMEOUT_SECONDS
)
except (ConfigError, RemoteSyncError) as exc:
# The reason travels back to the caller, which decides whether to heal
# or degrade -- but it is logged here too, so the originating failure
# or give up -- but it is logged here too, so the originating failure
# is on the record even when a later recovery masks it.
_logger.warning("Could not build the Firebase client: %s", exc)
return None, str(exc)
if not client.can_access_remote():
return None, (
"the cached Firebase credential was rejected by the server — it "
"exists on disk, so nothing failed while connecting, but every "
"read and write is being refused"
"the cached Firebase credential was rejected by the server, or "
"the database is unreachable — every read and write is refused"
)
return client, ""
def remote_client(github: RemoteStore) -> RemoteStore:
"""Return the backend to read the phone's workout log from.
Firebase when ``~/.config/crdt-sync/`` is set up, with GitHub kept as a
mirror so a phone that has not moved yet is still seen; GitHub alone
otherwise. :class:`MirrorSyncClient` reads the union of both, so a workout
logged against either backend still counts.
Not read-only: ``_manual_push.push_pc_workouts`` writes this machine's log
through the client this returns. That matters for the degraded path --
when Firebase is dropped here the push still lands on GitHub, which the
phone also reads, so records are not lost; ``_manual_push`` reports the
push as INCOMPLETE rather than letting a half-landed push look clean.
def sync_client_or_reason() -> tuple[RemoteStore | None, str]:
"""Return a live Firebase client, or None and the reason there is none.
The config file is checked before constructing anything, so an
unconfigured machine never reaches the network.
unconfigured machine never reaches the network. A configured but failing
Firebase is healed from a sibling app's session when possible (waiting
for a human to copy a JSON file is what cost 2026-06-12 and 2026-08-24 --
two workouts done, two lockouts anyway); if that fails too, the failure is
recorded as a degraded source so an empty pull is never reported as
"no workouts".
Rolling back is deleting this function and passing ``github`` straight
through: no data moves either way.
Returns:
``(client, "")`` on success, else ``(None, reason)`` -- ``reason`` is a
sentence a caller can put straight into its own result.
"""
if not CONFIG_FILE.is_file():
return github
usable, reason = _live_mirror_client(github)
if usable is not None:
return usable
# Before degrading, try to heal: a sibling app on this machine almost
# certainly holds a live refresh token for the same account. Waiting
# for a human to copy a JSON file is what cost 2026-06-12 and
# 2026-08-24 -- two workouts done, two lockouts anyway.
reason = f"no Firebase config at {CONFIG_FILE}"
_logger.warning("Sync is OFF: %s — %s", reason, _CONSEQUENCE)
return None, reason
client, reason = _live_firebase_client()
if client is not None:
return client, ""
recovery = try_recover_firebase_session()
if recovery.recovered:
retried, retry_reason = _live_mirror_client(github)
retried, retry_reason = _live_firebase_client()
if retried is not None:
_logger.info("Firebase recovered automatically: %s", recovery.reason)
return retried
_logger.warning(
"Firebase still unusable after %s: %s", recovery.reason, retry_reason
)
_record_degraded("firebase", retry_reason)
return github
return retried, ""
reason = f"still unusable after {recovery.reason}: {retry_reason}"
else:
reason = f"{reason}; automatic recovery failed: {recovery.reason}"
_logger.warning(
"Firebase unavailable, reading workouts via GitHub only: %s — the "
"phone syncs to Firebase, so a workout logged there is INVISIBLE "
"on this machine until this is fixed. Automatic recovery also "
"failed: %s",
reason,
recovery.reason,
"Firebase is configured but unusable: %s — %s", reason, _CONSEQUENCE
)
_record_degraded("firebase", f"{reason}; recovery: {recovery.reason}")
return github
_record_degraded("firebase", reason)
return None, f"Firebase unusable: {reason}"
def sync_client() -> RemoteStore | None:
"""Return the configured read client, or None if sync is set up nowhere.
"""Return the live Firebase client, or None when sync cannot run.
A GitHub token is no longer required: Firebase has been the primary backend
since eb4ff01, so a Firebase-only machine must still sync. Previously this
module returned early whenever the PAT was missing, reporting "sync is OFF"
on a machine whose sync was working perfectly -- a false negative that hid
a live backend behind a legacy credential check.
GitHub is used alone when only the PAT exists, Firebase alone when only
``~/.config/crdt-sync/`` exists, and the mirrored union when both do.
``None`` means neither is configured, which stays a benign, expected state.
``None`` is never silent: :func:`sync_client_or_reason` has already
logged a warning naming the cause and what will not sync because of it.
"""
token = read_sync_token()
github = (
GitHubSyncClient(
SYNC_REPO_OWNER,
SYNC_REPO_NAME,
token,
timeout_seconds=SYNC_TIMEOUT_SECONDS,
)
if token is not None
else None
)
if github is not None:
return remote_client(github)
if not CONFIG_FILE.is_file():
_logger.warning(
"Cannot pull synced workouts: no sync token at %s and no Firebase "
"config at %s — sync is OFF, so only ADB/HTTP can verify a phone "
"workout and phone-logged workouts will NOT count here",
SYNC_TOKEN_FILE,
CONFIG_FILE,
)
return None
try:
return firebase_client_for("screen_locker")
except (ConfigError, FirebaseAuthError, RemoteSyncError) as exc:
_logger.warning(
"Firebase is configured at %s but unusable, and there is no GitHub "
"token at %s to fall back to: %s — pulling NO synced workouts",
CONFIG_FILE,
SYNC_TOKEN_FILE,
exc,
)
return None
client, _reason = sync_client_or_reason()
return client

View File

@ -18,7 +18,7 @@ from crdt_sync import Hlc, Record
from screen_locker._manual_workout import MANUAL_WORKOUT_SYNC_KIND
if TYPE_CHECKING:
from collections.abc import Callable
from collections.abc import Callable, Iterable
_logger = logging.getLogger(__name__)
@ -123,3 +123,48 @@ def _manual_records(log_json: str) -> dict[str, tuple[dict, Hlc]]:
corrupt device log as "no manual records from that device".
"""
return _records_matching(log_json, _is_manual_payload)
def merge_device_texts(
texts: Iterable[tuple[str, str]],
extract: Callable[[str], dict[str, tuple[dict, Hlc]]],
what: str,
) -> dict[str, tuple[dict, Hlc]]:
"""Merge ``extract``-selected records across already-fetched device logs.
``texts`` is ``(path, log_json)`` per device. Keeps the highest-HLC copy of
each record id (records are id-stable, so one workout mirrored into two
device logs dedups to one), then drops every id ANY device tombstoned.
The pure half of ``_workout_sync._merge_device_records``, shared with the
Firebase stream (:mod:`screen_locker._session_stream`) so the two readers
cannot disagree on what counts. A corrupt log is skipped with a warning
naming it, never raised.
"""
merged: dict[str, tuple[dict, Hlc]] = {}
tombstoned: set[str] = set()
for path, text in texts:
try:
records = extract(text)
tombstoned |= _tombstoned_ids(text)
except (ValueError, KeyError, TypeError) as exc:
_logger.warning("Corrupt sync data at %s: %s", path, exc)
continue
for rid, (payload, hlc) in records.items():
existing = merged.get(rid)
if existing is None or existing[1] < hlc:
merged[rid] = (payload, hlc)
# Applied after the union, not per device: one device deleting a record
# while another still holds it live must delete it. crdt-sync's own merge
# makes deletion monotonic for exactly this reason, and this reader rolls
# its own merge, so it has to honour the same rule itself.
for rid in tombstoned & merged.keys():
_logger.info(
"Synced record %s is tombstoned on another device — dropping it, "
"so a deleted %s stops counting here too",
rid,
what,
)
del merged[rid]
return merged

View File

@ -21,7 +21,7 @@ from typing import TYPE_CHECKING
from crdt_sync import CONFIG_FILE as FIREBASE_CONFIG_FILE
from screen_locker._constants import SYNC_STATE_FILE, SYNC_TOKEN_FILE
from screen_locker._constants import SYNC_STATE_FILE
from screen_locker._device import device_identity
_logger = logging.getLogger(__name__)
@ -36,9 +36,9 @@ class SyncStatus:
Attributes:
device_id: The uuid this machine publishes under.
backend: ``"firebase"``, ``"github"``, or ``"none"`` -- the highest
backend this machine is configured for. Firebase is primary and
GitHub is the cutover mirror, so Firebase wins when both exist.
backend: ``"firebase"`` or ``"none"`` -- whether this machine is
configured for sync at all. Firebase is the only transport since
2026-10-09; the old GitHub mirror is a frozen archive.
pushed: Whether this machine has ever completed a push.
peer_count: How many other devices' logs it has merged.
last_push: ISO-ish local timestamp of the last push, or None.
@ -86,26 +86,22 @@ def _read_state(path: Path) -> dict[str, object]:
return parsed if isinstance(parsed, dict) else {}
def _backend(*, firebase_config: Path, token_file: Path) -> str:
"""Return the highest backend this machine is configured for."""
def _backend(*, firebase_config: Path) -> str:
"""Return the backend this machine is configured for, or ``"none"``."""
if firebase_config.is_file():
return "firebase"
if token_file.is_file():
return "github"
return "none"
def gather_sync_status(
*,
state_file: Path = SYNC_STATE_FILE,
token_file: Path = SYNC_TOKEN_FILE,
firebase_config: Path = FIREBASE_CONFIG_FILE,
) -> SyncStatus:
"""Read this machine's sync posture from local state only.
Args:
state_file: The revision cache written after each push.
token_file: The GitHub PAT, present only on the mirror path.
firebase_config: The shared Firebase credential.
Returns:
@ -138,7 +134,7 @@ def gather_sync_status(
return SyncStatus(
device_id=device_identity().device_id,
backend=_backend(firebase_config=firebase_config, token_file=token_file),
backend=_backend(firebase_config=firebase_config),
pushed=bool(state.get("pushed_rev")),
peer_count=peer_count,
last_push=last_push,

View File

@ -16,7 +16,9 @@ from typing import TYPE_CHECKING
import earned_time
from screen_locker import _sick_tracker
from screen_locker import _credit_notify, _sick_tracker
from screen_locker._constants import SHUTDOWN_BASE_FILE
from screen_locker._credit_slot import CreditSlot, credit_slot, locked_shutdown_state
from screen_locker._day import today_str
from screen_locker._earned import extra_minutes
from screen_locker._rest_day import is_rest_day
@ -123,10 +125,27 @@ class WorkoutCreditMixin:
verified ones; the manual-workout rate budget is the only limiter.
"""
weekly_count = count_weekly_workouts(self.log_file)
first_counted_today = not any(
entry.get("workout_data", {}).get("type") in COUNTED_WORKOUT_TYPES
for entry in prior_entries
)
# Slot-based, exactly like the daily reset (credit_key): the two
# StrongLifts ingestion paths of ONE session share a slot, so the
# second copy earns nothing. Deciding on "any counted type before
# it" instead paid one session +2h and then +1h (2026-10-09).
slot = credit_slot(prior_entries, self.workout_data)
if slot is CreditSlot.OCCUPIED:
_logger.warning(
"Workout %s (%s) shares its credit slot with an entry already "
"credited today — no shutdown time, no debt change; the daily "
"reset counts the two as one workout too",
self.workout_data.get("type", ""),
self.workout_data.get("source", ""),
)
return WorkoutCreditResult(
shutdown_adjusted=False,
new_debt=None,
extra_bonus_delta=0,
weekly_count=weekly_count,
already_counted_today=True,
)
first_counted_today = slot is CreditSlot.FIRST
shutdown_adjusted = False
extra_bonus_delta = 0
@ -138,20 +157,26 @@ class WorkoutCreditMixin:
if rest_paid:
_logger.info("Rest day: its first-unit bonus is already in tonight's time")
extra = extra_minutes(earned_time.WORKOUT, day)
if first_counted_today and not rest_paid:
shutdown_adjusted = self._try_adjust_shutdown_for_workout()
elif (
not first_counted_today
and extra
and self.workout_data.get("type") in COUNTED_WORKOUT_TYPES
):
old_cfg = self._read_shutdown_config()
if old_cfg and self._adjust_shutdown_time_by(extra):
# Same lock as the daily reset and the flat-bonus pass: all three
# read-add-write the shutdown config and the grace lift.
with locked_shutdown_state(SHUTDOWN_BASE_FILE):
before = self._read_shutdown_config()
if first_counted_today and not rest_paid:
shutdown_adjusted = self._try_adjust_shutdown_for_workout()
elif (
slot is CreditSlot.FURTHER
and extra
and before
and self._adjust_shutdown_time_by(extra)
):
new_cfg = self._read_shutdown_config()
if new_cfg:
extra_bonus_delta = new_cfg[1] - old_cfg[1]
extra_bonus_delta = new_cfg[1] - before[1]
after = self._read_shutdown_config()
new_debt = self._clear_debt_on_verified_workout()
if slot is not CreditSlot.NONE:
self._notify_credit(before, after)
return WorkoutCreditResult(
shutdown_adjusted=shutdown_adjusted,
@ -161,6 +186,26 @@ class WorkoutCreditMixin:
already_counted_today=False,
)
def _notify_credit(
self,
before: tuple[int, int, int] | None,
after: tuple[int, int, int] | None,
) -> None:
"""Pop the "Workout credited" notification; never fails the credit.
Runs after the credit is fully applied. Anything it raises -- a
malformed ledger inside the budget sum, a DBus oddity -- would
otherwise escape into the ingest loop and leave the rest of that
batch uncredited, so every exception is logged and dropped here.
"""
try:
_credit_notify.notify_workout_credit(before, after, self.log_file)
except Exception:
_logger.exception(
"Workout credit notification failed — the credit itself is "
"applied; only the desktop notification is missing"
)
def _apply_workout_credit(self) -> WorkoutCreditResult:
"""Append ``workout_data`` and apply its reward, scaled to the day.

View File

@ -1,11 +1,12 @@
"""Pulls phone/other-device workouts via crdt-sync's GitHub transport.
"""Pulls phone/other-device workouts via crdt-sync's Firebase transport.
GitHub is used purely as dumb file storage (see ``crdt_sync``'s own docs) --
the phone app pushes its completed-workout log to a private repo; this module
Firebase RTDB is the only backend since 2026-10-09 (the old GitHub repo is a
frozen archive nobody reads) -- the phone app pushes its completed-workout log
there; this module
reads the session log and every device's manual-workout records. (The PC does
push its OWN manual workouts, but via :mod:`screen_locker._manual_push`, not
here.) Sync is optional: an unconfigured token is a normal, expected state,
not an error -- unlike diet_guard, where sync is core to the app.
here.) Sync is optional: a machine without a Firebase config still locks
and verifies over ADB/HTTP -- but it says so at ``warning`` every time.
"""
from __future__ import annotations
@ -20,32 +21,20 @@ from crdt_sync import (
RemoteSyncError,
)
from screen_locker._constants import (
SYNC_REPO_NAME,
SYNC_REPO_OWNER,
SYNC_TOKEN_FILE,
)
from screen_locker._sync_client import (
read_sync_token,
remote_client,
sync_client,
)
from screen_locker._sync_client import sync_client, sync_client_or_reason
from screen_locker._sync_records import (
_is_manual_payload,
_is_session_payload,
_manual_records,
_records_matching,
_session_records,
_tombstoned_ids,
merge_device_texts,
)
from screen_locker._sync_retry import with_sync_retry
# Re-exported for callers (_manual_push) and for the autouse isolate_sync_token
# fixture, which redirects SYNC_TOKEN_FILE on this module as well as on
# _sync_client -- without both, a real token on the host leaks into the tests.
# Re-exported for callers (_manual_push, scripts/tombstone_sync_record.py).
__all__ = [
"CONFIG_FILE",
"SYNC_TOKEN_FILE",
"_is_manual_payload",
"_is_session_payload",
"_manual_records",
@ -54,9 +43,8 @@ __all__ = [
"pull_all_manual_records",
"pull_all_session_records",
"pull_synced_workout",
"read_sync_token",
"remote_client",
"sync_client",
"sync_client_or_reason",
]
if TYPE_CHECKING:
@ -104,11 +92,9 @@ def _merge_device_records(
)
except RemoteSyncError as exc:
_logger.warning(
"Could not list device logs under %s in %s/%s: %s — pulling NO "
"Could not list device logs under %s in Firebase: %s — pulling NO "
"synced %s, so phone-logged workouts will not count",
_DEVICES_PREFIX,
SYNC_REPO_OWNER,
SYNC_REPO_NAME,
exc,
what,
)
@ -116,8 +102,7 @@ def _merge_device_records(
raise
return {}
merged: dict[str, tuple[dict, Hlc]] = {}
tombstoned: set[str] = set()
texts: list[tuple[str, str]] = []
for device in devices:
path = f"{_DEVICES_PREFIX}/{device}/log.json"
try:
@ -131,33 +116,9 @@ def _merge_device_records(
what,
)
continue
if text is None:
continue
try:
records = extract(text)
tombstoned |= _tombstoned_ids(text)
except (ValueError, KeyError, TypeError) as exc:
_logger.warning("Corrupt sync data at %s: %s", path, exc)
continue
for rid, (payload, hlc) in records.items():
existing = merged.get(rid)
if existing is None or existing[1] < hlc:
merged[rid] = (payload, hlc)
# Applied after the union, not per device: one device deleting a record
# while another still holds it live must delete it. crdt-sync's own merge
# makes deletion monotonic for exactly this reason, and this reader rolls
# its own merge, so it has to honour the same rule itself.
for rid in tombstoned & merged.keys():
_logger.info(
"Synced record %s is tombstoned on another device — dropping it, "
"so a deleted %s stops counting here too",
rid,
what,
)
del merged[rid]
return merged
if text is not None:
texts.append((path, text))
return merge_device_texts(texts, extract, what)
def pull_synced_workout() -> tuple[dict | None, str | None]:
@ -171,7 +132,7 @@ def pull_synced_workout() -> tuple[dict | None, str | None]:
- Nothing configured anywhere: ``(None, None)`` -- benign, sync is optional.
- Nothing pushed yet: ``(None, None)``.
- A real sync error (network, bad token, backend unreachable):
- A real sync error (network, rejected credential, backend unreachable):
``(None, <message>)``.
- Success: ``(payload_dict, None)``.
"""
@ -207,13 +168,13 @@ def pull_all_session_records() -> list[tuple[str, dict]]:
being open: ``pull_synced_workout`` returns only the single newest session
for the live unlock check, which cannot backfill a week.
Best-effort in the same way -- an unconfigured token or a corrupt device
Best-effort in the same way -- no Firebase config or a corrupt device
log yields fewer records rather than raising.
"""
client = sync_client()
if client is None:
_logger.warning(
"No sync client (neither a GitHub token nor a Firebase config) — "
"No usable Firebase sync client (see the warning above) — "
"synced StrongLifts sessions cannot be pulled, so a workout done "
"on another device will NOT count toward the weekly minimum.",
)
@ -229,7 +190,7 @@ def pull_all_manual_records() -> list[tuple[str, dict]]:
Merges every ``devices/<device>/log.json`` under the sync prefix (phone,
pc, …), keeping the highest-HLC copy of each record id — records are
id-stable, so the same workout mirrored into two device logs dedups to one.
Best-effort: an unconfigured token, an unreachable repo, or a corrupt device
Best-effort: no Firebase config, an unreachable store, or a corrupt device
log yields fewer/no records rather than raising — manual sync, like session
sync, is optional.
"""

View File

@ -0,0 +1,118 @@
"""``python3 -m screen_locker.poke_server``: the phone -> PC workout poke daemon.
What ``workout-poke.service`` runs: load the shared key, warm the imports and
the budget sum, start the Firebase session stream (off-LAN credit,
:mod:`screen_locker._session_stream`) on a daemon thread, then serve ``POST
/v1/workout`` on port 8773 for good. The request handling lives in
:mod:`screen_locker._poke_server`; the contract is
``docs/DOCS-workout-poke-contract.md``.
A missing, malformed or group/world-readable key is a refusal to start,
logged at critical, so ``systemctl --user status workout-poke`` says why.
"""
from __future__ import annotations
import argparse
import logging
from pathlib import Path
import stat
import sys
from typing import Final
from screen_locker import _poke_credit
from screen_locker._poke_server import POKE_PATH, PokeServer
from screen_locker._poke_wire import parse_key
from screen_locker._session_stream import SessionStream
__all__ = ["DEFAULT_KEY_FILE", "DEFAULT_PORT", "load_key", "main"]
_logger: Final = logging.getLogger(__name__)
DEFAULT_PORT: Final = 8773
DEFAULT_KEY_FILE: Final = Path.home() / ".config" / "workout_poke" / "key"
_KEYGEN_HINT: Final = "run scripts/workout_poke_keygen.sh"
def load_key(path: Path) -> bytes:
"""Read the shared key; refuse a world/group-readable or malformed one.
Raises:
ValueError: With a sentence naming the problem and the fix.
OSError: The file cannot be read (usually: it does not exist).
"""
mode = stat.S_IMODE(path.stat().st_mode)
if mode & 0o077:
msg = f"{path} has mode {mode:o}; it must be 600 (chmod 600 {path})"
raise ValueError(msg)
return parse_key(path.read_text(encoding="ascii"))
def _parse_args(argv: list[str] | None) -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
# "" binds every interface; the firewall admits tcp/8773 from the LAN only.
parser.add_argument("--bind", default="", help="address (default: all)")
parser.add_argument("--port", type=int, default=DEFAULT_PORT)
parser.add_argument("--key-file", type=Path, default=DEFAULT_KEY_FILE)
parser.add_argument(
"--no-stream",
action="store_true",
help="skip the Firebase stream (off-LAN credit falls back to the sync)",
)
return parser.parse_args(argv)
def _start_stream(server: PokeServer) -> None:
"""Start the Firebase session stream; a failure here never stops the LAN poke."""
try:
# Same lock as the HTTP handler: a poke and a streamed copy of one
# session must never be credited concurrently.
SessionStream(server.gate).start()
except Exception:
_logger.exception(
"Could not start the Firebase session stream; off-LAN workouts will "
"only be credited by the 15-min workout-sync until the daemon restarts"
)
def main(argv: list[str] | None = None) -> int:
"""Load the key, warm up, serve forever; 1 (logged critical) if it cannot."""
logging.basicConfig(
level=logging.INFO, format="%(levelname)s %(name)s: %(message)s"
)
args = _parse_args(argv)
try:
key = load_key(args.key_file)
except (OSError, ValueError) as exc:
_logger.critical("Refusing to start: bad poke key (%s); %s", exc, _KEYGEN_HINT)
return 1
# Warm the budget sum (registry, ledgers) and the conf read once, so the
# first poke costs what every later one does.
_poke_credit.current_shutdown()
_poke_credit.current_gaming_minutes(_poke_credit.fresh_locker().log_file)
try:
server = PokeServer((args.bind, args.port), key)
except OSError as exc:
_logger.critical(
"Refusing to start: cannot bind %s:%d (%s)", args.bind, args.port, exc
)
return 1
_logger.info(
"Workout poke listening on %s:%d%s", args.bind or "*", args.port, POKE_PATH
)
if args.no_stream:
_logger.warning(
"Firebase session stream disabled by --no-stream; off-LAN workouts "
"will only be credited by the 15-min workout-sync"
)
else:
_start_stream(server)
try:
server.serve_forever()
finally:
server.server_close()
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@ -85,3 +85,26 @@ def _no_real_runnerup_webdav_dir(tmp_path: Path) -> Iterator[None]:
absent = (tmp_path / "no-runnerup-webdav",)
with patch("screen_locker._runnerup_verification.RUNNERUP_WEBDAV_DIRS", absent):
yield
@pytest.fixture(autouse=True)
def _no_desktop_notifications(tmp_path: Path) -> Iterator[None]:
"""Keep the credit path off the real desktop and the real lock file.
Every workout credit ends in ``_credit_notify.send_notification``, which
runs ``notify-send`` -- without this the suite would pop hundreds of
"Workout credited" bubbles on the developer's screen, and its budget
sum would read ledgers and log fail-closed warnings into caplog -- so
``notify_workout_credit`` itself is stubbed. The credit also takes
``bonus_lock`` on ``_workout_credit.SHUTDOWN_BASE_FILE``, bound at import
time, so that is redirected too. Tests of the notifier itself capture the
real function at import time.
"""
with (
patch("screen_locker._credit_notify.notify_workout_credit", return_value=True),
patch(
"screen_locker._workout_credit.SHUTDOWN_BASE_FILE",
tmp_path / "credit_shutdown_base.json",
),
):
yield

View File

@ -100,7 +100,7 @@ def _firebase_config(
class ReachableClient:
"""A built client whose authenticated probe succeeds.
``remote_client`` no longer trusts a client just because it constructed:
``sync_client`` no longer trusts a client just because it constructed:
it probes with ``can_access_remote`` first, because a credential that is
present but server-rejected builds fine and then 401s on every operation.
Fakes therefore have to answer that probe. ``identity`` carries whatever

View File

@ -69,9 +69,9 @@ if TYPE_CHECKING:
from collections.abc import Generator, Iterator
# Autouse fixtures that keep this suite off real user state live here; see
# that module for why the two seams are different.
pytest_plugins = ("screen_locker.tests._real_state_fixtures",)
# Real-state isolation; sync fixtures listed too: `-o addopts=""` drops `-p`.
_SYNC = "screen_locker.tests.test_sync_fixtures"
pytest_plugins = ("screen_locker.tests._real_state_fixtures", _SYNC)
@pytest.fixture(autouse=True)
@ -236,15 +236,14 @@ def _mock_weekly_logic() -> Iterator[None]:
def _no_real_firebase_config(monkeypatch: pytest.MonkeyPatch) -> None:
"""Point the Firebase config at a path that does not exist.
``remote_client`` reads ``crdt_sync.CONFIG_FILE`` to decide whether to
build a Firebase-primary mirror. On a developer machine that file *does*
exist, so without this the sync tests would reach the real database and
assert against live data instead of their own fakes. Tests that want the
Firebase path point it back at a file they control.
``sync_client`` (the ONLY way push, pull and the tombstone script get a
client) reads ``_sync_client.CONFIG_FILE`` to decide whether to build the
Firebase client. On a developer machine that file *does* exist, so
without this the sync tests would reach the real database and assert
against live data. Tests wanting Firebase point it at a file they own.
"""
# CONFIG_FILE is read by remote_client, which lives in _sync_client since
# _workout_sync was split. Patching the old module would leave the real
# config in play and the sync tests would assert against live data.
# Patch _sync_client's binding: crdt_sync's own CONFIG_FILE is bound to
# the real home at import, which _isolate_home cannot redirect.
from screen_locker import _sync_client
monkeypatch.setattr(_sync_client, "CONFIG_FILE", Path("/nonexistent/firebase.json"))

View File

@ -0,0 +1,73 @@
"""``--help`` answers and exits; an unknown flag is a usage error.
Before this, both fell through to building the demo lock screen. Split from
``test_cli.py`` for the 250-line cap. ``sys.exit`` is a no-op suite-wide (see
conftest), so each test installs one that really raises ``SystemExit``.
"""
# pylint: disable=protected-access
from __future__ import annotations
from typing import TYPE_CHECKING, NoReturn, cast
import pytest
from screen_locker import _cli
if TYPE_CHECKING:
from screen_locker.screen_lock import ScreenLocker
def _really_exit(code: int = 0) -> NoReturn:
raise SystemExit(code)
@pytest.fixture(autouse=True)
def _exiting_sys_exit(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(_cli.sys, "exit", _really_exit)
class _NeverBuilt:
"""A locker class whose construction would mean the guard failed."""
def __init__(self, *_: object, **__: object) -> None:
msg = "the lock screen must not be built"
raise AssertionError(msg)
def _main(argv: list[str]) -> None:
locker_cls = cast("type[ScreenLocker]", _NeverBuilt)
_cli.main(locker_cls, ["screen_lock.py", *argv])
@pytest.mark.parametrize("flag", ["--help", "-h"])
def test_help_prints_usage_and_exits_zero(
flag: str, capsys: pytest.CaptureFixture[str]
) -> None:
"""Help goes to stdout and the process exits 0 before any UI."""
with pytest.raises(SystemExit) as exited:
_main(["--production", flag])
assert exited.value.code == 0
out = capsys.readouterr().out
assert out.startswith("usage: python3 -m screen_locker.screen_lock")
def test_unknown_flag_is_exit_two_with_usage(
capsys: pytest.CaptureFixture[str],
) -> None:
"""A typo is named on stderr with the usage, and exits 2."""
with pytest.raises(SystemExit) as exited:
_main(["--prodution"])
assert exited.value.code == 2
err = capsys.readouterr().err
assert "unknown argument(s): --prodution" in err
assert "usage:" in err
def test_subcommand_args_are_not_judged_here() -> None:
"""Everything after a trailing-arg subcommand belongs to its own parser."""
assert (
_cli._own_args(["screen_lock.py", "--log-manual-workout", "--help", "--weird"])
== []
)
assert _cli._own_args(["screen_lock.py", "--status"]) == ["--status"]

View File

@ -0,0 +1,187 @@
"""The "Workout credited" desktop notification and every way it can fail.
The autouse ``_no_desktop_notifications`` fixture stubs
``notify_workout_credit`` for the whole suite; the real one is captured here
at import time, before any fixture runs.
"""
# pylint: disable=protected-access
from __future__ import annotations
import logging
import subprocess
from types import SimpleNamespace
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import pytest
from screen_locker import _credit_notify
from screen_locker.tests.conftest import create_locker
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
_REAL_NOTIFY = _credit_notify.notify_workout_credit
_FRIDAY = "2026-10-09" # Thu-Sun: tonight is the second config field
_MOD = "screen_locker._credit_notify"
@pytest.fixture(autouse=True)
def _fixed_day() -> Iterator[None]:
with patch(f"{_MOD}.today_str", return_value=_FRIDAY):
yield
def _warned(caplog: pytest.LogCaptureFixture, needle: str) -> bool:
return any(
r.levelno >= logging.WARNING and needle in r.getMessage()
for r in caplog.records
)
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:
"""Whichever parts are known end up in the body."""
def test_full_body(self) -> None:
"""Shutdown time, tonight's move and the gaming budget."""
body = _credit_notify.credit_body((0, 1200, 0), (0, 1320, 0), 420)
assert body == "Shutdown 22:00 (+2h) \N{MIDDLE DOT} gaming 7.0h"
def test_a_capped_credit_shows_plus_zero(self) -> None:
"""No backwards move is ever shown: the delta floors at zero."""
body = _credit_notify.credit_body((0, 1380, 0), (0, 1320, 0), None)
assert body == "Shutdown 22:00 (+0h)"
def test_unknown_before_drops_the_delta(self) -> None:
"""Without the old config there is no move to show."""
assert _credit_notify.credit_body(None, (0, 1320, 0), None) == "Shutdown 22:00"
def test_unreadable_after_warns_and_shows_gaming_only(
self, caplog: pytest.LogCaptureFixture
) -> None:
"""An unreadable config is said out loud, not silently omitted."""
assert _credit_notify.credit_body(None, None, 90) == "gaming 1.5h"
assert _warned(caplog, "unreadable")
def test_nothing_known_still_says_something(self) -> None:
"""An empty body would read as a glitch; say the credit happened."""
body = _credit_notify.credit_body(None, None, None)
assert body == "Credit applied (details unavailable)"
class TestSendNotification:
"""notify-send's every failure is a warning and a False."""
def test_missing_binary(self, caplog: pytest.LogCaptureFixture) -> None:
"""No notify-send on PATH."""
with patch(f"{_MOD}.shutil.which", return_value=None):
assert not _credit_notify.send_notification("t", "b")
assert _warned(caplog, "notify-send not found")
@pytest.mark.parametrize(
"error", [OSError("exec"), subprocess.TimeoutExpired("notify-send", 5)]
)
def test_spawn_failure_or_hang(
self, error: Exception, caplog: pytest.LogCaptureFixture
) -> None:
"""An exec error or a DBus hang past the timeout."""
with (
patch(f"{_MOD}.shutil.which", return_value="/usr/bin/notify-send"),
patch(f"{_MOD}.subprocess.run", side_effect=error),
):
assert not _credit_notify.send_notification("t", "b")
assert _warned(caplog, "Desktop notification failed")
@pytest.mark.parametrize(
("stderr", "shown"),
[("no bus", "no bus"), (" ", "is a DBus session reachable")],
)
def test_nonzero_exit(
self, stderr: str, shown: str, caplog: pytest.LogCaptureFixture
) -> None:
"""A failing notify-send names its stderr, or the likely cause."""
done = subprocess.CompletedProcess([], 1, stdout="", stderr=stderr)
with (
patch(f"{_MOD}.shutil.which", return_value="/usr/bin/notify-send"),
patch(f"{_MOD}.subprocess.run", return_value=done),
):
assert not _credit_notify.send_notification("t", "b")
assert _warned(caplog, shown)
def test_success(self) -> None:
"""Exit 0 is the only True."""
done = subprocess.CompletedProcess([], 0, stdout="", stderr="")
with (
patch(f"{_MOD}.shutil.which", return_value="/usr/bin/notify-send"),
patch(f"{_MOD}.subprocess.run", return_value=done) as run,
):
assert _credit_notify.send_notification("Title", "Body")
assert run.call_args.args[0] == [
"/usr/bin/notify-send",
"--app-name=screen-locker",
"Title",
"Body",
]
def test_notify_workout_credit_sends_the_composed_body() -> None:
"""The real entry point composes the body and sends it once."""
with (
patch(f"{_MOD}.gaming_minutes_today", return_value=60),
patch(f"{_MOD}.send_notification", return_value=True) as send,
):
assert _REAL_NOTIFY((0, 1200, 0), (0, 1260, 0), None)
send.assert_called_once_with(
_credit_notify.TITLE, "Shutdown 21:00 (+1h) \N{MIDDLE DOT} gaming 1.0h"
)
class TestCreditSideOfTheNotifier:
"""The credit mixin's guards around the notifier."""
def test_a_raising_notifier_never_fails_the_credit(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Anything the notifier raises is logged at ERROR and dropped."""
locker = create_locker(mock_tk, tmp_path)
with patch(f"{_MOD}.notify_workout_credit", side_effect=KeyError("x")):
locker._notify_credit(None, None)
assert any(
r.levelno == logging.ERROR and "notification failed" in r.getMessage()
for r in caplog.records
)
def test_uncounted_type_never_moves_the_shutdown(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
) -> None:
"""The first-unit push refuses a type that earns no credit."""
locker = create_locker(mock_tk, tmp_path)
locker.workout_data = {"type": "early_bird"}
adjust = MagicMock(return_value=True)
object.__setattr__(locker, "_adjust_shutdown_time_later", adjust)
assert locker._try_adjust_shutdown_for_workout() is False
adjust.assert_not_called()

View File

@ -0,0 +1,165 @@
"""Slot-based live workout credit: one slot pays once, a new slot pays again.
The two StrongLifts ingestion paths of ONE session used to earn +2h and then
+1h (2026-10-09). These tests drive the real shutdown arithmetic over a fake
config so the minute figures, not just the branch taken, are pinned.
"""
# pylint: disable=protected-access
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from screen_locker import _credit_slot
from screen_locker._credit_slot import CreditSlot, credit_slot, locked_shutdown_state
from screen_locker.tests.conftest import create_locker
if TYPE_CHECKING:
from pathlib import Path
import pytest
from screen_locker._workout_credit import WorkoutCreditResult
from screen_locker.screen_lock import ScreenLocker
_START = (1200, 1200, 300) # 20:00 / 20:00 / 05:00 -- well under the ceiling
def _entry(wtype: str) -> dict[str, dict[str, str]]:
return {"workout_data": {"type": wtype}}
class TestCreditSlot:
"""credit_slot classifies the new entry against the day before it."""
def test_first_counted_entry_of_the_day(self) -> None:
"""An empty day: the first counted workout opens the first slot."""
assert credit_slot([], {"type": "phone_verified"}) is CreditSlot.FIRST
def test_second_stronglifts_path_shares_the_slot(self) -> None:
"""pc_workout_verified then phone_verified: one session, one slot."""
prior = [_entry("pc_workout_verified")]
assert credit_slot(prior, {"type": "phone_verified"}) is CreditSlot.OCCUPIED
def test_a_run_after_stronglifts_is_a_further_slot(self) -> None:
"""A RunnerUp run is a separate session from the StrongLifts one."""
prior = [_entry("phone_verified")]
assert credit_slot(prior, {"type": "runnerup_verified"}) is CreditSlot.FURTHER
def test_uncounted_type_earns_nothing(self) -> None:
"""early_bird is not a counted workout type at all."""
assert credit_slot([], {"type": "early_bird"}) is CreditSlot.NONE
def test_non_dict_prior_entries_are_ignored(self) -> None:
"""A corrupt prior entry neither crashes nor occupies a slot."""
prior: list = ["garbage", None]
assert credit_slot(prior, {"type": "phone_verified"}) is CreditSlot.FIRST
class TestLockedShutdownState:
"""The credit takes bonus_lock, and degrades loudly when it cannot."""
def test_lock_failure_warns_and_still_runs_the_body(
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""An unlockable state file must not drop the credit -- only warn."""
ran: list[bool] = []
with (
patch.object(_credit_slot, "bonus_lock", side_effect=OSError("ro fs")),
caplog.at_level(logging.WARNING, logger=_credit_slot.__name__),
locked_shutdown_state(tmp_path / "base.json"),
):
ran.append(True)
assert ran == [True]
assert any(
r.levelno == logging.WARNING and "ro fs" in r.getMessage()
for r in caplog.records
)
def test_lock_success_runs_the_body(self, tmp_path: Path) -> None:
"""The happy path holds the real lock around the body."""
ran: list[bool] = []
with locked_shutdown_state(tmp_path / "base.json"):
ran.append(True)
assert ran == [True]
def _wired_locker(mock_tk: MagicMock, tmp_path: Path, wtype: str) -> ScreenLocker:
"""A locker over an in-memory shutdown config, real adjust arithmetic."""
locker = create_locker(mock_tk, tmp_path)
locker.workout_data = {"type": wtype}
config = {"value": _START}
def write(mw: int, ts: int, morning: int, *, restore: bool) -> bool:
assert restore
config["value"] = (mw, ts, morning)
return True
object.__setattr__(
locker, "_read_shutdown_config", MagicMock(side_effect=lambda: config["value"])
)
object.__setattr__(locker, "_write_shutdown_config", MagicMock(side_effect=write))
object.__setattr__(
locker, "_clear_debt_on_verified_workout", MagicMock(return_value=None)
)
return locker
def _credit(locker: ScreenLocker, prior: list) -> tuple[WorkoutCreditResult, MagicMock]:
with (
patch("screen_locker._shutdown.plan_absorb", side_effect=lambda m: (m, 0)),
patch("screen_locker._shutdown.save_lift"),
patch("screen_locker._workout_credit.is_rest_day", return_value=False),
patch("screen_locker._workout_credit.count_weekly_workouts", return_value=3),
patch(
"screen_locker._workout_credit._credit_notify.notify_workout_credit"
) as notify,
):
result = locker._apply_credit_for_written_entry(prior)
return result, notify
class TestSlotCreditMinutes:
"""The minutes each slot class actually moves the shutdown."""
def test_first_slot_earns_two_hours(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
) -> None:
"""First counted workout of the day: shutdown +120 min, notified."""
locker = _wired_locker(mock_tk, tmp_path, "phone_verified")
result, notify = _credit(locker, [])
assert result.shutdown_adjusted is True
assert locker._read_shutdown_config() == (1320, 1320, 300)
notify.assert_called_once_with(_START, (1320, 1320, 300), locker.log_file)
def test_distinct_slot_earns_one_hour(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
) -> None:
"""A run after StrongLifts: +60 min, reported as the extra delta."""
locker = _wired_locker(mock_tk, tmp_path, "runnerup_verified")
result, notify = _credit(locker, [_entry("phone_verified")])
assert result.extra_bonus_delta == 60
assert locker._read_shutdown_config() == (1260, 1260, 300)
notify.assert_called_once()
def test_same_slot_earns_nothing_and_warns(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
caplog: pytest.LogCaptureFixture,
) -> None:
"""The second StrongLifts path: 0 min, a WARNING, no notification."""
locker = _wired_locker(mock_tk, tmp_path, "phone_verified")
with caplog.at_level(logging.WARNING, logger="screen_locker._workout_credit"):
result, notify = _credit(locker, [_entry("pc_workout_verified")])
assert result.already_counted_today is True
assert result.extra_bonus_delta == 0
assert locker._read_shutdown_config() == _START # untouched
notify.assert_not_called()
assert any(
r.levelno == logging.WARNING and "shares its credit slot" in r.getMessage()
for r in caplog.records
)

View File

@ -85,7 +85,7 @@ def test_no_module_binds_a_path_inside_the_real_app_config() -> None:
"""Import-time bindings of ``~/.config/screen_locker`` must all be redirected.
``_isolate_home`` only reaches paths built from ``Path.home()`` at *call*
time. A module constant such as ``SYNC_TOKEN_FILE`` was bound at import,
time. A module constant such as the old ``SYNC_TOKEN_FILE`` was bound at import,
before any fixture ran, and keeps the real path unless every module that
holds it is patched. This scans every runtime module for such a binding,
so a new one fails here instead of silently writing to the live dir.

View File

@ -10,9 +10,9 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from crdt_sync import GitHubSyncError, RepoNotFoundError
from crdt_sync import FirebaseSyncError
from screen_locker import _manual_push, _sync_client
from screen_locker import _manual_push
from screen_locker._manual_push import (
PushResult,
push_pc_workouts,
@ -40,23 +40,32 @@ _RUN = {
class TestPushPcWorkouts:
"""Every outcome is reported — never a silent no-op."""
def test_no_token_reports_why(self, tmp_path: Path) -> None:
"""No token reports why."""
def test_no_firebase_config_reports_why(
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""No Firebase config: nothing pushed, the reason and count say so.
The autouse ``_no_real_firebase_config`` fixture is exactly this
machine state, so the real ``sync_client_or_reason`` runs here.
"""
log_file = tmp_path / "log.json"
_write_log(
log_file, {"2026-07-13": [_entry(_RUN, "2026-07-13T10:00:00+00:00")]}
)
with patch.object(_manual_push, "read_sync_token", return_value=None):
with caplog.at_level("WARNING"):
result = push_pc_workouts(log_file)
assert result == PushResult(pushed=False, record_count=0, reason=result.reason)
assert "no sync token" in result.reason
assert result.pushed is False
assert result.record_count == 1
assert result.reason.startswith("no Firebase config at ")
assert "1 workout(s) stay local" in caplog.text
def test_empty_log_reports_why(self, tmp_path: Path) -> None:
"""Empty log reports why."""
log_file = tmp_path / "log.json"
_write_log(log_file, {})
with patch.object(_manual_push, "read_sync_token", return_value="t"):
with patch.object(_manual_push, "sync_client_or_reason") as build:
result = push_pc_workouts(log_file)
build.assert_not_called()
assert result.pushed is False
assert result.record_count == 0
assert "no counted workouts" in result.reason
@ -68,10 +77,11 @@ class TestPushPcWorkouts:
log_file, {"2026-07-13": [_entry(_RUN, "2026-07-13T10:00:00+00:00")]}
)
with (
patch.object(_manual_push, "read_sync_token", return_value="t"),
patch.object(_manual_push, "GitHubSyncClient", MagicMock()),
patch.object(
_manual_push, "sync_log", side_effect=GitHubSyncError("403 forbidden")
_manual_push, "sync_client_or_reason", return_value=(MagicMock(), "")
),
patch.object(
_manual_push, "sync_log", side_effect=FirebaseSyncError("403 forbidden")
),
):
result = push_pc_workouts(log_file)
@ -94,12 +104,13 @@ class TestPushPcWorkouts:
log_file, {"2026-07-13": [_entry(_RUN, "2026-07-13T10:00:00+00:00")]}
)
with (
patch.object(_manual_push, "read_sync_token", return_value="t"),
patch.object(_manual_push, "GitHubSyncClient", MagicMock()),
patch.object(
_manual_push, "sync_client_or_reason", return_value=(MagicMock(), "")
),
patch.object(
_manual_push,
"sync_log",
side_effect=GitHubSyncError("network error reading x"),
side_effect=FirebaseSyncError("network error reading x"),
),
caplog.at_level("WARNING"),
):
@ -108,28 +119,6 @@ class TestPushPcWorkouts:
assert "network error reading x" in caplog.text
assert "contents:write" not in caplog.text
def test_repo_not_found_still_points_at_the_token(
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""The permission hint survives for the error that actually implies it."""
log_file = tmp_path / "log.json"
_write_log(
log_file, {"2026-07-13": [_entry(_RUN, "2026-07-13T10:00:00+00:00")]}
)
with (
patch.object(_manual_push, "read_sync_token", return_value="t"),
patch.object(_manual_push, "GitHubSyncClient", MagicMock()),
patch.object(
_manual_push,
"sync_log",
side_effect=RepoNotFoundError("no access"),
),
caplog.at_level("WARNING"),
):
result = push_pc_workouts(log_file)
assert result.pushed is False
assert "contents:write" in caplog.text
def test_successful_push_reports_count(self, tmp_path: Path) -> None:
"""Successful push reports count."""
log_file = tmp_path / "log.json"
@ -144,8 +133,9 @@ class TestPushPcWorkouts:
)
fake_sync = MagicMock()
with (
patch.object(_manual_push, "read_sync_token", return_value="t"),
patch.object(_manual_push, "GitHubSyncClient", MagicMock()),
patch.object(
_manual_push, "sync_client_or_reason", return_value=(MagicMock(), "")
),
patch.object(_manual_push, "sync_log", fake_sync),
):
result = push_pc_workouts(log_file)
@ -159,8 +149,9 @@ class TestPushPcWorkouts:
log_file, {"2026-07-12": [_entry(_RUN, "2026-07-12T10:00:00+00:00")]}
)
with (
patch.object(_manual_push, "read_sync_token", return_value="t"),
patch.object(_manual_push, "GitHubSyncClient", MagicMock()),
patch.object(
_manual_push, "sync_client_or_reason", return_value=(MagicMock(), "")
),
patch.object(_manual_push, "sync_log", MagicMock()) as fake_sync,
):
push_pc_workouts(log_file)
@ -169,57 +160,26 @@ class TestPushPcWorkouts:
assert "runnerup_verified:2026-07-12" in pushed
class TestIncompletePushIsNotReportedAsClean:
"""A push that reached only some backends must not look like a full one."""
class TestPushLogsItsOutcome:
"""The journal line is what says a push landed; it must name Firebase."""
def test_a_degraded_backend_makes_the_push_incomplete(
def test_a_healthy_push_logs_the_count_and_no_warning(
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Firebase missing the records must be said out loud, at warning.
Before this, a dead Firebase produced the identical
``INFO Synced N workout(s)`` line as a fully mirrored push, so a
half-landed push was indistinguishable from a healthy one for weeks.
"""
"""A clean push says how many records went to Firebase, at INFO."""
log_file = tmp_path / "log.json"
_write_log(
log_file, {"2026-07-13": [_entry(_RUN, "2026-07-13T10:00:00+00:00")]}
)
_sync_client.clear_degraded_sources()
_sync_client._record_degraded("firebase", "HTTP 401")
with (
patch.object(_manual_push, "read_sync_token", return_value="t"),
patch.object(_manual_push, "remote_client", MagicMock()),
patch.object(
_manual_push, "sync_client_or_reason", return_value=(MagicMock(), "")
),
patch.object(_manual_push, "with_sync_retry", MagicMock()),
caplog.at_level("WARNING"),
caplog.at_level("INFO"),
):
result = push_pc_workouts(log_file)
_sync_client.clear_degraded_sources()
assert result.pushed is True, "the records DID land on GitHub"
assert "firebase" in result.reason
assert "did NOT receive" in result.reason
assert "INCOMPLETE" in caplog.text
def test_a_healthy_push_stays_quiet(
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""The happy path must stay clean, or the warning means nothing."""
log_file = tmp_path / "log.json"
_write_log(
log_file, {"2026-07-13": [_entry(_RUN, "2026-07-13T10:00:00+00:00")]}
)
_sync_client.clear_degraded_sources()
with (
patch.object(_manual_push, "read_sync_token", return_value="t"),
patch.object(_manual_push, "remote_client", MagicMock()),
patch.object(_manual_push, "with_sync_retry", MagicMock()),
caplog.at_level("WARNING"),
):
result = push_pc_workouts(log_file)
assert result.pushed is True
assert result.reason == "pushed"
assert "INCOMPLETE" not in caplog.text
assert result == PushResult(pushed=True, record_count=1, reason="pushed")
assert "Synced 1 workout(s) to Firebase" in caplog.text
assert not [r for r in caplog.records if r.levelname == "WARNING"]

View File

@ -111,7 +111,9 @@ class TestApplyWorkoutCredit:
object.__setattr__(
locker,
"_read_shutdown_config",
MagicMock(side_effect=[(1260, 1260, 300), (1320, 1320, 300)]),
MagicMock(
side_effect=[(1260, 1260, 300), (1320, 1320, 300), (1320, 1320, 300)]
),
)
object.__setattr__(
locker, "_adjust_shutdown_time_by", MagicMock(return_value=True)
@ -135,12 +137,12 @@ class TestApplyWorkoutCredit:
) -> None:
"""An additional same-day VERIFIED workout earns the +1h extra bonus.
prior_entries already holds a counted workout, so this isn't the first
of the day; because the new type is verified it takes the +1h branch,
and extra_bonus_delta reflects the shutdown-config minute delta.
prior_entries already holds a StrongLifts session; a RunnerUp run is a
distinct credit slot, so it takes the +1h branch, and
extra_bonus_delta reflects the shutdown-config minute delta.
"""
locker = create_locker(mock_tk, tmp_path)
locker.workout_data = {"type": "phone_verified"}
locker.workout_data = {"type": "runnerup_verified"}
prior = [{"workout_data": {"type": "phone_verified"}}]
object.__setattr__(
locker,
@ -153,7 +155,9 @@ class TestApplyWorkoutCredit:
object.__setattr__(
locker,
"_read_shutdown_config",
MagicMock(side_effect=[(1260, 1260, 300), (1320, 1320, 300)]),
MagicMock(
side_effect=[(1260, 1260, 300), (1320, 1320, 300), (1320, 1320, 300)]
),
)
object.__setattr__(
locker, "_adjust_shutdown_time_by", MagicMock(return_value=True)

View File

@ -8,7 +8,7 @@ from __future__ import annotations
import pathlib
from typing import TYPE_CHECKING
from unittest.mock import MagicMock
from unittest.mock import MagicMock, patch
from screen_locker._log_mixin import RecordResult
from screen_locker.tests.conftest import create_locker
@ -71,7 +71,7 @@ class TestApplyWorkoutCredit:
"""A workout whose type isn't in COUNTED_WORKOUT_TYPES (e.g.
``early_bird``) and isn't the first counted entry of the day →
neither the base push nor the +1h branch fires; the shutdown config
is never even consulted."""
is never adjusted and no credit notification goes out."""
locker = create_locker(mock_tk, tmp_path)
locker.workout_data = {"type": "early_bird"}
prior = [{"workout_data": {"type": "phone_verified"}}]
@ -88,13 +88,16 @@ class TestApplyWorkoutCredit:
locker, "_clear_debt_on_verified_workout", MagicMock(return_value=None)
)
result = locker._apply_credit_for_written_entry(prior)
with patch(
"screen_locker._workout_credit._credit_notify.notify_workout_credit"
) as notify:
result = locker._apply_credit_for_written_entry(prior)
assert result.shutdown_adjusted is False
assert result.extra_bonus_delta == 0
locker._try_adjust_shutdown_for_workout.assert_not_called()
locker._read_shutdown_config.assert_not_called()
locker._adjust_shutdown_time_by.assert_not_called()
notify.assert_not_called()
def test_skips_save_for_sick_day_type(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path

View File

@ -0,0 +1,61 @@
"""The PC receiver against the shared phone<->PC poke fixture.
``contracts/workout_poke_v1.json`` is the literal both sides test against
(the Dart sender has the twin of this test). A drift in key decoding, body
encoding or MAC computation on this side fails here.
"""
from __future__ import annotations
from http import HTTPStatus
import json
from pathlib import Path
from screen_locker._poke_wire import (
NonceCache,
PokeRequest,
Rejection,
check_request,
parse_key,
verify_signature,
)
_FIXTURE = Path(__file__).resolve().parents[2] / "contracts" / "workout_poke_v1.json"
def _fixture() -> tuple[bytes, bytes, str]:
data = json.loads(_FIXTURE.read_text(encoding="utf-8"))
key = parse_key(data["key_hex"])
body = data["body_utf8"].encode("utf-8")
return key, body, data["signature_hex"]
def test_fixture_signature_verifies_over_raw_bytes() -> None:
key, body, signature = _fixture()
assert verify_signature(key, body, signature)
def test_one_altered_byte_is_rejected() -> None:
key, body, signature = _fixture()
altered = bytearray(body)
# The '1' in "v":1 -> '2': still valid JSON, so only the MAC can catch it.
altered[body.index(b'"v":1') + 4] = ord("2")
assert not verify_signature(key, bytes(altered), signature)
def test_fixture_passes_every_contract_check() -> None:
key, body, signature = _fixture()
sent_at = json.loads(body)["sent_at_ms"]
result = check_request(key, body, signature, NonceCache(), now_ms=sent_at)
assert isinstance(result, PokeRequest)
assert result.record_id == "2026-10-09T15:10:40.953"
assert result.payload["duration_seconds"] == 7020.5
assert result.payload["note"] == "zażółć gęślą jaźń"
def test_altered_body_is_a_401_through_check_request() -> None:
key, body, signature = _fixture()
altered = body.replace(b'"sandbox":false', b'"sandbox":true ')
result = check_request(key, altered, signature, NonceCache(), now_ms=0)
assert isinstance(result, Rejection)
assert result.status is HTTPStatus.UNAUTHORIZED

View File

@ -0,0 +1,204 @@
"""Crediting poked sessions: precheck, ingest, slot outcomes and the day reset."""
from __future__ import annotations
import json
import logging
from typing import TYPE_CHECKING, Any
from unittest.mock import MagicMock
import pytest
from screen_locker import _poke_credit
from screen_locker._poke_credit import (
BatchOutcome,
PokeLocker,
PokeOutcome,
credit_session,
credit_sessions,
)
from screen_locker._workout_credit import WorkoutCreditResult
if TYPE_CHECKING:
from pathlib import Path
_DAY = "2026-10-09"
def _session(**overrides: object) -> dict[str, Any]:
payload: dict[str, Any] = {
"workout_type": "B",
"date": _DAY,
"start_time": f"{_DAY}T15:10:40.953",
"duration_seconds": 7020,
"succeeded": True,
"exercises": [{"name": "Row", "succeeded": True}],
}
payload.update(overrides)
return payload
def _result(*, counted: bool = False) -> WorkoutCreditResult:
return WorkoutCreditResult(
shutdown_adjusted=not counted,
new_debt=None,
extra_bonus_delta=0,
weekly_count=1,
already_counted_today=counted,
)
@pytest.fixture
def log_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""A fresh PokeLocker on a tmp log; the day reset and the credit stubbed."""
log = tmp_path / "poke_log.json"
def headless(locker_cls: type[PokeLocker]) -> PokeLocker:
locker = object.__new__(locker_cls)
locker.log_file = log
locker.workout_data = {}
return locker
monkeypatch.setattr(_poke_credit, "_headless_locker", headless)
monkeypatch.setattr(_poke_credit, "process_week_transition", lambda *_: [])
monkeypatch.setattr(_poke_credit, "reset_to_base_if_new_day", lambda *_a, **_k: 0)
return log
@pytest.fixture
def credit(monkeypatch: pytest.MonkeyPatch) -> MagicMock:
"""Replace the shared credit step; the ingest itself stays real."""
stub = MagicMock(return_value=_result())
monkeypatch.setattr(PokeLocker, "_apply_credit_for_written_entry", stub)
return stub
def _logged_ids(log: Path) -> list[str]:
data = json.loads(log.read_text())
return [e["workout_data"]["sync_record_id"] for es in data.values() for e in es]
class TestCreditSession:
def test_happy_path_logs_and_credits_once(
self, log_file: Path, credit: MagicMock
) -> None:
outcome = credit_session("r1", _session())
assert outcome == PokeOutcome(
ok=True, credited=True, duplicate=False, reason="workout credited"
)
assert _logged_ids(log_file) == [f"{_DAY}T15:10:40.953"]
credit.assert_called_once()
def test_second_poke_of_the_same_session_is_a_duplicate(
self, log_file: Path, credit: MagicMock
) -> None:
credit_session("r1", _session())
outcome = credit_session("r1", _session())
assert (outcome.ok, outcome.credited, outcome.duplicate) == (True, False, True)
assert "already in the PC's log" in outcome.reason
assert credit.call_count == 1
assert len(_logged_ids(log_file)) == 1
def test_slot_already_paid_logs_but_credits_nothing(
self,
log_file: Path,
credit: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
credit.return_value = _result(counted=True)
with caplog.at_level(logging.WARNING):
outcome = credit_session("r1", _session())
assert (outcome.ok, outcome.credited, outcome.duplicate) == (True, False, False)
assert "slot" in outcome.reason
assert "not credited" in caplog.text
assert len(_logged_ids(log_file)) == 1
@pytest.mark.parametrize("day", [None, "", 20261009])
def test_session_without_a_usable_date_is_refused(
self, log_file: Path, credit: MagicMock, day: object
) -> None:
outcome = credit_session("r1", _session(date=day))
assert (outcome.ok, outcome.credited, outcome.duplicate) == (
False,
False,
False,
)
assert "no usable date" in outcome.reason
assert not log_file.exists()
credit.assert_not_called()
@pytest.mark.parametrize(
("overrides", "fragment"),
[
({"exercises": []}, "no exercises"),
({"duration_seconds": 600}, "10 min"),
({"duration_seconds": "long"}, "not a number"),
],
)
def test_invalid_session_is_refused_with_the_reason(
self,
log_file: Path,
credit: MagicMock,
overrides: dict[str, object],
fragment: str,
) -> None:
outcome = credit_session("r1", _session(**overrides))
assert outcome.ok is False
assert "does not count" in outcome.reason
assert fragment in outcome.reason
assert not log_file.exists()
credit.assert_not_called()
def test_the_day_is_reset_before_the_credit(
self, log_file: Path, credit: MagicMock, monkeypatch: pytest.MonkeyPatch
) -> None:
order: list[str] = []
def reset(_self: PokeLocker) -> None:
order.append("reset")
def paid(*_args: object) -> WorkoutCreditResult:
order.append("credit")
return _result()
monkeypatch.setattr(PokeLocker, "start_the_day", reset)
credit.side_effect = paid
credit_session("r1", _session())
assert order == ["reset", "credit"]
class TestCreditSessions:
def test_batch_counts_ingested_and_credited(
self, log_file: Path, credit: MagicMock
) -> None:
other = _session(date="2026-10-08", start_time="2026-10-08T09:00:00.000")
outcome = credit_sessions([("r1", _session()), ("r2", other)])
assert outcome == BatchOutcome(ingested=("r1", "r2"), credited=2)
assert credit.call_count == 2
def test_already_logged_ids_cost_nothing(
self, log_file: Path, credit: MagicMock
) -> None:
credit_sessions([("r1", _session())])
outcome = credit_sessions([("r1", _session())])
assert outcome == BatchOutcome(ingested=(), credited=0)
assert credit.call_count == 1
def test_invalid_session_in_a_batch_is_skipped(
self, log_file: Path, credit: MagicMock
) -> None:
outcome = credit_sessions([("bad", _session(exercises=[]))])
assert outcome == BatchOutcome(ingested=(), credited=0)
assert not log_file.exists()
def test_sessions_that_shared_a_paid_slot_are_warned_about(
self,
log_file: Path,
credit: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
credit.return_value = _result(counted=True)
with caplog.at_level(logging.WARNING):
outcome = credit_sessions([("r1", _session())])
assert outcome == BatchOutcome(ingested=("r1",), credited=0)
assert "1 streamed session(s)" in caplog.text

View File

@ -0,0 +1,119 @@
"""The poke credit's day reset, workout hand-off and the two reply snapshots."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from unittest.mock import MagicMock
import pytest
from screen_locker import _poke_credit
from screen_locker._poke_credit import PokeLocker
from screen_locker._workout_credit import WorkoutCreditResult
if TYPE_CHECKING:
from pathlib import Path
@pytest.fixture
def log_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""A fresh PokeLocker on a tmp log; the day reset stubbed."""
log = tmp_path / "poke_log.json"
def headless(locker_cls: type[PokeLocker]) -> PokeLocker:
locker = object.__new__(locker_cls)
locker.log_file = log
locker.workout_data = {}
return locker
monkeypatch.setattr(_poke_credit, "_headless_locker", headless)
monkeypatch.setattr(_poke_credit, "process_week_transition", lambda *_: [])
monkeypatch.setattr(_poke_credit, "reset_to_base_if_new_day", lambda *_a, **_k: 0)
return log
@pytest.fixture
def credit(monkeypatch: pytest.MonkeyPatch) -> MagicMock:
"""Replace the shared credit step."""
stub = MagicMock(
return_value=WorkoutCreditResult(
shutdown_adjusted=True,
new_debt=None,
extra_bonus_delta=0,
weekly_count=1,
already_counted_today=False,
)
)
monkeypatch.setattr(PokeLocker, "_apply_credit_for_written_entry", stub)
return stub
class TestStartTheDay:
def test_new_day_applies_the_weekly_bonus_after_the_reset(
self, log_file: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
calls: list[str] = []
def week(*_args: object) -> list[str]:
calls.append("week")
return ["+1h streak"]
def reset(*_args: object, **_kwargs: object) -> bool:
calls.append("reset")
return True
def bonus(_self: PokeLocker) -> None:
calls.append("bonus")
monkeypatch.setattr(_poke_credit, "process_week_transition", week)
monkeypatch.setattr(_poke_credit, "reset_to_base_if_new_day", reset)
monkeypatch.setattr(PokeLocker, "_apply_weekly_shutdown_bonus", bonus)
_poke_credit.fresh_locker().start_the_day()
assert calls == ["week", "reset", "bonus"]
def test_same_day_does_not_apply_the_weekly_bonus(
self, log_file: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
bonus = MagicMock()
monkeypatch.setattr(PokeLocker, "_apply_weekly_shutdown_bonus", bonus)
_poke_credit.fresh_locker().start_the_day()
bonus.assert_not_called()
def test_credit_written_sets_the_entry_and_returns_the_result(
self, log_file: Path, credit: MagicMock
) -> None:
locker = _poke_credit.fresh_locker()
assert locker.credit_written({"type": "x"}, [{"a": 1}]) == credit.return_value
assert locker.workout_data == {"type": "x"}
credit.assert_called_once_with([{"a": 1}])
class TestSnapshots:
def test_current_shutdown_renders_tonights_time(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(_poke_credit, "read_shutdown_config", lambda _p: (1, 2, 3))
monkeypatch.setattr(_poke_credit, "tonight_minutes", lambda _c, _d: 20 * 60 + 5)
assert _poke_credit.current_shutdown() == "20:05"
def test_unreadable_config_is_none_and_warned(
self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
monkeypatch.setattr(_poke_credit, "read_shutdown_config", lambda _p: None)
with caplog.at_level(logging.WARNING):
assert _poke_credit.current_shutdown() is None
assert "shutdown=null" in caplog.text
def test_current_gaming_minutes_delegates(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
seen: list[Path] = []
def minutes(log: Path) -> int:
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

@ -0,0 +1,186 @@
"""The poke daemon CLI: key loading, startup refusals, stream wiring."""
from __future__ import annotations
import logging
import threading
from typing import TYPE_CHECKING, Any, ClassVar
from unittest.mock import MagicMock
import pytest
from screen_locker import _poke_credit, poke_server
from screen_locker._poke_server import POKE_PATH
if TYPE_CHECKING:
from pathlib import Path
_KEY_HEX = "ab" * 32
def _key_file(tmp_path: Path, text: str = _KEY_HEX, mode: int = 0o600) -> Path:
path = tmp_path / "key"
path.write_text(text, encoding="ascii")
path.chmod(mode)
return path
class FakeServer:
"""Stands in for PokeServer: records how the daemon drove it."""
instances: ClassVar[list[FakeServer]] = []
def __init__(self, address: tuple[str, int], key: bytes) -> None:
self.address = address
self.key = key
self.gate = threading.Lock()
self.closed = False
self.instances.append(self)
def serve_forever(self) -> None:
return
def server_close(self) -> None:
self.closed = True
@pytest.fixture(autouse=True)
def _daemon_stubs(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""No real budget sum or server socket in any test here."""
FakeServer.instances.clear()
locker = MagicMock()
locker.log_file = tmp_path / "log.json"
monkeypatch.setattr(_poke_credit, "fresh_locker", lambda: locker)
monkeypatch.setattr(_poke_credit, "current_shutdown", MagicMock())
monkeypatch.setattr(_poke_credit, "current_gaming_minutes", MagicMock())
monkeypatch.setattr(poke_server, "PokeServer", FakeServer)
@pytest.fixture(autouse=True)
def stream(monkeypatch: pytest.MonkeyPatch) -> MagicMock:
"""The Firebase stream class; never a real connection."""
stub = MagicMock()
monkeypatch.setattr(poke_server, "SessionStream", stub)
return stub
class TestLoadKey:
def test_reads_a_600_key(self, tmp_path: Path) -> None:
assert poke_server.load_key(_key_file(tmp_path)) == bytes.fromhex(_KEY_HEX)
@pytest.mark.parametrize("mode", [0o640, 0o604, 0o660, 0o644])
def test_group_or_world_access_is_refused_with_the_fix(
self, tmp_path: Path, mode: int
) -> None:
with pytest.raises(ValueError, match="chmod 600"):
poke_server.load_key(_key_file(tmp_path, mode=mode))
def test_malformed_key_is_refused(self, tmp_path: Path) -> None:
with pytest.raises(ValueError, match="hex"):
poke_server.load_key(_key_file(tmp_path, text="short"))
def test_missing_file_raises_oserror(self, tmp_path: Path) -> None:
with pytest.raises(OSError, match="key"):
poke_server.load_key(tmp_path / "key")
class TestMain:
def test_missing_key_refuses_to_start_at_critical(
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
with caplog.at_level(logging.CRITICAL):
code = poke_server.main(["--key-file", str(tmp_path / "nope")])
assert code == 1
assert "bad poke key" in caplog.text
assert "workout_poke_keygen.sh" in caplog.text
assert not FakeServer.instances
def test_loose_key_mode_refuses_to_start(self, tmp_path: Path) -> None:
key = _key_file(tmp_path, mode=0o644)
assert poke_server.main(["--key-file", str(key)]) == 1
assert not FakeServer.instances
def test_bind_failure_refuses_to_start_at_critical(
self,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
) -> None:
def busy(_address: tuple[str, int], _key: bytes) -> Any:
msg = "address in use"
raise OSError(msg)
monkeypatch.setattr(poke_server, "PokeServer", busy)
with caplog.at_level(logging.CRITICAL):
code = poke_server.main(
["--key-file", str(_key_file(tmp_path)), "--port", "9"]
)
assert code == 1
assert "cannot bind :9 (address in use)" in caplog.text
def test_serves_with_the_key_and_starts_the_stream(
self,
tmp_path: Path,
stream: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
argv = ["--key-file", str(_key_file(tmp_path)), "--port", "1234"]
with caplog.at_level(logging.INFO):
code = poke_server.main([*argv, "--bind", "127.0.0.1"])
(server,) = FakeServer.instances
assert code == 0
assert server.address == ("127.0.0.1", 1234)
assert server.key == bytes.fromhex(_KEY_HEX)
assert server.closed
stream.assert_called_once_with(server.gate)
stream.return_value.start.assert_called_once_with()
assert f"127.0.0.1:1234{POKE_PATH}" in caplog.text
assert isinstance(_poke_credit.current_shutdown, MagicMock)
_poke_credit.current_shutdown.assert_called_once_with()
def test_default_bind_is_all_interfaces_on_the_default_port(
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
with caplog.at_level(logging.INFO):
poke_server.main(["--key-file", str(_key_file(tmp_path))])
assert FakeServer.instances[0].address == ("", poke_server.DEFAULT_PORT)
assert f"*:{poke_server.DEFAULT_PORT}" in caplog.text
def test_no_stream_skips_firebase_and_says_so(
self,
tmp_path: Path,
stream: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
with caplog.at_level(logging.WARNING):
code = poke_server.main(
["--key-file", str(_key_file(tmp_path)), "--no-stream"]
)
assert code == 0
stream.assert_not_called()
assert "disabled by --no-stream" in caplog.text
assert FakeServer.instances[0].closed
def test_stream_failure_never_stops_the_lan_poke(
self,
tmp_path: Path,
stream: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
stream.return_value.start.side_effect = RuntimeError("no network")
with caplog.at_level(logging.ERROR):
code = poke_server.main(["--key-file", str(_key_file(tmp_path))])
assert code == 0
assert "Could not start the Firebase session stream" in caplog.text
assert FakeServer.instances[0].closed
def test_server_is_closed_even_when_serving_raises(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
def explode(_self: FakeServer) -> None:
raise KeyboardInterrupt
monkeypatch.setattr(FakeServer, "serve_forever", explode)
with pytest.raises(KeyboardInterrupt):
poke_server.main(["--key-file", str(_key_file(tmp_path))])
assert FakeServer.instances[0].closed

View File

@ -0,0 +1,87 @@
"""A sandbox poke is verified and answered, but writes and credits nothing."""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock
import pytest
from screen_locker import _poke_credit, _poke_server
from screen_locker._poke_credit import PokeLocker
from screen_locker._poke_wire import PokeRequest
if TYPE_CHECKING:
from pathlib import Path
_LOCKER_STEPS = (
"start_the_day",
"credit_written",
"_write_shutdown_config",
"_adjust_shutdown_time_later",
"_apply_credit_for_written_entry",
)
def _request(*, sandbox: bool) -> PokeRequest:
return PokeRequest(
sent_at_ms=1,
nonce="n",
sandbox=sandbox,
record_id="rec-1",
payload={"date": "2026-10-09"},
)
@pytest.fixture
def pc(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> dict[str, MagicMock]:
"""A real PokeLocker on a tmp log with every state-changing step spied."""
def headless(locker_cls: type[PokeLocker]) -> PokeLocker:
locker = object.__new__(locker_cls)
locker.log_file = tmp_path / "log.json"
return locker
spies = {name: MagicMock() for name in (*_LOCKER_STEPS, "ingest", "credit")}
for name in _LOCKER_STEPS:
monkeypatch.setattr(PokeLocker, name, spies[name])
monkeypatch.setattr(_poke_credit, "_headless_locker", headless)
monkeypatch.setattr(_poke_credit, "ingest_session_records", spies["ingest"])
monkeypatch.setattr(_poke_credit, "credit_session", spies["credit"])
monkeypatch.setattr(_poke_credit, "current_shutdown", lambda: "20:30")
monkeypatch.setattr(_poke_credit, "current_gaming_minutes", lambda _p: 75)
return spies
def test_sandbox_replies_ok_with_the_snapshot_and_nothing_credited(
pc: dict[str, MagicMock],
) -> None:
reply = _poke_server._process(_request(sandbox=True))
assert reply["ok"] is True
assert reply["sandbox"] is True
assert reply["credited"] is False
assert reply["duplicate"] is False
assert reply["shutdown"] == "20:30"
assert reply["gaming_budget_minutes"] == 75
assert "nothing written or credited" in str(reply["reason"])
def test_sandbox_never_logs_credits_or_touches_the_shutdown_config(
pc: dict[str, MagicMock], tmp_path: Path
) -> None:
before = sorted(p.name for p in tmp_path.iterdir())
_poke_server._process(_request(sandbox=True))
for name, spy in pc.items():
assert not spy.called, name
assert sorted(p.name for p in tmp_path.iterdir()) == before
assert not (tmp_path / "log.json").exists()
def test_a_real_poke_does_reach_the_credit_step(pc: dict[str, MagicMock]) -> None:
"""Guards the guard: the spies above are wired to the path a real poke takes."""
pc["credit"].return_value = _poke_credit.PokeOutcome(
ok=True, credited=True, duplicate=False, reason="workout credited"
)
reply = _poke_server._process(_request(sandbox=False))
assert reply["credited"] is True
pc["credit"].assert_called_once_with("rec-1", {"date": "2026-10-09"})

View File

@ -0,0 +1,248 @@
"""The poke HTTP front end, driven over real loopback HTTP on an ephemeral port."""
from __future__ import annotations
import hashlib
import hmac
from http.client import HTTPConnection
import json
import socket
import threading
import time
from typing import TYPE_CHECKING, Any
from unittest.mock import MagicMock
import pytest
from screen_locker import _poke_credit, _poke_server
from screen_locker._poke_server import MAX_BODY_BYTES, POKE_PATH, PokeServer
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
# conftest stubs socket.create_connection process-wide (see test_web_server).
_REAL_CREATE_CONNECTION = socket.create_connection
_KEY = bytes(range(32))
def _now_ms() -> int:
return time.time_ns() // 1_000_000
def _body(nonce: str = "n-1", **overrides: object) -> bytes:
doc: dict[str, Any] = {
"v": 1,
"sent_at_ms": _now_ms(),
"nonce": nonce,
"sandbox": False,
"record_id": "rec-1",
"payload": {"date": "2026-10-09", "note": "zażółć"},
}
doc.update(overrides)
return json.dumps(doc, ensure_ascii=False).encode("utf-8")
def _sign(body: bytes) -> str:
return hmac.new(_KEY, body, hashlib.sha256).hexdigest()
@pytest.fixture
def port(monkeypatch: pytest.MonkeyPatch) -> Iterator[int]:
"""A running PokeServer on 127.0.0.1:0; shut down afterwards."""
monkeypatch.setattr(socket, "create_connection", _REAL_CREATE_CONNECTION)
server = PokeServer(("127.0.0.1", 0), _KEY)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
yield server.server_address[1]
finally:
server.shutdown()
server.server_close()
thread.join(timeout=5)
@pytest.fixture
def credit(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> MagicMock:
"""Stub the PC side: tmp locker, fixed snapshot, a spy for the credit."""
locker = MagicMock()
locker.log_file = tmp_path / "log.json"
monkeypatch.setattr(_poke_credit, "fresh_locker", lambda: locker)
monkeypatch.setattr(_poke_credit, "current_shutdown", lambda: "20:30")
monkeypatch.setattr(_poke_credit, "current_gaming_minutes", lambda _p: 75)
spy = MagicMock(
return_value=_poke_credit.PokeOutcome(
ok=True, credited=True, duplicate=False, reason="workout credited"
)
)
monkeypatch.setattr(_poke_credit, "credit_session", spy)
return spy
def _post(
port: int,
body: bytes,
signature: str | None,
path: str = POKE_PATH,
) -> tuple[int, dict[str, Any]]:
conn = HTTPConnection("127.0.0.1", port, timeout=10)
headers = {"Content-Type": "application/json"}
if signature is not None:
headers["X-Poke-Signature"] = signature
conn.request("POST", path, body=body, headers=headers)
resp = conn.getresponse()
data = json.loads(resp.read().decode("utf-8"))
conn.close()
return resp.status, data
def _raw(port: int, lines: list[str], send: bytes = b"") -> tuple[int, dict[str, Any]]:
"""A hand-written POST (so headers http.client would add can be omitted)."""
conn = HTTPConnection("127.0.0.1", port, timeout=10)
conn.putrequest("POST", POKE_PATH)
for line in lines:
name, value = line.split(": ", 1)
conn.putheader(name, value)
conn.endheaders()
if send and conn.sock is not None:
conn.sock.sendall(send)
if conn.sock is not None:
conn.sock.shutdown(socket.SHUT_WR)
resp = conn.getresponse()
data = json.loads(resp.read().decode("utf-8"))
conn.close()
return resp.status, data
class TestCredit:
def test_valid_poke_credits_and_answers_the_contract_shape(
self, port: int, credit: MagicMock
) -> None:
body = _body()
status, reply = _post(port, body, _sign(body))
assert status == 200
assert reply["ok"] is True
assert reply["credited"] is True
assert reply["duplicate"] is False
assert reply["sandbox"] is False
assert reply["shutdown"] == "20:30"
assert reply["gaming_budget_minutes"] == 75
assert isinstance(reply["pc_ms"], int)
credit.assert_called_once_with(
"rec-1", {"date": "2026-10-09", "note": "zażółć"}
)
def test_replayed_nonce_is_409_and_credits_once(
self, port: int, credit: MagicMock
) -> None:
body = _body()
assert _post(port, body, _sign(body))[0] == 200
status, reply = _post(port, body, _sign(body))
assert status == 409
assert reply["ok"] is False
assert reply["shutdown"] is None
assert credit.call_count == 1
def test_stale_timestamp_is_401(self, port: int, credit: MagicMock) -> None:
body = _body(sent_at_ms=_now_ms() - 600_000)
status, reply = _post(port, body, _sign(body))
assert status == 401
assert "stale" in reply["reason"]
credit.assert_not_called()
def test_bad_or_missing_signature_is_401(
self, port: int, credit: MagicMock
) -> None:
body = _body()
assert _post(port, body, "00" * 32)[0] == 401
assert _post(port, body, None)[0] == 401
credit.assert_not_called()
def test_schema_violation_is_400(self, port: int, credit: MagicMock) -> None:
body = _body(v=2)
status, reply = _post(port, body, _sign(body))
assert status == 400
assert "protocol version" in reply["reason"]
credit.assert_not_called()
def test_internal_error_is_500_and_says_the_sync_will_cover_it(
self,
port: int,
credit: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
credit.side_effect = RuntimeError("boom")
body = _body()
status, reply = _post(port, body, _sign(body))
assert status == 500
assert reply["ok"] is False
assert "regular sync will still credit" in reply["reason"]
assert "crashed" in caplog.text
class TestSandbox:
def test_sandbox_poke_over_http_is_answered_but_not_credited(
self, port: int, credit: MagicMock
) -> None:
body = _body(sandbox=True)
status, reply = _post(port, body, _sign(body))
assert (status, reply["ok"], reply["sandbox"]) == (200, True, True)
assert reply["credited"] is False
credit.assert_not_called()
def test_sandbox_with_a_bad_signature_is_still_refused(
self, port: int, credit: MagicMock
) -> None:
status, reply = _post(port, _body(sandbox=True), "00" * 32)
assert status == 401
assert reply["sandbox"] is False
class TestRouting:
def test_unknown_path_is_404(self, port: int, credit: MagicMock) -> None:
body = _body()
status, reply = _post(port, body, _sign(body), path="/v2/other")
assert status == 404
assert "unknown path" in reply["reason"]
def test_get_is_405(self, port: int) -> None:
conn = HTTPConnection("127.0.0.1", port, timeout=10)
conn.request("GET", POKE_PATH)
resp = conn.getresponse()
data = json.loads(resp.read())
conn.close()
assert resp.status == 405
assert "only POST" in data["reason"]
def test_missing_content_length_is_411(self, port: int) -> None:
status, _ = _raw(port, ["Host: x"])
assert status == 411
@pytest.mark.parametrize("value", ["abc", "-5", ""])
def test_malformed_content_length_is_400(self, port: int, value: str) -> None:
status, reply = _raw(port, [f"Content-Length: {value}"])
assert status == 400
assert "bad Content-Length" in reply["reason"]
def test_oversized_body_is_413_without_reading_it(self, port: int) -> None:
status, reply = _raw(port, [f"Content-Length: {MAX_BODY_BYTES + 1}"])
assert status == 413
assert str(MAX_BODY_BYTES) in reply["reason"]
def test_body_at_the_cap_is_read_and_judged_on_its_signature(
self, port: int
) -> None:
body = b"x" * MAX_BODY_BYTES
assert _post(port, body, _sign(body))[0] == 400
def test_truncated_body_is_400(self, port: int) -> None:
status, reply = _raw(port, ["Content-Length: 100"], send=b"0123456789")
assert status == 400
assert "10 of 100 bytes" in reply["reason"]
def test_reply_for_a_refusal_leaves_the_snapshot_null() -> None:
reply = _poke_server._refused("nope")
assert reply["ok"] is False
assert (reply["shutdown"], reply["gaming_budget_minutes"]) == (None, None)
assert reply["reason"] == "nope"

View File

@ -0,0 +1,204 @@
"""The poke wire checks: signature, freshness, replay and schema, in order."""
from __future__ import annotations
import hashlib
import hmac
from http import HTTPStatus
import json
from typing import Any
import pytest
from screen_locker._poke_wire import (
REPLAY_WINDOW_MS,
NonceCache,
PokeRequest,
Rejection,
check_request,
parse_key,
verify_signature,
)
_KEY = bytes(range(32))
_NOW = 1_800_000_000_000
def _doc(**overrides: object) -> dict[str, Any]:
doc: dict[str, Any] = {
"v": 1,
"sent_at_ms": _NOW,
"nonce": "n-1",
"sandbox": False,
"record_id": "rec-1",
"payload": {"date": "2026-10-09"},
}
doc.update(overrides)
return doc
def _sign(body: bytes, key: bytes = _KEY) -> str:
return hmac.new(key, body, hashlib.sha256).hexdigest()
def _check(
doc: dict[str, Any] | bytes,
*,
nonces: NonceCache | None = None,
now_ms: int = _NOW,
) -> PokeRequest | Rejection:
body = doc if isinstance(doc, bytes) else json.dumps(doc).encode("utf-8")
return check_request(
_KEY, body, _sign(body), NonceCache() if nonces is None else nonces, now_ms
)
def _rejected(result: PokeRequest | Rejection, status: HTTPStatus) -> Rejection:
assert isinstance(result, Rejection)
assert result.status is status
return result
class TestParseKey:
def test_decodes_64_hex_chars_with_surrounding_whitespace(self) -> None:
assert parse_key(f" {_KEY.hex()}\n") == _KEY
def test_wrong_length_says_how_long_it_was(self) -> None:
with pytest.raises(ValueError, match="got 4"):
parse_key("abcd")
def test_non_hex_of_the_right_length_is_refused(self) -> None:
with pytest.raises(ValueError, match="not valid hex"):
parse_key("zz" * 32)
class TestVerifySignature:
def test_matching_mac_verifies(self) -> None:
assert verify_signature(_KEY, b"body", _sign(b"body"))
def test_uppercase_and_padded_header_is_accepted(self) -> None:
assert verify_signature(_KEY, b"body", f" {_sign(b'body').upper()} ")
@pytest.mark.parametrize("header", [None, ""])
def test_missing_header_is_false(self, header: str | None) -> None:
assert not verify_signature(_KEY, b"body", header)
def test_wrong_key_is_false(self) -> None:
assert not verify_signature(_KEY, b"body", _sign(b"body", b"k" * 32))
def test_non_ascii_header_is_false_not_an_exception(self) -> None:
assert not verify_signature(_KEY, b"body", "é" * 64)
assert not verify_signature(_KEY, b"body", "☃" * 64)
class TestNonceCache:
def test_second_use_inside_window_is_refused(self) -> None:
cache = NonceCache()
assert cache.check_and_add("a", _NOW, _NOW)
assert not cache.check_and_add("a", _NOW, _NOW + 1)
assert len(cache) == 1
def test_pruned_by_sent_at_after_the_window(self) -> None:
cache = NonceCache()
cache.check_and_add("a", _NOW, _NOW)
assert cache.check_and_add("b", _NOW, _NOW + REPLAY_WINDOW_MS)
assert len(cache) == 2
assert cache.check_and_add("a", _NOW, _NOW + REPLAY_WINDOW_MS + 1)
assert len(cache) == 1 # both old entries pruned, only the new "a" stays
def test_future_stamped_nonce_is_remembered_until_sent_at_plus_window(
self,
) -> None:
cache = NonceCache()
future = _NOW + 100_000
cache.check_and_add("a", future, _NOW)
assert not cache.check_and_add("a", future, _NOW + 150_000)
class TestCheckRequest:
def test_valid_request_is_parsed(self) -> None:
result = _check(_doc(sandbox=True))
assert isinstance(result, PokeRequest)
assert (result.nonce, result.record_id) == ("n-1", "rec-1")
assert result.sandbox is True
assert result.payload == {"date": "2026-10-09"}
def test_bad_signature_is_401_and_parses_nothing(self) -> None:
body = b"not json at all"
result = check_request(_KEY, body, "00" * 32, NonceCache(), _NOW)
assert "signature" in _rejected(result, HTTPStatus.UNAUTHORIZED).reason
def test_bad_signature_beats_every_later_check(self) -> None:
body = json.dumps(_doc(sent_at_ms=0)).encode()
result = check_request(_KEY, body, None, NonceCache(), _NOW)
assert "signature" in _rejected(result, HTTPStatus.UNAUTHORIZED).reason
def test_signed_non_utf8_is_400(self) -> None:
reason = _rejected(_check(b"\xff\xfe"), HTTPStatus.BAD_REQUEST).reason
assert "UTF-8 JSON" in reason
def test_signed_invalid_json_is_400(self) -> None:
_rejected(_check(b"{nope"), HTTPStatus.BAD_REQUEST)
def test_signed_json_array_is_400(self) -> None:
reason = _rejected(_check(b"[1]"), HTTPStatus.BAD_REQUEST).reason
assert "not a JSON object" in reason
@pytest.mark.parametrize("value", [None, "1", True, 1.5])
def test_sent_at_must_be_a_real_int(self, value: object) -> None:
reason = _rejected(
_check(_doc(sent_at_ms=value)), HTTPStatus.BAD_REQUEST
).reason
assert "sent_at_ms" in reason
@pytest.mark.parametrize("skew", [REPLAY_WINDOW_MS + 1, -REPLAY_WINDOW_MS - 1])
def test_stale_or_future_stamp_is_401_naming_the_clock(self, skew: int) -> None:
result = _check(_doc(sent_at_ms=_NOW - skew))
assert "stale" in _rejected(result, HTTPStatus.UNAUTHORIZED).reason
@pytest.mark.parametrize("skew", [REPLAY_WINDOW_MS, -REPLAY_WINDOW_MS])
def test_exactly_the_window_edge_is_still_fresh(self, skew: int) -> None:
assert isinstance(_check(_doc(sent_at_ms=_NOW - skew)), PokeRequest)
@pytest.mark.parametrize("nonce", [None, "", 7])
def test_nonce_must_be_a_non_empty_string(self, nonce: object) -> None:
_rejected(_check(_doc(nonce=nonce)), HTTPStatus.BAD_REQUEST)
def test_replayed_nonce_is_409(self) -> None:
nonces = NonceCache()
assert isinstance(_check(_doc(), nonces=nonces), PokeRequest)
result = _check(_doc(), nonces=nonces)
assert "already used" in _rejected(result, HTTPStatus.CONFLICT).reason
def test_staleness_is_checked_before_replay(self) -> None:
nonces = NonceCache()
_check(_doc(), nonces=nonces)
stale = _doc(sent_at_ms=_NOW - REPLAY_WINDOW_MS - 1)
_rejected(_check(stale, nonces=nonces), HTTPStatus.UNAUTHORIZED)
@pytest.mark.parametrize("version", [None, 2, "1", True])
def test_unsupported_version_is_400(self, version: object) -> None:
reason = _rejected(_check(_doc(v=version)), HTTPStatus.BAD_REQUEST).reason
assert "protocol version" in reason
@pytest.mark.parametrize("sandbox", [None, "false", 0])
def test_sandbox_must_be_a_bool(self, sandbox: object) -> None:
reason = _rejected(_check(_doc(sandbox=sandbox)), HTTPStatus.BAD_REQUEST).reason
assert "'sandbox'" in reason
@pytest.mark.parametrize("record_id", [None, "", 5])
def test_record_id_must_be_a_non_empty_string(self, record_id: object) -> None:
reason = _rejected(
_check(_doc(record_id=record_id)), HTTPStatus.BAD_REQUEST
).reason
assert "'record_id'" in reason
@pytest.mark.parametrize("payload", [None, [], "x"])
def test_payload_must_be_an_object(self, payload: object) -> None:
reason = _rejected(_check(_doc(payload=payload)), HTTPStatus.BAD_REQUEST).reason
assert "'payload'" in reason
def test_schema_failure_still_burns_the_nonce(self) -> None:
nonces = NonceCache()
_rejected(_check(_doc(v=2), nonces=nonces), HTTPStatus.BAD_REQUEST)
_rejected(_check(_doc(), nonces=nonces), HTTPStatus.CONFLICT)

View File

@ -0,0 +1,168 @@
"""Tests for _rtdb_stream: the SSE line parser and the put/patch normaliser."""
from __future__ import annotations
import json
import pytest
from screen_locker._rtdb_stream import SseEvent, device_updates, parse_sse
_LEAF = "log~2Ejson"
def _event(name: str, path: str, data: object) -> SseEvent:
"""A ``put``/``patch`` event carrying ``{path, data}`` as RTDB sends it."""
return SseEvent(name, json.dumps({"path": path, "data": data}))
class TestParseSse:
"""Server-Sent Events framing: a blank line ends each event."""
def test_named_event_with_data(self) -> None:
"""``event:`` + ``data:`` + blank line yields one event."""
lines = ["event: put", 'data: {"path":"/"}', ""]
assert list(parse_sse(lines)) == [SseEvent("put", '{"path":"/"}')]
def test_multiple_data_lines_are_joined_with_newlines(self) -> None:
"""Per the SSE spec, repeated ``data:`` lines join with ``\\n``."""
events = list(parse_sse(["event: patch", "data: a", "data: b", ""]))
assert events == [SseEvent("patch", "a\nb")]
def test_no_space_after_colon_is_accepted(self) -> None:
"""``event:put`` is as valid as ``event: put``."""
assert list(parse_sse(["event:keep-alive", "data:null", ""])) == [
SseEvent("keep-alive", "null")
]
def test_data_without_event_is_a_message(self) -> None:
"""An unnamed event defaults to ``message``."""
assert list(parse_sse(["data: hi", ""])) == [SseEvent("message", "hi")]
def test_event_without_data_still_yields(self) -> None:
"""A name alone is an event (``cancel`` may carry no data)."""
assert list(parse_sse(["event: cancel", ""])) == [SseEvent("cancel", "")]
def test_stray_blank_lines_and_comments_yield_nothing(self) -> None:
"""Blank separators and ``:`` comments / unknown fields are ignored."""
assert list(parse_sse(["", "", ": comment", "id: 7", "retry: 5", ""])) == []
def test_back_to_back_events_do_not_leak_state(self) -> None:
"""Each event starts with a clean name and data."""
lines = ["event: put", "data: 1", "", "data: 2", ""]
assert list(parse_sse(lines)) == [
SseEvent("put", "1"),
SseEvent("message", "2"),
]
def test_unterminated_event_is_not_emitted(self) -> None:
"""Without the closing blank line the event is incomplete: dropped."""
assert list(parse_sse(["event: put", "data: 1"])) == []
class TestDeviceUpdatesPut:
"""``put`` events: the data replaces whatever sits at the path."""
def test_root_put_is_a_full_snapshot(self) -> None:
"""``put /`` carries every device; the caller must REPLACE its cache."""
data = {"phone": {_LEAF: "TEXT-P"}, "pc": {_LEAF: "TEXT-C"}}
full, updates = device_updates(_event("put", "/", data))
assert full is True
assert updates == {"phone": "TEXT-P", "pc": "TEXT-C"}
def test_root_put_with_null_is_an_empty_snapshot(self) -> None:
"""An empty devices node arrives as ``data: null``."""
assert device_updates(_event("put", "/", None)) == (True, {})
def test_root_put_decodes_plain_and_escaped_leaf_keys(self) -> None:
"""The leaf may arrive as ``log.json`` or the escaped ``log~2Ejson``."""
data = {"a": {"log.json": "X"}, "b": {_LEAF: "Y"}}
assert device_updates(_event("put", "/", data))[1] == {"a": "X", "b": "Y"}
def test_root_put_device_without_log_is_none(self) -> None:
"""A device node that is not a dict, lacks the leaf or holds a non-string."""
data = {"a": "scalar", "b": {"other": "x"}, "c": {_LEAF: 5}, "d": None}
updates = device_updates(_event("put", "/", data))[1]
assert updates == {"a": None, "b": None, "c": None, "d": None}
def test_root_put_with_non_object_is_a_type_error(self) -> None:
"""A devices node that is not an object is a protocol violation."""
with pytest.raises(TypeError, match="not an object"):
device_updates(_event("put", "/", ["x"]))
def test_device_level_put(self) -> None:
"""``put /phone`` replaces one device's node."""
full, updates = device_updates(_event("put", "/phone", {_LEAF: "T"}))
assert (full, updates) == (False, {"phone": "T"})
def test_device_level_delete(self) -> None:
"""``put /phone`` with null removes the log."""
assert device_updates(_event("put", "/phone", None)) == (False, {"phone": None})
def test_leaf_level_put_and_delete(self) -> None:
"""``put /phone/log~2Ejson`` sets or clears the text directly."""
path = f"/phone/{_LEAF}"
assert device_updates(_event("put", path, "T")) == (False, {"phone": "T"})
assert device_updates(_event("put", path, None)) == (False, {"phone": None})
def test_leaf_level_put_of_non_string_is_none(self) -> None:
"""A non-text leaf is not a log: the device has none."""
assert device_updates(_event("put", f"/phone/{_LEAF}", 7)) == (
False,
{"phone": None},
)
def test_put_below_the_log_leaf_is_irrelevant(self) -> None:
"""Anything under a device that is not its log changes nothing."""
assert device_updates(_event("put", "/phone/other", "x")) == (False, {})
def test_device_ids_are_decoded(self) -> None:
"""Escaped device names (``~2E``) come back as the real id."""
assert device_updates(_event("put", "/pc~2E1", {_LEAF: "T"}))[1] == {
"pc.1": "T"
}
class TestDeviceUpdatesPatch:
"""``patch`` events: several children, keys may be multi-segment paths."""
def test_patch_with_leaf_paths(self) -> None:
"""Each key is resolved relative to the event path."""
data = {f"phone/{_LEAF}": "T1", f"pc/{_LEAF}": None}
full, updates = device_updates(_event("patch", "/", data))
assert full is False
assert updates == {"phone": "T1", "pc": None}
def test_patch_with_device_keys_and_base_path(self) -> None:
"""A patch at ``/phone`` with a bare leaf key targets that device."""
data = {_LEAF: "T"}
assert device_updates(_event("patch", "/phone", data)) == (
False,
{"phone": "T"},
)
def test_patch_at_root_is_never_a_snapshot(self) -> None:
"""Even at ``/``, a patch merges; it must not replace the cache."""
assert device_updates(_event("patch", "/", {"phone": {_LEAF: "T"}}))[0] is False
def test_patch_with_non_object_data_is_a_type_error(self) -> None:
"""``patch`` data must be an object."""
with pytest.raises(TypeError, match="patch data is str"):
device_updates(_event("patch", "/", "oops"))
class TestDeviceUpdatesMalformed:
"""Garbage must raise, so the caller can warn instead of guessing."""
def test_non_json_data_is_a_value_error(self) -> None:
"""Unparsable data raises ``ValueError``."""
with pytest.raises(json.JSONDecodeError):
device_updates(SseEvent("put", "{not json"))
@pytest.mark.parametrize(
"data", ["[]", "null", '"x"', '{"data": 1}', '{"path": 3, "data": 1}']
)
def test_missing_or_bad_path_is_a_type_error(self, data: str) -> None:
"""Anything but ``{path: str, data: ...}`` is rejected."""
with pytest.raises(TypeError, match="without a path"):
device_updates(SseEvent("put", data))

View File

@ -0,0 +1,101 @@
"""scripts/runnerup_watch.sh starts workout-sync only for a FRESH upload.
endurain-import's adb fallback re-pulls every export it already moved into
``processed/`` and renames each into place, so one import fired ~27 events
and as many workout-sync starts (~370 on 2026-10-09). The script runs as a
black box here: ``inotifywait`` and ``systemctl`` are shims on PATH, the
first replaying a fixed event list, the second recording what was started.
"""
from __future__ import annotations
import os
from pathlib import Path
import subprocess
import pytest
_SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "runnerup_watch.sh"
_UNIT = "workout-sync.service"
# conftest replaces subprocess.run process-wide for every test; this module
# needs the real one, captured at import time before any fixture runs.
_REAL_RUN = subprocess.run
def _shim(path: Path, body: str) -> None:
path.write_text(f"#!/bin/bash\n{body}\n", encoding="utf-8")
path.chmod(0o755)
def _run(
tmp_path: Path, events: list[str], *, processed: list[str]
) -> tuple[list[str], str, int]:
"""Replay ``events`` through the watcher; return systemctl calls, stderr, rc."""
watch = tmp_path / "RunnerUp"
(watch / "processed").mkdir(parents=True)
for name in processed:
(watch / "processed" / name).write_text("<tcx/>", encoding="utf-8")
bin_dir = tmp_path / "bin"
bin_dir.mkdir()
events_file = tmp_path / "events"
events_file.write_text("".join(f"{e}\n" for e in events), encoding="utf-8")
calls = tmp_path / "systemctl.calls"
_shim(bin_dir / "inotifywait", f'cat "{events_file}"')
_shim(
bin_dir / "systemctl",
f'echo "$*" >>"{calls}"\n[[ $2 == is-active ]] && echo inactive\nexit 0',
)
env = {
**os.environ,
"PATH": f"{bin_dir}:{os.environ['PATH']}",
"RUNNERUP_WATCH_DIR": str(watch),
"RUNNERUP_SYNC_UNIT": _UNIT,
}
done = _REAL_RUN(
["bash", str(_SCRIPT)],
env=env,
capture_output=True,
text=True,
timeout=30,
check=False,
)
lines = calls.read_text(encoding="utf-8").splitlines() if calls.exists() else []
return lines, done.stderr, done.returncode
def _starts(calls: list[str]) -> list[str]:
return [c for c in calls if c.startswith("--user start")]
def test_a_fresh_upload_starts_the_sync(tmp_path: Path) -> None:
"""A new top-level TCX is credited at once."""
calls, err, rc = _run(tmp_path, ["2026-10-09-run.tcx"], processed=[])
assert _starts(calls) == [f"--user start {_UNIT}"]
assert "RunnerUp upload finished: 2026-10-09-run.tcx" in err
# inotifywait ending is a failure systemd must restart.
assert rc == 1
def test_a_re_pulled_burst_starts_nothing_and_logs_once(tmp_path: Path) -> None:
"""Names already in processed/ are skipped, with one line per burst."""
old = [f"2026-10-0{d}-run.tcx" for d in range(1, 6)]
calls, err, _ = _run(tmp_path, old, processed=old)
assert _starts(calls) == []
assert err.count("Ignoring re-pulled") == 1
@pytest.mark.parametrize("name", [".2026-10-09-run.tcx", "notes.txt", "x.tcx.part"])
def test_partials_and_non_tcx_are_ignored(tmp_path: Path, name: str) -> None:
"""Dotfiles are partial transfers; anything not *.tcx is not a run."""
calls, _, _ = _run(tmp_path, [name], processed=[])
assert _starts(calls) == []
def test_fresh_upload_inside_a_re_pull_burst_still_counts(tmp_path: Path) -> None:
"""The filter must not swallow the one real upload among the re-pulls."""
calls, _, _ = _run(
tmp_path,
["old-a.tcx", "new.tcx", "old-b.tcx"],
processed=["old-a.tcx", "old-b.tcx"],
)
assert _starts(calls) == [f"--user start {_UNIT}"]

View File

@ -52,7 +52,7 @@ class TestUnlockScreenExtras:
# Simulate before=22:00, after=23:00 → delta=60
old_cfg = (1320, 1320, 300)
new_cfg = (1380, 1380, 300)
locker._read_shutdown_config.side_effect = [old_cfg, new_cfg]
locker._read_shutdown_config.side_effect = [old_cfg, new_cfg, new_cfg]
text_calls: list[str] = []
@ -114,7 +114,7 @@ class TestUnlockScreenExtras:
"""Re-reading the shutdown config fails after the +1h → delta stays 0."""
locker = setup_unlock(mock_tk, tmp_path, seed_today_type="manual_workout")
# old_cfg readable, new_cfg unreadable → no delta can be computed.
locker._read_shutdown_config.side_effect = [(1320, 1320, 300), None]
locker._read_shutdown_config.side_effect = [(1320, 1320, 300), None, None]
text_calls: list[str] = []
object.__setattr__(locker, "_text", lambda msg, **kw: text_calls.append(msg))

View File

@ -0,0 +1,207 @@
"""Tests for _session_stream: byte metering, event dispatch and token renewal."""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
import json
import logging
import threading
from types import SimpleNamespace
from typing import TYPE_CHECKING
from crdt_sync import Hlc, Record
import pytest
import requests
import urllib3
from screen_locker import _session_stream, _stream_cache
from screen_locker._poke_credit import BatchOutcome
from screen_locker._session_stream import SessionStream
from screen_locker._stream_auth import StreamError
if TYPE_CHECKING:
from collections.abc import Iterable, Mapping
_FUTURE = datetime(2999, 1, 1, tzinfo=UTC)
_PAST = datetime.now(UTC) - timedelta(hours=1)
_LEAF = "log~2Ejson"
KEEPALIVE = ("keep-alive", "null")
class FakeRaw:
"""``response.raw``: yields queued chunks, raises queued exceptions."""
def __init__(self, chunks: Iterable[bytes | Exception]) -> None:
self.chunks = list(chunks)
self.closed = False
def read1(self, _size: int) -> bytes:
"""The next chunk (``b""`` at EOF), or raise the queued error."""
if not self.chunks:
return b""
item = self.chunks.pop(0)
if isinstance(item, Exception):
raise item
return item
def close(self) -> None:
"""Mark the connection released."""
self.closed = True
def fake_response(
chunks: Iterable[bytes | Exception] = (),
status_code: int = 200,
text: str = "",
) -> requests.Response:
"""A real ``Response`` whose body is the queued chunks (no sockets)."""
response = requests.Response()
response.status_code = status_code
response.encoding = "utf-8"
response._content = text.encode()
response.raw = FakeRaw(chunks)
return response
def sse(*events: tuple[str, str]) -> bytes:
"""Encode ``(name, data)`` pairs as an SSE byte stream."""
return b"".join(f"event: {n}\ndata: {d}\n\n".encode() for n, d in events)
def make_stream(monkeypatch: pytest.MonkeyPatch) -> SessionStream:
"""A stream with a fake device identity (the real one mints a file)."""
identity = SimpleNamespace(device_id="pc-new", legacy_id="pc-old")
monkeypatch.setattr(_session_stream, "device_identity", lambda: identity)
return SessionStream(threading.Lock())
@pytest.fixture
def stream(monkeypatch: pytest.MonkeyPatch) -> SessionStream:
"""A ``SessionStream`` that never reads or writes the real device id."""
return make_stream(monkeypatch)
def _put(data: object, path: str = "/") -> tuple[str, str]:
return "put", json.dumps({"path": path, "data": data})
class TestConsume:
"""Dispatching events until the server or the renew deadline ends it."""
def test_snapshot_and_patch_are_credited(
self, stream: SessionStream, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Real cache + fake credit: snapshot then patch each credit once."""
batches: list[list[str]] = []
def credit(records: Iterable[tuple[str, Mapping[str, object]]]) -> BatchOutcome:
ids = [rid for rid, _p in records]
batches.append(ids)
return BatchOutcome(tuple(ids), len(ids))
monkeypatch.setattr(_stream_cache._poke_credit, "credit_sessions", credit)
log = _session_log("s1")
log2 = _session_log("s2")
body = sse(
_put({"phone": {_LEAF: log}}),
("patch", json.dumps({"path": "/", "data": {f"phone/{_LEAF}": log2}})),
("auth_revoked", '"expired"'),
)
stream._consume(fake_response([body]), _FUTURE)
assert batches == [["s1"], ["s2"]]
assert stream._got_snapshot is True
def test_keepalives_are_logged_only_a_few_times(
self,
stream: SessionStream,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Keep-alive events 1..3 are logged; later ones are silent."""
body = sse(*[("keep-alive", "null")] * 5, ("auth_revoked", "x"))
with caplog.at_level(logging.INFO):
stream._consume(fake_response([body]), _FUTURE)
seen = [
r.getMessage() for r in caplog.records if "keep-alive #" in r.getMessage()
]
assert seen == [f"Session stream keep-alive #{n}" for n in (1, 2, 3)]
def test_auth_revoked_returns_with_a_warning(
self, stream: SessionStream, caplog: pytest.LogCaptureFixture
) -> None:
"""A revoked token ends the connection on purpose, loudly."""
with caplog.at_level(logging.WARNING):
stream._consume(
fake_response([sse(("auth_revoked", "stale"))]),
_FUTURE,
)
assert any(
"token revoked/expired (stale)" in r.getMessage()
and r.levelno == logging.WARNING
for r in caplog.records
)
def test_cancel_is_a_stream_error(self, stream: SessionStream) -> None:
"""``cancel`` means the rules deny us: back off."""
response = fake_response([sse(("cancel", "permission_denied"))])
with pytest.raises(
StreamError, match=r"cancelled the stream \(permission_denied\)"
):
stream._consume(response, _FUTURE)
def test_unknown_event_is_warned_about_and_ignored(
self, stream: SessionStream, caplog: pytest.LogCaptureFixture
) -> None:
"""Unexpected events are logged at WARNING and the stream carries on."""
response = fake_response([sse(("mystery", "?"), ("auth_revoked", "x"))])
with caplog.at_level(logging.WARNING):
stream._consume(response, _FUTURE)
assert any("ignored event 'mystery'" in r.getMessage() for r in caplog.records)
def test_token_is_renewed_before_expiry(
self, stream: SessionStream, caplog: pytest.LogCaptureFixture
) -> None:
"""Once the renew deadline passes, the next event ends it cleanly."""
response = fake_response([sse(("keep-alive", "null"), ("keep-alive", "null"))])
with caplog.at_level(logging.INFO):
stream._consume(response, _PAST)
assert any("renewing its ID token" in r.getMessage() for r in caplog.records)
assert response.raw.chunks == []
keepalives = [r for r in caplog.records if "keep-alive #" in r.getMessage()]
assert len(keepalives) == 1 # stopped after the first event
def test_server_closing_unasked_is_a_stream_error(
self, stream: SessionStream
) -> None:
"""EOF without auth_revoked/renewal is a failure, with a byte count."""
response = fake_response([sse(("keep-alive", "null"))])
with pytest.raises(
StreamError,
match=f"server closed the stream after {len(sse(KEEPALIVE))} bytes",
):
stream._consume(response, _FUTURE)
@pytest.mark.parametrize(
"error",
[
requests.exceptions.ReadTimeout("read timed out"),
requests.exceptions.ChunkedEncodingError("cut"),
urllib3.exceptions.ProtocolError("connection broken"),
TimeoutError("socket timeout"),
],
)
def test_read_errors_and_timeouts_become_stream_errors(
self, stream: SessionStream, error: Exception
) -> None:
"""A silent socket (read timeout) or broken read ends in StreamError."""
response = fake_response([sse(("keep-alive", "null")), error])
with pytest.raises(
StreamError, match=f"stream broke after {len(sse(KEEPALIVE))} bytes"
) as ei:
stream._consume(response, _FUTURE)
assert ei.value.__cause__ is error
def _session_log(rid: str) -> str:
"""A device-log blob with one completed-session record."""
record = Record(rid, {"payload": ({"exercises": []}, Hlc(1, 0, "n"))})
return json.dumps({rid: record.to_dict()})

View File

@ -0,0 +1,213 @@
"""Tests for _session_stream: connecting, backoff, reconnect and thread control."""
from __future__ import annotations
from datetime import UTC, datetime
import json
import logging
import pytest
import requests
from screen_locker import _session_stream
from screen_locker._rtdb_stream import SseEvent
from screen_locker._session_stream import SessionStream, _ByteMeter
from screen_locker._stream_auth import StreamAuth, StreamError
from screen_locker.tests.test_session_stream import fake_response, make_stream
_RENEW = datetime(2999, 1, 1, tzinfo=UTC)
_LONG = 400.0 # longer than the 300 s minimum lifetime
@pytest.fixture
def stream(monkeypatch: pytest.MonkeyPatch) -> SessionStream:
"""A ``SessionStream`` that never reads or writes the real device id."""
return make_stream(monkeypatch)
class TestByteMeter:
"""Line splitting without waiting for a full buffer."""
def test_lines_split_across_chunks_and_counted(self) -> None:
"""A line broken over two reads is rejoined; CRLF is stripped."""
meter = _ByteMeter()
chunks = [b"ev", b"ent: a\r\ndata: b\n\nx", b"y\n"]
lines = list(meter.lines(fake_response(chunks)))
assert lines == ["event: a", "data: b", "", "xy"]
assert meter.total == sum(map(len, chunks))
def test_trailing_partial_line_is_dropped_at_eof(self) -> None:
"""Bytes after the last newline never form a line."""
meter = _ByteMeter()
assert list(meter.lines(fake_response([b"a\nb"]))) == ["a"]
class TestDispatch:
"""One put/patch handed to the cache."""
def test_undecodable_event_is_warned_and_does_not_end_the_stream(
self, stream: SessionStream, caplog: pytest.LogCaptureFixture
) -> None:
"""Malformed data logs a WARNING naming the fallback, never raises."""
with caplog.at_level(logging.WARNING):
stream._dispatch(SseEvent("put", "{garbage"), 10)
stream._dispatch(SseEvent("patch", "[]"), 10)
messages = [r.getMessage() for r in caplog.records]
assert len(messages) == 2
assert all("undecodable" in m and "15-min workout-sync" in m for m in messages)
assert stream._got_snapshot is False
def test_snapshot_flag_only_set_by_snapshots(
self, stream: SessionStream, caplog: pytest.LogCaptureFixture
) -> None:
"""A patch does not mark the connection as having a snapshot."""
patch_event = SseEvent("patch", json.dumps({"path": "/", "data": {}}))
with caplog.at_level(logging.INFO):
stream._dispatch(patch_event, 7)
assert stream._got_snapshot is False
assert any(
"Session stream patch (7 bytes" in r.getMessage() for r in caplog.records
)
snapshot = SseEvent("put", json.dumps({"path": "/", "data": None}))
with caplog.at_level(logging.INFO):
stream._dispatch(snapshot, 9)
assert stream._got_snapshot is True
assert any(
"Session stream snapshot (9 bytes" in r.getMessage() for r in caplog.records
)
class _FakeHttp:
"""``requests.Session`` stand-in recording the one GET it is given."""
def __init__(self, outcome: requests.Response | Exception) -> None:
self.outcome = outcome
self.calls: list[tuple[str, dict[str, object]]] = []
def get(self, url: str, **kwargs: object) -> requests.Response:
"""Record the request; return or raise the scripted outcome."""
self.calls.append((url, kwargs))
if isinstance(self.outcome, Exception):
raise self.outcome
return self.outcome
def _arm(
stream: SessionStream,
monkeypatch: pytest.MonkeyPatch,
outcome: requests.Response | Exception,
) -> _FakeHttp:
"""Give ``stream`` a canned auth and HTTP layer."""
auth = StreamAuth("https://db/x.json", "TOK", _RENEW)
monkeypatch.setattr(_session_stream, "stream_auth", lambda _path: auth)
http = _FakeHttp(outcome)
monkeypatch.setattr(stream, "_http", http)
return http
class TestConnectOnce:
"""Opening the connection and classifying HTTP failures."""
def test_streams_with_token_and_sse_headers(
self, stream: SessionStream, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A 200 is consumed with the auth's renew deadline, then released."""
response = fake_response()
http = _arm(stream, monkeypatch, response)
consumed: list[tuple[requests.Response, datetime]] = []
monkeypatch.setattr(
stream, "_consume", lambda resp, renew: consumed.append((resp, renew))
)
stream._connect_once()
url, kwargs = http.calls[0]
assert url == "https://db/x.json"
assert kwargs["params"] == {"auth": "TOK"}
assert kwargs["headers"] == {"Accept": "text/event-stream"}
assert kwargs["stream"] is True
assert kwargs["timeout"] == (10, 90)
assert consumed == [(response, _RENEW)]
assert response.raw.closed is True
@pytest.mark.parametrize(
"error",
[requests.ConnectionError("refused"), TimeoutError("connect timed out")],
)
def test_network_error_opening_is_a_stream_error(
self,
stream: SessionStream,
monkeypatch: pytest.MonkeyPatch,
error: Exception,
) -> None:
"""Connect failures and connect timeouts back off."""
_arm(stream, monkeypatch, error)
with pytest.raises(StreamError, match="network error opening") as ei:
stream._connect_once()
assert ei.value.__cause__ is error
@pytest.mark.parametrize(
("status", "kind"),
[(401, "rejected"), (403, "rejected"), (500, "failed")],
)
def test_http_errors_are_classified(
self,
stream: SessionStream,
monkeypatch: pytest.MonkeyPatch,
status: int,
kind: str,
) -> None:
"""401/403 name the token or rules; others are plain failures."""
response = fake_response(status_code=status, text="denied")
_arm(stream, monkeypatch, response)
with pytest.raises(StreamError, match=f"stream {kind}.*HTTP {status} denied"):
stream._connect_once()
class TestRunOne:
"""One connection, its outcome and what gets logged."""
def test_clean_end_is_planned(
self, stream: SessionStream, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Returning normally means renewal or auth_revoked: planned."""
monkeypatch.setattr(stream, "_connect_once", lambda: None)
assert stream._run_one() is True
def test_stream_error_is_a_warning(
self,
stream: SessionStream,
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
) -> None:
"""A StreamError is unplanned and logged at WARNING with the fallback."""
def boom() -> None:
msg = "HTTP 500"
raise StreamError(msg)
monkeypatch.setattr(stream, "_connect_once", boom)
with caplog.at_level(logging.WARNING):
assert stream._run_one() is False
(record,) = caplog.records
assert record.levelno == logging.WARNING
assert "HTTP 500" in record.getMessage()
assert "15-min workout-sync" in record.getMessage()
def test_unexpected_exception_is_logged_with_traceback(
self,
stream: SessionStream,
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
) -> None:
"""A bug must not kill the thread -- and must not be silent."""
def boom() -> None:
msg = "bug"
raise RuntimeError(msg)
monkeypatch.setattr(stream, "_connect_once", boom)
with caplog.at_level(logging.WARNING):
assert stream._run_one() is False
(record,) = caplog.records
assert record.levelno == logging.ERROR
assert record.exc_info is not None
assert "crashed" in record.getMessage()

View File

@ -0,0 +1,171 @@
"""Tests for _session_stream.run_forever: reconnect backoff and thread control."""
from __future__ import annotations
import logging
from types import SimpleNamespace
from typing import TYPE_CHECKING
import pytest
from screen_locker import _session_stream
from screen_locker.tests.test_session_stream import make_stream
if TYPE_CHECKING:
from screen_locker._session_stream import SessionStream
_LONG = 400.0 # longer than the 300 s minimum lifetime
@pytest.fixture
def stream(monkeypatch: pytest.MonkeyPatch) -> SessionStream:
"""A ``SessionStream`` that never reads or writes the real device id."""
return make_stream(monkeypatch)
class _Loop:
"""Scripted ``_run_one`` outcomes with a fake clock, jitter and stop event."""
def __init__(
self,
stream: SessionStream,
monkeypatch: pytest.MonkeyPatch,
script: list[tuple[bool, float, bool]],
factor: float = 1.0,
) -> None:
self.script = script
self.index = 0
self.now = 0.0
self.waits: list[float] = []
self.uniform_args: list[tuple[float, float]] = []
self.factor = factor
self.stream = stream
monkeypatch.setattr(stream, "_run_one", self._run_one)
monkeypatch.setattr(stream, "_stop", self)
monkeypatch.setattr(
_session_stream, "time", SimpleNamespace(monotonic=lambda: self.now)
)
monkeypatch.setattr(_session_stream, "_JITTER", self)
def _run_one(self) -> bool:
planned, duration, snapshot = self.script[self.index]
self.index += 1
self.now += duration
self.stream._got_snapshot = snapshot
return planned
def is_set(self) -> bool:
"""Stop once the script is exhausted."""
return self.index >= len(self.script)
def wait(self, pause: float) -> None:
"""Record the backoff instead of sleeping."""
self.waits.append(pause)
def uniform(self, low: float, high: float) -> float:
"""Record the jitter range; scale between the bounds by ``factor``."""
self.uniform_args.append((low, high))
return low + (high - low) * self.factor
class TestRunForever:
"""Reconnect backoff: growth, cap, reset and the tight-loop guard."""
@staticmethod
def _run(loop: _Loop) -> list[float]:
loop.stream.run_forever()
return loop.waits
def test_backoff_doubles_and_is_capped(
self, stream: SessionStream, monkeypatch: pytest.MonkeyPatch
) -> None:
"""1, 2, 4 ... capped at 60 s while connections keep failing fast."""
loop = _Loop(stream, monkeypatch, [(False, 0.0, False)] * 8)
assert self._run(loop) == [1, 2, 4, 8, 16, 32, 60, 60]
def test_pause_is_jittered_between_half_and_full(
self, stream: SessionStream, monkeypatch: pytest.MonkeyPatch
) -> None:
"""The pause is the delay times a factor drawn from 0.5..1.0."""
loop = _Loop(stream, monkeypatch, [(False, 0.0, False)] * 2, factor=0.0)
assert self._run(loop) == [0.5, 1.0]
assert set(loop.uniform_args) == {(0.5, 1.0)}
def test_long_lived_connection_with_snapshot_resets_the_backoff(
self, stream: SessionStream, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A healthy connection (snapshot + 5 min) restarts the ladder at 1 s."""
script = [(False, 0.0, False)] * 3 + [(False, _LONG, True), (False, 0.0, False)]
assert self._run(_Loop(stream, monkeypatch, script)) == [1, 2, 4, 1, 2]
def test_long_connection_without_snapshot_does_not_reset(
self, stream: SessionStream, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Surviving 5 min without ever getting data proves nothing."""
script = [(False, 0.0, False)] * 3 + [(False, _LONG, False)]
assert self._run(_Loop(stream, monkeypatch, script)) == [1, 2, 4, 8]
def test_short_snapshot_connection_does_not_reset(
self, stream: SessionStream, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A snapshot that dies within 5 min is a flapping link: keep backing off."""
script = [(False, 0.0, False)] * 2 + [(False, 5.0, True)]
assert self._run(_Loop(stream, monkeypatch, script)) == [1, 2, 4]
def test_planned_end_after_a_long_life_reconnects_at_once(
self, stream: SessionStream, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Token renewal after a healthy hour is not a failure: no pause."""
script: list[tuple[bool, float, bool]] = [(True, 3600.0, True)] * 2
assert self._run(_Loop(stream, monkeypatch, script)) == []
def test_planned_end_after_a_short_life_still_backs_off(
self, stream: SessionStream, monkeypatch: pytest.MonkeyPatch
) -> None:
"""auth_revoked straight after connecting must not spin in a tight loop."""
script: list[tuple[bool, float, bool]] = [(True, 1.0, True)] * 3
assert self._run(_Loop(stream, monkeypatch, script)) == [1, 2, 4]
def test_each_pause_is_logged_as_a_warning(
self,
stream: SessionStream,
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Reconnect pauses are visible in the journal."""
loop = _Loop(stream, monkeypatch, [(False, 0.0, False)])
with caplog.at_level(logging.WARNING):
self._run(loop)
(record,) = caplog.records
assert record.levelno == logging.WARNING
assert record.getMessage() == "Reconnecting the session stream in 1.0 s"
def test_stop_before_start_runs_nothing(
self, stream: SessionStream, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A set stop flag exits without connecting."""
loop = _Loop(stream, monkeypatch, [])
stream.run_forever()
assert loop.index == 0
class TestThread:
"""start() and stop()."""
def test_start_runs_the_loop_on_a_named_daemon_thread(
self, stream: SessionStream, monkeypatch: pytest.MonkeyPatch
) -> None:
"""The loop runs off the caller's thread, as a daemon."""
ran: list[str] = []
monkeypatch.setattr(stream, "run_forever", lambda: ran.append("ran"))
thread = stream.start()
thread.join(timeout=5)
assert ran == ["ran"]
assert thread.daemon is True
assert thread.name == "firebase-session-stream"
def test_stop_sets_the_flag(self, stream: SessionStream) -> None:
"""stop() asks the loop to exit after the current connection."""
assert stream._stop.is_set() is False
stream.stop()
assert stream._stop.is_set() is True

View File

@ -145,8 +145,11 @@ class TestANewlyRegisteredEarner:
class TestRealLedgers:
def test_signed_credits_on_disk_reach_the_reset(self, tmp_path: Path) -> None:
"""No mock between the ledgers and the written hour."""
write_ledger(earned_time.LEETCODE, [credit(earned_time.LEETCODE)])
write_ledger(earned_time.READING, [credit(earned_time.READING)])
# Pinned to local midnight: stamped "now", the grace floor (first
# credit + GRACE_MINUTES) beats base+120 whenever this runs after ~19:00.
midnight = datetime.now(tz=UTC).astimezone().replace(hour=0, minute=0, second=0)
write_ledger(earned_time.LEETCODE, [credit(earned_time.LEETCODE, midnight)])
write_ledger(earned_time.READING, [credit(earned_time.READING, midnight)])
state = tmp_path / "state.json"
mixin = _mixin()
with signing_key(tmp_path):

View File

@ -0,0 +1,133 @@
"""Tests for _stream_auth: token, URL and renew deadline for the stream."""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from unittest.mock import MagicMock
from crdt_sync import (
ConfigError,
FirebaseAuthError,
FirebaseConfig,
FirebaseCredentials,
)
import pytest
from screen_locker import _stream_auth
from screen_locker._credential_recovery import RecoveryResult
from screen_locker._stream_auth import StreamAuth, StreamError, stream_auth
_CONFIG = FirebaseConfig(
api_key="key",
database_url="https://db.example/",
project_id="proj",
uid="uid",
email="me@example.com",
)
_EXPIRY = datetime(2030, 1, 1, 12, 0, tzinfo=UTC)
def _provider(*, has_session: bool = True, minted: str = "TOKEN") -> MagicMock:
"""A token provider fake with a cached (or missing) session."""
provider = MagicMock()
provider.has_session.return_value = has_session
provider.id_token.return_value = minted
return provider
class _Fakes:
"""The patched collaborators of ``stream_auth``."""
def __init__(self) -> None:
self.store = MagicMock()
self.store.load.return_value = FirebaseCredentials("id", "refresh", _EXPIRY)
self.providers: list[MagicMock] = [_provider()]
self.recovery = RecoveryResult(recovered=True, reason="ok", donor="todo")
self.recover = MagicMock(side_effect=lambda: self.recovery)
@pytest.fixture
def fakes(monkeypatch: pytest.MonkeyPatch) -> _Fakes:
"""Patch config loading, the credential store, providers and recovery."""
fake = _Fakes()
monkeypatch.setattr(
_stream_auth.FirebaseConfig, "load", classmethod(lambda _cls: _CONFIG)
)
monkeypatch.setattr(_stream_auth, "credential_store_for", lambda _app: fake.store)
monkeypatch.setattr(
_stream_auth,
"FirebaseTokenProvider",
MagicMock(side_effect=lambda *_a, **_k: fake.providers.pop(0)),
)
monkeypatch.setattr(_stream_auth, "try_recover_firebase_session", fake.recover)
return fake
class TestCachedSession:
"""The common path: the cache already holds a session."""
def test_url_token_and_renew_at_from_saved_expiry(self, fakes: _Fakes) -> None:
"""The URL is the encoded path on the DB host; renew 4 min before expiry."""
auth = stream_auth("screen-locker-sync/devices")
assert auth == StreamAuth(
"https://db.example/screen-locker-sync/devices.json",
"TOKEN",
_EXPIRY - timedelta(minutes=4),
)
fakes.recover.assert_not_called()
def test_assumed_lifetime_when_nothing_is_saved(self, fakes: _Fakes) -> None:
"""No stored expiry: assume an hour, still renewing 4 minutes early."""
fakes.store.load.return_value = None
before = datetime.now(UTC)
auth = stream_auth("a/b")
after = datetime.now(UTC)
lifetime = timedelta(hours=1) - timedelta(minutes=4)
assert before + lifetime <= auth.renew_at <= after + lifetime
class TestRecovery:
"""A missing session is healed the way the sync heals it."""
def test_recovered_session_is_used(self, fakes: _Fakes) -> None:
"""After recovery a fresh provider over the same store mints the token."""
fakes.providers = [
_provider(has_session=False),
_provider(minted="RECOVERED"),
]
auth = stream_auth("a/b")
assert auth.url.endswith("/a/b.json")
assert auth == StreamAuth(auth.url, "RECOVERED", auth.renew_at)
fakes.recover.assert_called_once_with()
def test_failed_recovery_is_a_stream_error_with_the_reason(
self, fakes: _Fakes
) -> None:
"""No donor session: back off, and say why."""
fakes.providers = [_provider(has_session=False)]
fakes.recovery = RecoveryResult(recovered=False, reason="no donor found")
with pytest.raises(StreamError, match="recovery failed: no donor found"):
stream_auth("a/b")
class TestUnusableAuth:
"""Library errors become StreamError, keeping the cause."""
def test_config_error(self, fakes: _Fakes, monkeypatch: pytest.MonkeyPatch) -> None:
"""A broken Firebase config file is a StreamError."""
def boom(_cls: type[FirebaseConfig]) -> FirebaseConfig:
msg = "placeholder key"
raise ConfigError(msg)
monkeypatch.setattr(_stream_auth.FirebaseConfig, "load", classmethod(boom))
with pytest.raises(StreamError, match="config unusable: placeholder key") as ei:
stream_auth("a/b")
assert isinstance(ei.value.__cause__, ConfigError)
def test_firebase_auth_error(self, fakes: _Fakes) -> None:
"""A refresh the server rejects is a StreamError."""
fakes.providers[0].id_token.side_effect = FirebaseAuthError("revoked")
with pytest.raises(StreamError, match="ID token: revoked") as ei:
stream_auth("a/b")
assert isinstance(ei.value.__cause__, FirebaseAuthError)

View File

@ -0,0 +1,169 @@
"""Tests for _stream_cache: merge, tombstones, own-device rule and crediting."""
from __future__ import annotations
import json
import logging
import threading
from typing import TYPE_CHECKING
from crdt_sync import Hlc, Record
import pytest
from screen_locker import _stream_cache
from screen_locker._poke_credit import BatchOutcome
from screen_locker._rtdb_stream import SseEvent
from screen_locker._stream_cache import DeviceLogCache
if TYPE_CHECKING:
from collections.abc import Iterable, Mapping
_LEAF = "log~2Ejson"
OWN = "pc-own"
_PAYLOAD = {"exercises": [], "date": "2026-10-09"}
def log_blob(
rid: str, *, wall: int = 1, deleted: bool = False, payload: object = None
) -> str:
"""One device-log blob holding a single (possibly tombstoned) record."""
hlc = Hlc(wall, 0, "n")
record = Record(
rid,
{"payload": (_PAYLOAD if payload is None else payload, hlc)},
deleted=deleted,
deleted_hlc=hlc if deleted else None,
)
return json.dumps({rid: record.to_dict()})
def snapshot(logs: Mapping[str, str]) -> SseEvent:
"""A ``put /`` carrying every device log."""
data = {dev: {_LEAF: text} for dev, text in logs.items()}
return SseEvent("put", json.dumps({"path": "/", "data": data}))
def patch_event(logs: Mapping[str, str | None]) -> SseEvent:
"""A ``patch /`` rewriting some device logs (``None`` deletes one)."""
data = {f"{dev}/{_LEAF}": text for dev, text in logs.items()}
return SseEvent("patch", json.dumps({"path": "/", "data": data}))
class Credit:
"""Stand-in for ``credit_sessions`` that records every batch it is handed."""
def __init__(self) -> None:
self.batches: list[list[str]] = []
self.error: Exception | None = None
self.gate_held: list[bool] = []
self.gate: threading.Lock | None = None
def __call__(
self, records: Iterable[tuple[str, Mapping[str, object]]]
) -> BatchOutcome:
if self.gate is not None:
self.gate_held.append(self.gate.locked())
if self.error is not None:
raise self.error
ids = [rid for rid, _payload in records]
self.batches.append(ids)
return BatchOutcome(ingested=tuple(ids), credited=len(ids))
@pytest.fixture
def credit(monkeypatch: pytest.MonkeyPatch) -> Credit:
"""Replace the real (locker-building) credit step with a recorder."""
fake = Credit()
monkeypatch.setattr(_stream_cache._poke_credit, "credit_sessions", fake)
return fake
@pytest.fixture
def cache(credit: Credit) -> DeviceLogCache:
"""A cache whose own device dir is ``pc-own``."""
gate = threading.Lock()
credit.gate = gate
return DeviceLogCache("sync/devices", frozenset({OWN}), gate)
class TestCredit:
"""Which events credit, and how."""
def test_snapshot_credits_foreign_sessions_under_the_gate(
self, cache: DeviceLogCache, credit: Credit
) -> None:
"""A phone session in the snapshot is credited while the lock is held."""
result = cache.handle(snapshot({"phone": log_blob("s1")}))
assert result.snapshot is True
assert credit.batches == [["s1"]]
assert credit.gate_held == [True]
assert (
"1 session(s) checked, 1 newly logged ['s1'], 1 credited" in result.summary
)
def test_patch_credits_a_new_session(
self, cache: DeviceLogCache, credit: Credit
) -> None:
"""A later patch for the phone credits only what is new."""
cache.handle(snapshot({"phone": log_blob("s1")}))
result = cache.handle(patch_event({"phone": log_blob("s2")}))
assert result.snapshot is False
assert credit.batches == [["s1"], ["s2"]]
def test_already_handed_sessions_are_a_no_op(
self, cache: DeviceLogCache, credit: Credit
) -> None:
"""Re-streaming the same snapshot costs no second credit call."""
cache.handle(snapshot({"phone": log_blob("s1")}))
result = cache.handle(snapshot({"phone": log_blob("s1")}))
assert credit.batches == [["s1"]]
assert "no-op, no file I/O" in result.summary
assert result.snapshot is True
def test_a_newer_hlc_of_the_same_record_is_credited_again(
self, cache: DeviceLogCache, credit: Credit
) -> None:
"""The seen-set is keyed on (id, hlc): an edit is a new thing to check."""
cache.handle(snapshot({"phone": log_blob("s1", wall=1)}))
cache.handle(patch_event({"phone": log_blob("s1", wall=2)}))
assert credit.batches == [["s1"], ["s1"]]
def test_non_session_records_are_not_credited(
self, cache: DeviceLogCache, credit: Credit
) -> None:
"""A record without ``exercises`` (e.g. runnerup_verified) is skipped."""
cache.handle(snapshot({"phone": log_blob("v1", payload={"kind": "x"})}))
assert credit.batches == []
class TestFailures:
"""Nothing is swallowed silently; nothing is marked seen on failure."""
def test_credit_failure_is_logged_and_retried_next_event(
self,
cache: DeviceLogCache,
credit: Credit,
caplog: pytest.LogCaptureFixture,
) -> None:
"""A crediting error logs at ERROR, keeps the stream, retries later."""
credit.error = RuntimeError("disk full")
with caplog.at_level(logging.WARNING):
result = cache.handle(snapshot({"phone": log_blob("s1")}))
assert result.summary == "crediting failed (see above)"
assert result.snapshot is True
failures = [r for r in caplog.records if r.levelno >= logging.ERROR]
assert failures
assert failures[0].exc_info is not None
assert "Crediting 1 streamed session(s) failed" in failures[0].getMessage()
credit.error = None
cache.handle(snapshot({"phone": log_blob("s1")}))
assert credit.batches == [["s1"]]
def test_bad_json_propagates_for_the_caller_to_warn(
self, cache: DeviceLogCache
) -> None:
"""Undecodable events are the connection's to report, not ours to eat."""
with pytest.raises(json.JSONDecodeError):
cache.handle(SseEvent("put", "{nope"))
with pytest.raises(TypeError, match="without a path"):
cache.handle(SseEvent("put", "[]"))

View File

@ -0,0 +1,137 @@
"""Tests for _stream_cache: union merge, tombstones and the own-device rule."""
from __future__ import annotations
import json
import logging
import threading
import pytest
from screen_locker import _stream_cache
from screen_locker._rtdb_stream import SseEvent
from screen_locker._stream_cache import DeviceLogCache
from screen_locker.tests.test_stream_cache import (
OWN,
Credit,
log_blob,
patch_event,
snapshot,
)
@pytest.fixture
def credit(monkeypatch: pytest.MonkeyPatch) -> Credit:
"""Replace the real (locker-building) credit step with a recorder."""
fake = Credit()
monkeypatch.setattr(_stream_cache._poke_credit, "credit_sessions", fake)
return fake
@pytest.fixture
def cache(credit: Credit) -> DeviceLogCache:
"""A cache whose own device dir is ``pc-own``."""
gate = threading.Lock()
credit.gate = gate
return DeviceLogCache("sync/devices", frozenset({OWN}), gate)
class TestMerge:
"""Union across devices, tombstones and the own-device rule."""
def test_highest_hlc_copy_wins_across_devices(
self, cache: DeviceLogCache, credit: Credit
) -> None:
"""One record mirrored in two device logs is credited once."""
both = {"phone": log_blob("s1", wall=1), "tab": log_blob("s1", wall=5)}
result = cache.handle(snapshot(both))
assert credit.batches == [["s1"]]
assert "1 session(s) checked" in result.summary
def test_tombstone_on_another_device_drops_the_record(
self, cache: DeviceLogCache, credit: Credit
) -> None:
"""A delete anywhere beats a live copy elsewhere: nothing is credited."""
logs = {"phone": log_blob("s1"), "tab": log_blob("s1", deleted=True)}
result = cache.handle(snapshot(logs))
assert credit.batches == []
assert "no-op" in result.summary
def test_own_log_tombstone_still_suppresses_a_phone_session(
self, cache: DeviceLogCache, credit: Credit
) -> None:
"""The PC's own log stays in the union: its tombstones must be honoured."""
logs = {OWN: log_blob("s1", deleted=True), "phone": log_blob("s1")}
cache.handle(snapshot(logs))
assert credit.batches == []
def test_event_touching_only_the_own_log_never_credits(
self, cache: DeviceLogCache, credit: Credit
) -> None:
"""Our own push echoing back must not trigger a pass."""
result = cache.handle(patch_event({OWN: log_blob("s9")}))
assert credit.batches == []
assert "only this PC's own log changed (pc-own); no credit" in result.summary
assert result.snapshot is False
def test_own_snapshot_is_still_processed(
self, cache: DeviceLogCache, credit: Credit
) -> None:
"""A full snapshot always runs the union, even if only own logs differ."""
cache.handle(snapshot({OWN: log_blob("s9")}))
assert credit.batches == [["s9"]]
def test_byte_identical_rewrite_does_nothing(
self, cache: DeviceLogCache, credit: Credit
) -> None:
"""RTDB-style repeat of the same text: nothing to read or credit."""
cache.handle(snapshot({"phone": log_blob("s1")}))
result = cache.handle(patch_event({"phone": log_blob("s1")}))
assert "byte-identical rewrite" in result.summary
assert credit.batches == [["s1"]]
def test_deleting_an_unknown_device_is_a_no_op(self, cache: DeviceLogCache) -> None:
"""A ``null`` for a device never cached changes nothing."""
result = cache.handle(patch_event({"ghost": None}))
assert "byte-identical rewrite" in result.summary
def test_patch_null_removes_a_cached_device(
self, cache: DeviceLogCache, credit: Credit
) -> None:
"""Deleting a device log drops it from the cache."""
cache.handle(snapshot({"phone": log_blob("s1")}))
result = cache.handle(patch_event({"phone": None}))
assert "0 device log(s) cached, changed: phone" in result.summary
assert credit.batches == [["s1"]]
def test_snapshot_replaces_the_cache(self, cache: DeviceLogCache) -> None:
"""Devices missing from a new snapshot are gone, and reported changed."""
cache.handle(snapshot({"a": log_blob("s1"), "b": log_blob("s2")}))
result = cache.handle(snapshot({"a": log_blob("s1")}))
assert "1 device log(s) cached, changed: b;" in result.summary
def test_snapshot_ignores_devices_without_alog_blob(
self, cache: DeviceLogCache
) -> None:
"""A device node with no text is not cached."""
event = SseEvent(
"put", json.dumps({"path": "/", "data": {"a": {"other": "x"}}})
)
result = cache.handle(event)
assert "0 device log(s) cached" in result.summary
def test_corrupt_log_is_skipped_with_a_warning(
self,
cache: DeviceLogCache,
credit: Credit,
caplog: pytest.LogCaptureFixture,
) -> None:
"""One broken device log does not hide the others' sessions."""
with caplog.at_level(logging.WARNING):
cache.handle(snapshot({"bad": "not json", "phone": log_blob("s1")}))
assert credit.batches == [["s1"]]
assert any(
"Corrupt sync data at sync/devices/bad/log.json" in r.getMessage()
and r.levelno >= logging.WARNING
for r in caplog.records
)

View File

@ -2,8 +2,8 @@
Regression tests for 2026-06-12 and 2026-08-24, when a completed ~2h workout
sat in Firebase while the PC locked the screen anyway. The PC's Firebase
credential no longer authenticated, so ``remote_client`` degraded to the
GitHub mirror -- which the phone had stopped writing to on 2026-08-15. The
credential no longer authenticated, so the PC degraded to the (since
retired) GitHub mirror -- which the phone had stopped writing to on 2026-08-15. The
pull then returned zero records and the lock chain read that as "you did not
train today" rather than "I could not read the place your workouts live".
@ -101,11 +101,10 @@ class TestFirebaseDegradationIsVisible:
message = "failed to sign in: HTTP 400 (INVALID_LOGIN_CREDENTIALS)"
raise FirebaseAuthError(message)
monkeypatch.setattr(_sync_client, "mirror_client_for", _boom)
monkeypatch.setattr(_sync_client, "firebase_client_for", _boom)
_sync_client.clear_degraded_sources()
github = object()
assert _workout_sync.remote_client(github) is github
assert _workout_sync.sync_client() is None
degraded = _sync_client.degraded_sources()
assert degraded, "a failed Firebase sign-in must be recorded"
assert "INVALID_LOGIN_CREDENTIALS" in degraded[0].reason
@ -117,12 +116,12 @@ class TestFirebaseDegradationIsVisible:
_firebase_config(_sync_client, tmp_path, monkeypatch)
monkeypatch.setattr(
_sync_client,
"mirror_client_for",
lambda _app, client: ReachableClient(("mirror", client)),
"firebase_client_for",
lambda *_a, **_k: ReachableClient(),
)
_sync_client.clear_degraded_sources()
_workout_sync.remote_client(object())
_workout_sync.sync_client()
assert _sync_client.degraded_sources() == []
@ -139,24 +138,23 @@ class TestFirebaseDegradationIsVisible:
_firebase_config(_sync_client, tmp_path, monkeypatch)
attempts: list[int] = []
def _dead_then_alive(_app: object, client: object) -> object:
def _dead_then_alive(*_args: object, **_kwargs: object) -> object:
attempts.append(1)
if len(attempts) == 1:
message = "failed to sign in: HTTP 400 (INVALID_LOGIN_CREDENTIALS)"
raise FirebaseAuthError(message)
return ReachableClient(("mirror", client))
return ReachableClient()
monkeypatch.setattr(_sync_client, "mirror_client_for", _dead_then_alive)
monkeypatch.setattr(_sync_client, "firebase_client_for", _dead_then_alive)
monkeypatch.setattr(
_sync_client,
"try_recover_firebase_session",
lambda: RecoveryResult(recovered=True, reason="rebuilt from a sibling"),
)
_sync_client.clear_degraded_sources()
github = object()
recovered = _workout_sync.remote_client(github)
assert recovered.identity == ("mirror", github)
recovered = _workout_sync.sync_client()
assert isinstance(recovered, ReachableClient)
assert _sync_client.degraded_sources() == [], (
"a source that recovered is not degraded"
)
@ -168,8 +166,8 @@ class TestFirebaseDegradationIsVisible:
Recovery reporting success is not proof the backend is readable, so
the retry is what decides. If it raises too, this is the same lockout
as before and must be recorded -- silently returning the GitHub
mirror is exactly how 2026-08-24 stayed invisible.
as before and must be recorded -- silently handing back a dead
client is exactly how 2026-08-24 stayed invisible.
"""
_firebase_config(_sync_client, tmp_path, monkeypatch)
@ -177,16 +175,15 @@ class TestFirebaseDegradationIsVisible:
msg = "still 400 after refresh"
raise FirebaseAuthError(msg)
monkeypatch.setattr(_sync_client, "mirror_client_for", _always_dead)
monkeypatch.setattr(_sync_client, "firebase_client_for", _always_dead)
monkeypatch.setattr(
_sync_client,
"try_recover_firebase_session",
lambda: RecoveryResult(recovered=True, reason="rebuilt from a sibling"),
)
_sync_client.clear_degraded_sources()
github = object()
assert _workout_sync.remote_client(github) is github
assert _workout_sync.sync_client() is None
degraded = _sync_client.degraded_sources()
assert degraded, "a retry that still fails must be recorded"
assert "still 400 after refresh" in degraded[0].reason
@ -206,7 +203,7 @@ class TestFirebaseDegradationIsVisible:
msg = "HTTP 400 (INVALID_LOGIN_CREDENTIALS)"
raise FirebaseAuthError(msg)
monkeypatch.setattr(_sync_client, "mirror_client_for", _boom)
monkeypatch.setattr(_sync_client, "firebase_client_for", _boom)
monkeypatch.setattr(
_sync_client,
"try_recover_firebase_session",
@ -215,9 +212,8 @@ class TestFirebaseDegradationIsVisible:
),
)
_sync_client.clear_degraded_sources()
github = object()
assert _workout_sync.remote_client(github) is github
assert _workout_sync.sync_client() is None
reason = _sync_client.degraded_sources()[0].reason
assert "INVALID_LOGIN_CREDENTIALS" in reason
assert "no sibling app" in reason
@ -227,10 +223,10 @@ class TestFirebaseDegradationIsVisible:
) -> None:
"""No Firebase config is a choice, not a failure -- do not cry wolf."""
monkeypatch.setattr(
_workout_sync, "CONFIG_FILE", Path("/nonexistent/firebase.json")
_sync_client, "CONFIG_FILE", Path("/nonexistent/firebase.json")
)
_sync_client.clear_degraded_sources()
_workout_sync.remote_client(object())
_workout_sync.sync_client()
assert _sync_client.degraded_sources() == []

View File

@ -2,7 +2,7 @@
Split from ``test_sync_degradation.py`` (250-line cap).
``mirror_client_for`` only checks ``has_session()``, which reads the cached
``firebase_client_for`` only checks ``has_session()``, which reads the cached
JSON off disk and never reaches the network. So on 2026-08-27 a credential the
server had stopped accepting constructed perfectly, the recovery -- wired only
to construction failures -- never ran, and every read and write was refused
@ -38,7 +38,7 @@ class TestRejectedCredentialTriggersRecovery:
) -> None:
"""This is 2026-08-27: present on disk, rejected by the server.
``mirror_client_for`` only checks ``has_session()``, which reads the
``firebase_client_for`` only checks ``has_session()``, which reads the
cached JSON and never reaches the network, so construction SUCCEEDED
and the recovery -- wired only to construction failures -- never ran
while every read and write was being refused with HTTP 401.
@ -46,11 +46,11 @@ class TestRejectedCredentialTriggersRecovery:
_firebase_config(_sync_client, tmp_path, monkeypatch)
built: list[int] = []
def _rejected_then_live(_app: object, _client: object) -> object:
def _rejected_then_live(*_args: object, **_kwargs: object) -> object:
built.append(1)
return RejectedClient() if len(built) == 1 else ReachableClient()
monkeypatch.setattr(_sync_client, "mirror_client_for", _rejected_then_live)
monkeypatch.setattr(_sync_client, "firebase_client_for", _rejected_then_live)
monkeypatch.setattr(
_sync_client,
"try_recover_firebase_session",
@ -58,7 +58,7 @@ class TestRejectedCredentialTriggersRecovery:
)
_sync_client.clear_degraded_sources()
client = _workout_sync.remote_client(object())
client = _workout_sync.sync_client()
assert isinstance(client, ReachableClient), (
"a rejected credential must trigger the same self-heal as a "
@ -71,14 +71,14 @@ class TestRejectedCredentialTriggersRecovery:
) -> None:
"""If it is still refused after healing, say so on the lock screen.
Falling back to GitHub silently is what let weeks of 401s scroll past
Returning a dead client silently is what let weeks of 401s scroll past
in a journal nobody reads.
"""
_firebase_config(_sync_client, tmp_path, monkeypatch)
monkeypatch.setattr(
_sync_client,
"mirror_client_for",
lambda _app, _client: RejectedClient(),
"firebase_client_for",
lambda *_a, **_k: RejectedClient(),
)
monkeypatch.setattr(
_sync_client,
@ -86,9 +86,8 @@ class TestRejectedCredentialTriggersRecovery:
lambda: RecoveryResult(recovered=True, reason="rebuilt from a sibling"),
)
_sync_client.clear_degraded_sources()
github = object()
assert _workout_sync.remote_client(github) is github
assert _workout_sync.sync_client() is None
degraded = _sync_client.degraded_sources()
assert degraded, "a credential the server refuses must be recorded"
assert "rejected" in degraded[0].reason

View File

@ -1,4 +1,4 @@
"""Isolation fixture for the phone-workout GitHub sync token.
"""Autouse isolation fixtures for the phone-workout sync layer.
Split out of ``conftest.py`` (already at the repo's 400-line-per-file cap)
and re-exported there so pytest still picks this up as an autouse fixture
@ -7,7 +7,6 @@ for every test in this directory.
from __future__ import annotations
from contextlib import ExitStack
from typing import TYPE_CHECKING
from unittest.mock import patch
@ -18,40 +17,6 @@ if TYPE_CHECKING:
from pathlib import Path
# Every module that holds SYNC_TOKEN_FILE (~/.config/screen_locker/sync_token)
# by value, bound at import before any fixture could redirect Path.home().
_SYNC_TOKEN_BINDINGS = (
"_constants",
"_manual_push",
"_sync_client",
"_sync_status",
"_workout_sync",
)
@pytest.fixture(autouse=True)
def isolate_sync_token(tmp_path: Path) -> Iterator[None]:
"""Redirect SYNC_TOKEN_FILE to tmp_path so tests never see a real token.
Without this, any test calling ``_verify_phone_workout`` would fall
through to ``pull_synced_workout()``, which -- if a real
``~/.config/screen_locker/sync_token`` happens to exist on the host --
would make a real GitHub API call. Defaulting to a nonexistent tmp_path
file makes ``read_sync_token()`` return None, the same benign "sync not
configured" state every existing test already assumes.
"""
# read_sync_token moved to _sync_client when _workout_sync was split;
# _workout_sync still re-exports the constant, so both names must be
# redirected or a real token on the host leaks into the tests. The rest
# bind it by value too (only for messages today); patching every binding
# is what test_home_isolation's module scan checks.
token = tmp_path / "sync_token"
with ExitStack() as stack:
for module in _SYNC_TOKEN_BINDINGS:
stack.enter_context(patch(f"screen_locker.{module}.SYNC_TOKEN_FILE", token))
yield
@pytest.fixture(autouse=True)
def isolate_sync_device_id(tmp_path: Path) -> Iterator[None]:
"""Redirect the persisted device id so tests never mint one for real.

View File

@ -27,13 +27,11 @@ def _gather(
tmp_path: Path,
*,
state_file: Path | None = None,
token_file: Path | None = None,
firebase_config: Path | None = None,
) -> SyncStatus:
"""Gather status against files under ``tmp_path`` unless overridden."""
return gather_sync_status(
state_file=state_file or tmp_path / "sync_state.json",
token_file=token_file or tmp_path / "sync_token",
firebase_config=firebase_config or tmp_path / "firebase.json",
)
@ -45,15 +43,14 @@ class TestBackendDetection:
"""No credentials is not configured."""
assert _gather(tmp_path).backend == "none"
def test_a_github_token_alone_is_the_mirror_path(self, tmp_path: Path) -> None:
"""A github token alone is the mirror path."""
def test_a_leftover_github_token_does_not_count(self, tmp_path: Path) -> None:
"""A stale GitHub PAT on disk is not a backend: Firebase is the only one."""
(tmp_path / "sync_token").write_text("tok")
assert _gather(tmp_path).backend == "github"
assert _gather(tmp_path).backend == "none"
def test_firebase_wins_when_both_exist(self, tmp_path: Path) -> None:
"""Firebase is primary; GitHub is only the cutover mirror."""
(tmp_path / "sync_token").write_text("tok")
def test_firebase_config_is_the_backend(self, tmp_path: Path) -> None:
"""The shared Firebase config is what makes this machine configured."""
(tmp_path / "firebase.json").write_text("{}")
assert _gather(tmp_path).backend == "firebase"

View File

@ -1,8 +1,8 @@
"""Tests for the phone-workout sync pull (crdt-sync transport).
Covers the token read, the payload predicates, the per-log record extractors
and the cross-device merge. The backend selection (``sync_client`` /
``remote_client``) and the two public pulls live in ``_part2``.
Covers the payload predicates, the per-log record extractors
and the cross-device merge. The backend selection (``sync_client``)
and the two public pulls live in ``_part2``.
"""
from __future__ import annotations
@ -21,31 +21,9 @@ from screen_locker.tests._workout_sync_fixtures import (
_session_record_dict,
)
# The autouse `isolate_sync_token` fixture (registered repo-wide via the
# `pytest_plugins` entry for `screen_locker.tests.test_sync_fixtures` in
# pyproject.toml) already redirects `_workout_sync.SYNC_TOKEN_FILE` into a
# per-test tmp_path, so tests here can write to it directly without needing
# their own isolation fixture. The autouse `_no_real_firebase_config` fixture
# in conftest.py likewise points `CONFIG_FILE` at a nonexistent path, so tests
# that want the Firebase branch must monkeypatch it back at a file they own.
class TestReadSyncToken:
"""ReadSyncToken."""
def test_returns_none_when_file_is_missing(self) -> None:
"""Returns none when file is missing."""
assert _workout_sync.read_sync_token() is None
def test_returns_none_when_file_is_empty(self) -> None:
"""Returns none when file is empty."""
_workout_sync.SYNC_TOKEN_FILE.write_text(" \n")
assert _workout_sync.read_sync_token() is None
def test_returns_the_stripped_token(self) -> None:
"""Returns the stripped token."""
_workout_sync.SYNC_TOKEN_FILE.write_text(" abc123 \n")
assert _workout_sync.read_sync_token() == "abc123"
# The autouse `_no_real_firebase_config` fixture in conftest.py points
# `_sync_client.CONFIG_FILE` at a nonexistent path, so tests that want the
# Firebase branch must monkeypatch it back at a file they own.
class TestIsSessionPayload:

View File

@ -18,7 +18,6 @@ import pytest
from screen_locker import _sync_client, _workout_sync
from screen_locker.tests._workout_sync_fixtures import (
ReachableClient,
_firebase_config,
)
@ -27,7 +26,7 @@ if TYPE_CHECKING:
class TestSyncClient:
"""Every configuration of (GitHub token, Firebase config), plus failure."""
"""Firebase is the only backend: configured, missing, or unusable."""
def test_returns_none_when_nothing_is_configured(self) -> None:
"""Returns none when nothing is configured."""
@ -36,41 +35,36 @@ class TestSyncClient:
def test_warns_when_nothing_is_configured(
self, caplog: pytest.LogCaptureFixture
) -> None:
"""Warns when nothing is configured."""
"""The warning names BOTH directions that stop syncing."""
with caplog.at_level("WARNING"):
_workout_sync.sync_client()
assert "sync is OFF" in caplog.text
assert "Sync is OFF" in caplog.text
assert "will NOT be pushed" in caplog.text
assert "NOT be pulled" in caplog.text
def test_uses_github_alone_when_only_the_token_exists(self) -> None:
"""Uses github alone when only the token exists."""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
github = MagicMock()
with patch.object(_sync_client, "GitHubSyncClient", return_value=github):
assert _workout_sync.sync_client() is github
def test_reason_names_the_missing_config(self) -> None:
"""The reason is a sentence a caller can put into its own result."""
client, reason = _workout_sync.sync_client_or_reason()
assert client is None
assert reason.startswith("no Firebase config at ")
def test_mirrors_when_both_the_token_and_firebase_exist(
def test_never_builds_a_client_without_config(self) -> None:
"""An unconfigured machine must not reach the network at all."""
with patch.object(_sync_client, "firebase_client_for") as build:
_workout_sync.sync_client()
build.assert_not_called()
def test_uses_firebase_when_the_config_exists(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Mirrors when both the token and firebase exist."""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
_firebase_config(_sync_client, tmp_path, monkeypatch)
github = MagicMock()
monkeypatch.setattr(
_sync_client,
"mirror_client_for",
lambda _app, client: ReachableClient(("mirror", client)),
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=github):
assert _workout_sync.sync_client().identity == ("mirror", github)
def test_uses_firebase_alone_when_only_the_config_exists(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A Firebase-only machine must still sync -- no PAT required."""
"""A configured machine syncs over Firebase -- no PAT anywhere."""
_firebase_config(_sync_client, tmp_path, monkeypatch)
firebase = MagicMock()
monkeypatch.setattr(_sync_client, "firebase_client_for", lambda _app: firebase)
monkeypatch.setattr(
_sync_client, "firebase_client_for", lambda *_a, **_k: firebase
)
assert _workout_sync.sync_client() is firebase
assert _workout_sync.sync_client_or_reason() == (firebase, "")
@pytest.mark.parametrize(
"error",
@ -83,14 +77,16 @@ class TestSyncClient:
def test_returns_none_when_firebase_only_is_unusable(
self, error: Exception, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""No PAT to fall back to: report it loudly, do not raise."""
"""No fallback exists: report it loudly, do not raise."""
_firebase_config(_sync_client, tmp_path, monkeypatch)
def _boom(*_args: object, **_kwargs: object) -> None:
raise error
monkeypatch.setattr(_sync_client, "firebase_client_for", _boom)
assert _workout_sync.sync_client() is None
client, reason = _workout_sync.sync_client_or_reason()
assert client is None
assert reason.startswith("Firebase unusable: ")
def test_warns_when_firebase_only_is_unusable(
self,

View File

@ -1,65 +0,0 @@
"""``remote_client`` mirror selection, split from ``test_workout_sync_part2``.
Kept separate from the pulls so no workout-sync test file exceeds the repo's
400-line limit.
"""
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
from crdt_sync import ConfigError
from screen_locker import _sync_client, _workout_sync
from screen_locker.tests._workout_sync_fixtures import (
ReachableClient,
_firebase_config,
)
if TYPE_CHECKING:
import pytest
class TestRemoteClient:
"""Which backend the workout pull reads from during the cutover."""
def test_stays_on_github_without_firebase_config(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
"""An unconfigured machine must not reach the network at all."""
monkeypatch.setattr(
_workout_sync, "CONFIG_FILE", Path("/nonexistent/firebase.json")
)
github = object()
assert _workout_sync.remote_client(github) is github
def test_mirrors_to_github_when_configured(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Configured: reads union both, so either backend's workout counts."""
_firebase_config(_sync_client, tmp_path, monkeypatch)
monkeypatch.setattr(
_sync_client,
"mirror_client_for",
lambda _app, client: ReachableClient(("mirror", client)),
)
github = object()
assert _workout_sync.remote_client(github).identity == ("mirror", github)
def test_falls_back_when_firebase_is_unusable(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A broken Firebase must degrade to GitHub, never fail the pull."""
_firebase_config(_sync_client, tmp_path, monkeypatch)
def _boom(*_args: object, **_kwargs: object) -> None:
message = "no password"
raise ConfigError(message)
monkeypatch.setattr(_sync_client, "mirror_client_for", _boom)
github = object()
assert _workout_sync.remote_client(github) is github

View File

@ -1,8 +1,8 @@
"""Tests for the phone-workout sync pull (crdt-sync transport).
Covers the token read, the payload predicates, the per-log record extractors
and the cross-device merge. The backend selection (``sync_client`` /
``remote_client``) and the two public pulls live in ``_part2``.
Covers the payload predicates, the per-log record extractors and the
cross-device merge. The backend selection (``sync_client``) and the two
public pulls live in ``_part2``.
"""
from __future__ import annotations

View File

@ -12,7 +12,6 @@ from unittest.mock import MagicMock, patch
from crdt_sync import (
FirebaseSyncError,
GitHubSyncError,
)
from screen_locker import _sync_client, _workout_sync
@ -36,16 +35,15 @@ class TestPullSyncedWorkout:
def test_returns_none_none_when_no_token_is_configured(self) -> None:
"""Returns none none when no token is configured."""
with patch.object(_sync_client, "GitHubSyncClient") as client_cls:
with patch.object(_sync_client, "firebase_client_for") as client_cls:
assert _workout_sync.pull_synced_workout() == (None, None)
client_cls.assert_not_called()
def test_returns_the_error_message_on_a_sync_error(self) -> None:
"""A failed device LISTING is a real error, not "nothing to sync"."""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
client = MagicMock()
client.list_directory.side_effect = GitHubSyncError("offline")
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
client.list_directory.side_effect = FirebaseSyncError("offline")
with patch.object(_workout_sync, "sync_client", return_value=client):
assert _workout_sync.pull_synced_workout() == (None, "offline")
def test_does_not_propagate_a_firebase_sync_error(self) -> None:
@ -55,10 +53,9 @@ class TestPullSyncedWorkout:
crash the locker with status=1/FAILURE. It must come back as an error
tuple like any other backend failure.
"""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
client = MagicMock()
client.list_directory.side_effect = FirebaseSyncError("firebase exploded")
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
with patch.object(_workout_sync, "sync_client", return_value=client):
data, error = _workout_sync.pull_synced_workout()
assert data is None
assert error == "firebase exploded"
@ -74,33 +71,32 @@ class TestPullSyncedWorkout:
_firebase_config(_sync_client, tmp_path, monkeypatch)
client = MagicMock()
client.list_directory.side_effect = FirebaseSyncError("firebase exploded")
monkeypatch.setattr(_sync_client, "firebase_client_for", lambda _app: client)
monkeypatch.setattr(
_sync_client, "firebase_client_for", lambda *_a, **_k: client
)
data, error = _workout_sync.pull_synced_workout()
assert data is None
assert error == "firebase exploded"
def test_returns_none_none_when_nothing_has_been_pushed_yet(self) -> None:
"""Returns none none when nothing has been pushed yet."""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
client = _multi_device_client({"phone": None})
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
with patch.object(_workout_sync, "sync_client", return_value=client):
assert _workout_sync.pull_synced_workout() == (None, None)
def test_returns_none_none_when_there_are_no_devices_at_all(self) -> None:
"""Returns none none when there are no devices at all."""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
client = _multi_device_client({})
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
with patch.object(_workout_sync, "sync_client", return_value=client):
assert _workout_sync.pull_synced_workout() == (None, None)
def test_returns_the_payload_on_success(self) -> None:
"""Returns the payload on success."""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
payload = _session_payload()
client = _multi_device_client(
{"phone": json.dumps({"a": _session_record_dict("session:a", payload)})}
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
with patch.object(_workout_sync, "sync_client", return_value=client):
assert _workout_sync.pull_synced_workout() == (payload, None)
def test_finds_a_session_in_a_uuid_named_device_directory(self) -> None:
@ -109,7 +105,6 @@ class TestPullSyncedWorkout:
Reading a single hardcoded ``devices/phone/log.json`` returned a stale
session forever while newer ones sat unread one directory over.
"""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
fresh = _session_payload(note="FROM-UUID-DIR")
client = _multi_device_client(
{
@ -131,12 +126,11 @@ class TestPullSyncedWorkout:
),
}
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
with patch.object(_workout_sync, "sync_client", return_value=client):
assert _workout_sync.pull_synced_workout() == (fresh, None)
def test_returns_the_highest_clock_session_across_devices(self) -> None:
"""Returns the highest clock session across devices."""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
newest = _session_payload(note="NEWEST")
client = _multi_device_client(
{
@ -163,7 +157,7 @@ class TestPullSyncedWorkout:
),
}
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
with patch.object(_workout_sync, "sync_client", return_value=client):
data, error = _workout_sync.pull_synced_workout()
assert error is None
assert data == newest
@ -175,7 +169,6 @@ class TestPullSyncedWorkout:
would hand back a record with none of the fields a caller expects --
even though here they carry the HIGHEST clocks in the log.
"""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
session = _session_payload(note="REAL-SESSION")
client = _multi_device_client(
{
@ -201,14 +194,13 @@ class TestPullSyncedWorkout:
)
}
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
with patch.object(_workout_sync, "sync_client", return_value=client):
data, error = _workout_sync.pull_synced_workout()
assert error is None
assert data == session
def test_skips_a_corrupt_device_log_instead_of_failing(self) -> None:
"""A corrupt log costs that device's sessions, not the whole pull."""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
payload = _session_payload()
client = _multi_device_client(
{
@ -216,12 +208,11 @@ class TestPullSyncedWorkout:
"phone": json.dumps({"a": _session_record_dict("session:a", payload)}),
}
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
with patch.object(_workout_sync, "sync_client", return_value=client):
assert _workout_sync.pull_synced_workout() == (payload, None)
def test_returns_none_none_when_every_device_log_is_corrupt(self) -> None:
"""Returns none none when every device log is corrupt."""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
client = _multi_device_client({"corrupt": "{not valid json"})
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
with patch.object(_workout_sync, "sync_client", return_value=client):
assert _workout_sync.pull_synced_workout() == (None, None)

View File

@ -10,12 +10,12 @@ import json
from unittest.mock import MagicMock, patch
from crdt_sync import (
GitHubSyncError,
FirebaseSyncError,
Hlc,
Record,
)
from screen_locker import _sync_client, _workout_sync
from screen_locker import _workout_sync
from screen_locker.tests._workout_sync_fixtures import (
_manual_payload,
_manual_record_dict,
@ -32,15 +32,13 @@ class TestPullAllManualRecords:
def test_returns_empty_when_listing_fails(self) -> None:
"""Returns empty when listing fails."""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
client = MagicMock()
client.list_directory.side_effect = GitHubSyncError("offline")
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
client.list_directory.side_effect = FirebaseSyncError("offline")
with patch.object(_workout_sync, "sync_client", return_value=client):
assert _workout_sync.pull_all_manual_records() == []
def test_merges_manual_records_across_devices(self) -> None:
"""Merges manual records across devices."""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
client = _multi_device_client(
{
"phone": json.dumps(
@ -51,7 +49,7 @@ class TestPullAllManualRecords:
),
}
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
with patch.object(_workout_sync, "sync_client", return_value=client):
result = _workout_sync.pull_all_manual_records()
assert sorted(rid for rid, _ in result) == ["manual:a", "manual:b"]
@ -63,7 +61,6 @@ class TestPullAllManualRecords:
the phone app look like it worked and then silently come back on the
next 15-minute sync.
"""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
hlc = Hlc(wall_time_ms=1000, counter=0, node_id="phone")
tombstoned = Record(
id="manual:gone",
@ -81,7 +78,7 @@ class TestPullAllManualRecords:
),
}
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
with patch.object(_workout_sync, "sync_client", return_value=client):
result = _workout_sync.pull_all_manual_records()
assert [rid for rid, _ in result] == ["manual:kept"]
@ -92,7 +89,6 @@ class TestPullAllManualRecords:
absent from one device's dict while the live copy won the merge from
the other, so the record was ingested exactly as before.
"""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
hlc = Hlc(wall_time_ms=1000, counter=0, node_id="phone")
tombstoned = Record(
id="manual:dup",
@ -111,30 +107,28 @@ class TestPullAllManualRecords:
),
}
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
with patch.object(_workout_sync, "sync_client", return_value=client):
result = _workout_sync.pull_all_manual_records()
assert [rid for rid, _ in result] == ["manual:keep"]
def test_skips_missing_and_corrupt_device_logs(self) -> None:
"""Skips missing and corrupt device logs."""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
client = _multi_device_client(
{
"phone": json.dumps(
{"a": _manual_record_dict("manual:a", _manual_payload())}
),
"gone": GitHubSyncError("404"),
"gone": FirebaseSyncError("404"),
"empty": None,
"corrupt": "{not json",
}
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
with patch.object(_workout_sync, "sync_client", return_value=client):
result = _workout_sync.pull_all_manual_records()
assert [rid for rid, _ in result] == ["manual:a"]
def test_dedups_same_id_keeping_highest_clock(self) -> None:
"""Dedups same ID keeping highest clock."""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
client = _multi_device_client(
{
"phone": json.dumps(
@ -157,14 +151,13 @@ class TestPullAllManualRecords:
),
}
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
with patch.object(_workout_sync, "sync_client", return_value=client):
result = _workout_sync.pull_all_manual_records()
assert len(result) == 1
assert result[0][1]["cost"] == "NEW"
def test_ignores_a_lower_clock_duplicate_seen_later(self) -> None:
"""Ignores a lower clock duplicate seen later."""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
client = _multi_device_client(
{
"phone": json.dumps(
@ -187,7 +180,7 @@ class TestPullAllManualRecords:
),
}
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
with patch.object(_workout_sync, "sync_client", return_value=client):
result = _workout_sync.pull_all_manual_records()
assert len(result) == 1
assert result[0][1]["cost"] == "NEW"

102
scripts/pair_phone.sh Executable file
View File

@ -0,0 +1,102 @@
#!/bin/bash
# ============================================================================
# Pair the phone's workout_app with this PC's workout poke listener.
#
# Creates ~/.config/workout_poke/key if missing (workout_poke_keygen.sh), then
# hands it and the PC's LAN address to the app over adb via its
# PairPcReceiver broadcast, which stores both in the Android keystore. Success
# is decided by the broadcast's own reply -- `adb shell` exits 0 even when
# the receiver is missing -- so it needs both `result=-1` and `data="paired"`.
#
# The key is on adb's command line for the broadcast's lifetime (that is the
# receiver's interface) but is never printed.
#
# Usage: pair_phone.sh [--sandbox] [--host IP] [-s SERIAL]
# --sandbox pair the sandbox flavor (com.kuhy.workout_app.sandbox)
# --host IP the PC address the phone should poke (default 192.168.1.43)
# -s SERIAL passed to adb when several devices are attached
# ============================================================================
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_DIR
readonly SCRIPT_NAME="${0##*/}"
readonly KEY_FILE="${HOME}/.config/workout_poke/key"
readonly ACTION="com.kuhy.workout_app.PAIR_PC"
readonly RECEIVER="com.kuhy.workout_app.PairPcReceiver"
PACKAGE="com.kuhy.workout_app"
HOST="192.168.1.43"
ADB_ARGS=()
usage() {
echo "Usage: $SCRIPT_NAME [--sandbox] [--host IP] [-s SERIAL]"
exit 0
}
require_adb() {
if ! command -v adb >/dev/null 2>&1; then
echo "Installing missing dependency: android-tools (adb)"
sudo pacman -S --needed --noconfirm android-tools
fi
}
# The broadcast's reply minus the key, should anything ever echo it back.
redact() {
local text="$1" key="$2"
printf '%s\n' "${text//"$key"/<key>}"
}
main() {
require_adb
bash "$SCRIPT_DIR/workout_poke_keygen.sh"
local key output
key="$(<"$KEY_FILE")"
echo "Pairing ${PACKAGE} with host ${HOST} ..."
if ! output="$(adb "${ADB_ARGS[@]}" shell am broadcast \
-a "$ACTION" \
-n "${PACKAGE}/${RECEIVER}" \
--es key "$key" \
--es host "$HOST" 2>&1)"; then
echo "Error: adb failed (is the phone connected and authorized?):" >&2
redact "$output" "$key" >&2
exit 1
fi
if [[ $output == *"result=-1"* && $output == *'data="paired"'* ]]; then
echo "paired"
return 0
fi
echo "Error: ${PACKAGE} did not confirm the pairing. A missing" \
"'result=-1' usually means the app (or this flavor) is not installed" \
"or predates PairPcReceiver. adb said:" >&2
redact "$output" "$key" >&2
exit 1
}
while [[ $# -gt 0 ]]; do
case $1 in
--sandbox)
PACKAGE="com.kuhy.workout_app.sandbox"
shift
;;
--host)
HOST="${2:?--host needs an address}"
shift 2
;;
-s)
ADB_ARGS=(-s "${2:?-s needs a device serial}")
shift 2
;;
-h | --help)
usage
;;
*)
echo "Unknown option: $1" >&2
exit 1
;;
esac
done
main

137
scripts/poke_selftest.py Executable file
View File

@ -0,0 +1,137 @@
#!/usr/bin/env python3
"""Drive the running workout poke listener from this PC, signed with the real key.
Each case POSTs to ``http://127.0.0.1:8773/v1/workout`` exactly as the phone
would (``docs/DOCS-workout-poke-contract.md``) and prints the status and reply:
* ``sandbox`` -- a signed sandbox request: 200, ok, credited=false;
* ``badsig`` -- a signature for different bytes: 401;
* ``replay`` -- the same nonce twice: 200 (sandbox), then 409;
* ``stale`` -- ``sent_at_ms`` 10 minutes old: 401;
* ``duplicate`` -- a NON-sandbox poke of today's already-logged session
(record ``2026-10-09T15:10:40.953``): duplicate=true, credited=false;
* ``latency`` -- N sandbox round trips, p50/p95 in ms.
Usage: ``python3 scripts/poke_selftest.py CASE [--count N] [--port P]``.
"""
from __future__ import annotations
import argparse
import hashlib
import hmac
import http.client
import json
from pathlib import Path
import statistics
import sys
import time
import uuid
KEY_FILE = Path.home() / ".config" / "workout_poke" / "key"
STALE_MS = 600_000
DUPLICATE_RECORD_ID = "2026-10-09T15:10:40.953"
# The session as the phone syncs it (same shape as the shared fixture).
DUPLICATE_PAYLOAD: dict[str, object] = {
"date": "2026-10-09",
"start_time": DUPLICATE_RECORD_ID,
"workout_type": "A",
"duration_seconds": 7020.5,
"succeeded": True,
"exercises": [{"name": "Squat", "weight_kg": 100.0, "sets": [5, 5, 5, 5, 5]}],
}
def _body(
*, sandbox: bool, sent_at_ms: int | None = None, nonce: str | None = None
) -> bytes:
"""One request body; compact separators like the phone's encoder."""
doc = {
"v": 1,
"sent_at_ms": sent_at_ms
if sent_at_ms is not None
else time.time_ns() // 1_000_000,
"nonce": nonce or str(uuid.uuid4()),
"sandbox": sandbox,
"record_id": DUPLICATE_RECORD_ID,
"payload": DUPLICATE_PAYLOAD,
}
return json.dumps(doc, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
def _post(
port: int, key: bytes, body: bytes, *, sign_over: bytes | None = None
) -> tuple[int, dict[str, object], float]:
"""POST ``body``, signed over ``sign_over`` (default: itself).
Returns (status, reply, round-trip ms).
"""
signature = hmac.new(
key, sign_over if sign_over is not None else body, hashlib.sha256
).hexdigest()
started = time.perf_counter()
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=10)
try:
conn.request(
"POST",
"/v1/workout",
body=body,
headers={"Content-Type": "application/json", "X-Poke-Signature": signature},
)
response = conn.getresponse()
reply = json.loads(response.read())
finally:
conn.close()
return response.status, reply, (time.perf_counter() - started) * 1000
def _show(label: str, result: tuple[int, dict[str, object], float]) -> int:
status, reply, ms = result
shown = json.dumps(reply, ensure_ascii=False)
sys.stdout.write(f"{label}: HTTP {status} rtt={ms:.1f}ms {shown}\n")
return status
def _latency(port: int, key: bytes, count: int) -> None:
rtts = sorted(_post(port, key, _body(sandbox=True))[2] for _ in range(count))
p95 = rtts[max(0, round(0.95 * count) - 1)]
p50 = statistics.median(rtts)
sys.stdout.write(
f"latency over {count} sandbox pokes: p50={p50:.1f}ms "
f"p95={p95:.1f}ms max={rtts[-1]:.1f}ms\n"
)
def main() -> int:
"""Run one case against the local listener."""
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument(
"case", choices=["sandbox", "badsig", "replay", "stale", "duplicate", "latency"]
)
parser.add_argument("--count", type=int, default=20)
parser.add_argument("--port", type=int, default=8773)
args = parser.parse_args()
key = bytes.fromhex(KEY_FILE.read_text(encoding="ascii").strip())
if args.case == "sandbox":
_show("sandbox", _post(args.port, key, _body(sandbox=True)))
elif args.case == "badsig":
_show(
"badsig",
_post(args.port, key, _body(sandbox=True), sign_over=b"something else"),
)
elif args.case == "replay":
body = _body(sandbox=True)
_show("replay first", _post(args.port, key, body))
_show("replay again", _post(args.port, key, body))
elif args.case == "stale":
stale = time.time_ns() // 1_000_000 - STALE_MS
_show("stale", _post(args.port, key, _body(sandbox=True, sent_at_ms=stale)))
elif args.case == "duplicate":
_show("duplicate (NON-sandbox)", _post(args.port, key, _body(sandbox=False)))
else:
_latency(args.port, key, args.count)
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@ -15,6 +15,13 @@
# timer run; when one was already in flight it started before this file was
# complete, so the start merged into it and a second start is needed.
#
# Only a FRESH top-level *.tcx counts. endurain-import's adb fallback re-pulls
# every phone export it does not see at the top level -- including the ones it
# already moved into processed/ -- and renames each into place, so every
# 15-min import used to fire ~27 moved_to events and as many workout-sync
# starts (~370 on 2026-10-09). A name already in processed/ was handled
# before, and dotfiles are partial transfers; both are skipped with zero forks.
#
# Run by runnerup-watch.service (Restart=always). Event-driven: no polling.
# ============================================================================
@ -22,6 +29,7 @@ set -euo pipefail
readonly WATCH_DIR="${RUNNERUP_WATCH_DIR:-$HOME/data/cloud/RunnerUp}"
readonly SYNC_UNIT="${RUNNERUP_SYNC_UNIT:-workout-sync.service}"
readonly PROCESSED_DIR="$WATCH_DIR/processed"
log() {
printf '%s\n' "$*" >&2
@ -47,6 +55,15 @@ ingest() {
fi
}
# is_fresh_upload NAME -- true for a new top-level TCX, false for anything
# endurain-import already handled (its copy is in processed/) or a partial.
# Builtins only: this runs once per inotify event.
is_fresh_upload() {
local name="$1"
[[ $name == *.tcx && $name != .* ]] || return 1
[[ ! -e $PROCESSED_DIR/$name ]]
}
validate_requirements() {
if ! command -v inotifywait >/dev/null 2>&1; then
log "ERROR: inotifywait missing (pacman -S inotify-tools) — RunnerUp" \
@ -63,9 +80,19 @@ validate_requirements() {
main() {
validate_requirements
log "Watching $WATCH_DIR for finished RunnerUp TCX uploads"
local name
local name now last_skip_log=0
while IFS= read -r name; do
[[ $name == *.tcx ]] || continue
if ! is_fresh_upload "$name"; then
[[ $name == *.tcx ]] || continue
# One line per burst, not per file: the re-pull lands ~27 at once.
printf -v now '%(%s)T' -1
if ((now - last_skip_log > 60)); then
log "Ignoring re-pulled $name (already in processed/; no" \
"workout-sync) — further re-pulls this minute not logged"
last_skip_log=$now
fi
continue
fi
ingest "$name"
done < <(inotifywait -m -q -e close_write -e moved_to --format '%f' "$WATCH_DIR")
log "ERROR: inotifywait on $WATCH_DIR exited — restarting via systemd"

View File

@ -34,7 +34,6 @@ import sys
from crdt_sync import (
FileSyncStateStore,
GitHubSyncClient,
LogCodec,
Record,
RevisionTracking,
@ -42,12 +41,7 @@ from crdt_sync import (
sync_log,
)
from screen_locker._constants import (
SYNC_REPO_NAME,
SYNC_REPO_OWNER,
SYNC_STATE_FILE,
SYNC_TIMEOUT_SECONDS,
)
from screen_locker._constants import SYNC_STATE_FILE
from screen_locker._device import device_identity
from screen_locker._manual_push import (
_decode_log,
@ -55,7 +49,7 @@ from screen_locker._manual_push import (
records_from_workout_log,
)
from screen_locker._sync_tombstones import add_tombstone
from screen_locker._workout_sync import _DEVICES_PREFIX, read_sync_token, remote_client
from screen_locker._workout_sync import _DEVICES_PREFIX, sync_client_or_reason
_logger = logging.getLogger(__name__)
@ -72,15 +66,10 @@ def _report(message: str) -> None:
def _sync(local_log: dict[str, Record]) -> dict[str, Record]:
"""Run one sync tick with *local_log* as this device's view; return the merge."""
identity = device_identity()
token = read_sync_token()
if token is None:
msg = "no sync token — cannot reach the store"
client, reason = sync_client_or_reason()
if client is None:
msg = f"cannot reach the Firebase sync store: {reason}"
raise SystemExit(msg)
client = remote_client(
GitHubSyncClient(
SYNC_REPO_OWNER, SYNC_REPO_NAME, token, timeout_seconds=SYNC_TIMEOUT_SECONDS
)
)
return sync_log(
SyncTarget(
client=client,

87
scripts/workout_poke_keygen.sh Executable file
View File

@ -0,0 +1,87 @@
#!/bin/bash
# ============================================================================
# Create the phone -> PC workout poke key if it does not exist yet.
#
# The key is 32 random bytes as 64 hex characters in
# ~/.config/workout_poke/key (mode 600, dir 700). workout-poke.service verifies
# each poke's HMAC with it and refuses to start without it; pair_phone.sh
# copies it to the phone. An existing key is NEVER overwritten: a new key
# would silently unpair the phone. Prints the path, never the key.
#
# Usage: workout_poke_keygen.sh [--key-file PATH]
# ============================================================================
set -euo pipefail
KEY_FILE="${HOME}/.config/workout_poke/key"
readonly SCRIPT_NAME="${0##*/}"
readonly KEY_HEX_LENGTH=64
usage() {
echo "Usage: $SCRIPT_NAME [--key-file PATH]"
exit 0
}
# An existing key must still be well-formed and private, or the daemon will
# refuse it; say so here rather than let the unit fail later.
check_existing_key() {
local key mode
mode="$(stat -c '%a' "$KEY_FILE")"
if [[ $mode != "600" ]]; then
echo "Error: $KEY_FILE has mode $mode; run: chmod 600 $KEY_FILE" >&2
exit 1
fi
key="$(<"$KEY_FILE")"
if [[ ! $key =~ ^[0-9a-f]{$KEY_HEX_LENGTH}$ ]]; then
echo "Error: $KEY_FILE is not $KEY_HEX_LENGTH lowercase hex characters;" \
"move it aside and re-run (the phone must then be re-paired)" >&2
exit 1
fi
echo "Key already present: $KEY_FILE (left unchanged)"
}
create_key() {
local dir key
dir="$(dirname "$KEY_FILE")"
mkdir -p "$dir"
chmod 700 "$dir"
key="$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')"
if [[ ! $key =~ ^[0-9a-f]{$KEY_HEX_LENGTH}$ ]]; then
echo "Error: could not read 32 random bytes from /dev/urandom" >&2
exit 1
fi
# umask + noclobber: the file is born 600 and a racing creator loses.
(
umask 077
set -o noclobber
printf '%s\n' "$key" >"$KEY_FILE"
)
echo "Created key: $KEY_FILE (mode 600)"
}
main() {
if [[ -e $KEY_FILE ]]; then
check_existing_key
else
create_key
fi
}
while [[ $# -gt 0 ]]; do
case $1 in
--key-file)
KEY_FILE="$2"
shift 2
;;
-h | --help)
usage
;;
*)
echo "Unknown option: $1" >&2
exit 1
;;
esac
done
main

View File

@ -72,6 +72,18 @@
android:foregroundServiceType="dataSync"
android:exported="false"
android:stopWithTask="false" />
<!-- adb-only pairing for the phone->PC workout poke. Exported because
the shell is another uid; android.permission.DUMP is held by the
adb shell and cannot be granted to a third-party app, so nothing
else on the phone can send it. See PairPcReceiver. -->
<receiver
android:name=".PairPcReceiver"
android:exported="true"
android:permission="android.permission.DUMP">
<intent-filter>
<action android:name="com.kuhy.workout_app.PAIR_PC" />
</intent-filter>
</receiver>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data

View File

@ -24,9 +24,27 @@ class MainActivity : FlutterActivity() {
else -> result.notImplemented()
}
}
// Hands a key parked by PairPcReceiver to Dart, which stores it in
// secure storage and only then asks for the parked copy to go.
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, PAIRING_CHANNEL)
.setMethodCallHandler { call, result ->
when (call.method) {
"takePending" -> try {
result.success(PairPcReceiver.takePending(applicationContext))
} catch (error: Exception) {
result.error("pairing_unreadable", error.toString(), null)
}
"clearPending" -> {
PairPcReceiver.clearPending(applicationContext)
result.success(null)
}
else -> result.notImplemented()
}
}
}
companion object {
const val PAIRING_CHANNEL = "com.kuhy.workout_app/pc_pairing"
const val CHANNEL = "com.kuhy.workout_app/sandbox"
const val LOG_TAG = "WorkoutSandbox"
}

View File

@ -0,0 +1,94 @@
package com.kuhy.workout_app
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Process
import android.util.Log
import org.json.JSONObject
import java.io.File
/**
* Pairs this install with the PC for the workout poke, over adb only.
*
* `scripts/pair_phone.sh` on the PC runs
* `adb shell am broadcast -a com.kuhy.workout_app.PAIR_PC -n <pkg>/com.kuhy.workout_app.PairPcReceiver --es key <64 hex> [--es host <ip>]`.
*
* Two gates keep anything but the adb shell out:
* - the manifest requires the sender to hold `android.permission.DUMP`,
* which the shell has and no third-party app can be granted;
* - on API >= 34 the sender uid, when the platform shares it, must be the
* shell (2000) or root (0).
*
* A manifest receiver runs without a Dart isolate, so the key is parked in
* a private no-backup file; Dart moves it into secure storage the next time
* it asks (`PcPairing.absorbPending`) and only then deletes the file.
* The result code/data are what `am broadcast` prints and what
* `scripts/pair_phone.sh` parses: `result=-1 data="paired"` on success,
* `result=0 data="<reason>"` on rejection. `result=0` with NO data means the
* receiver never ran (sender lacks DUMP, or the OEM blocked a stopped app).
* An omitted host keeps the current setting.
*/
class PairPcReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action != ACTION) return refuse("unexpected action ${intent.action}")
if (Build.VERSION.SDK_INT >= 34) {
val uid = sentFromUid
Log.i(TAG, "pair request sentFromUid=$uid")
if (uid != Process.INVALID_UID && uid != SHELL_UID && uid != ROOT_UID) {
return refuse("sender uid $uid is not the adb shell")
}
}
val key = intent.getStringExtra("key")?.trim()?.lowercase()
if (key == null || !KEY_PATTERN.matches(key)) {
return refuse("key must be exactly 64 hex characters")
}
val host = intent.getStringExtra("host")?.trim()
if (host != null && !HOST_PATTERN.matches(host)) {
return refuse("host '$host' is not an IPv4 address or hostname")
}
val json = JSONObject().put("key", key)
if (host != null) json.put("host", host)
try {
pendingFile(context).writeText(json.toString())
} catch (error: Exception) {
return refuse("could not park the key: $error")
}
Log.i(TAG, "pairing parked for ${context.packageName}; the app absorbs it on next use")
setResult(RESULT_PAIRED, "paired", null)
}
private fun refuse(reason: String) {
Log.w(TAG, "pairing refused: $reason")
setResult(RESULT_REFUSED, reason, null)
}
companion object {
const val ACTION = "com.kuhy.workout_app.PAIR_PC"
const val TAG = "WorkoutPair"
const val RESULT_PAIRED = -1 // Activity.RESULT_OK
const val RESULT_REFUSED = 0 // Activity.RESULT_CANCELED
private const val SHELL_UID = 2000
private const val ROOT_UID = 0
private val KEY_PATTERN = Regex("^[0-9a-f]{64}$")
private val HOST_PATTERN = Regex("^[A-Za-z0-9][A-Za-z0-9.-]{0,252}$")
fun pendingFile(context: Context): File =
File(context.noBackupFilesDir, "pc_pairing_pending.json")
/** `{key, host?}` parked by [onReceive], or null. */
fun takePending(context: Context): Map<String, String>? {
val file = pendingFile(context)
if (!file.exists()) return null
val json = JSONObject(file.readText())
val out = mutableMapOf("key" to json.getString("key"))
if (json.has("host")) out["host"] = json.getString("host")
return out
}
fun clearPending(context: Context) {
pendingFile(context).delete()
}
}
}

View File

@ -12,6 +12,7 @@ import 'package:workout_app/services/break_service_controller.dart';
import 'package:workout_app/services/foreground_break_client_flutter.dart';
import 'package:workout_app/services/http_server_service.dart';
import 'package:workout_app/services/lock_mode.dart';
import 'package:workout_app/services/pc_pairing.dart';
import 'package:workout_app/services/progression_sync_service.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/sync_device_id.dart';
@ -71,6 +72,9 @@ void main(List<String> args) async {
);
}
await StorageService.init();
// Absorbs a key parked by an adb pairing and points the sandbox's one
// network exception at the configured PC, before anything can poke.
await PcPairing.load();
if (Sandbox.enabled) {
Sandbox.restSecs = await StorageService.instance.getSandboxRestSecs(
Sandbox.defaultRestSecs,

View File

@ -4,19 +4,44 @@ library;
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:workout_app/services/pc_poke_wire.dart';
/// Makes every `dart:io` HTTP connection fail before a socket is opened.
/// Makes every `dart:io` HTTP connection fail before a socket is opened --
/// except the workout poke to the configured PC.
///
/// Installed as `HttpOverrides.global` by `main` in the sandbox. Firebase and
/// GitHub sync both go through `package:http`, whose IO client is built from
/// `HttpClient()` and therefore from these overrides — one seam, not one
/// guard per service. A refused connection surfaces as a normal sync failure
/// in the UI, which is the honest answer: the sandbox is offline by design.
///
/// The single exception is `http://<pokeHost>:8773/v1/workout`, so a sandbox
/// workout can time the PC round trip. The PC verifies the signed
/// `"sandbox": true` and never writes or credits it. Firebase and GitHub are
/// https on 443 and can never match.
class SandboxHttpOverrides extends HttpOverrides {
/// The PC host the poke may reach; set by `PcPairing` whenever the host is
/// loaded or saved. Null means no exception at all.
static String? pokeHost;
/// Whether [uri] is exactly the poke endpoint on the configured PC.
static bool allows(Uri uri) =>
pokeHost != null &&
uri.scheme == 'http' &&
uri.host == pokeHost &&
uri.port == kPcPokePort &&
uri.path == kPcPokePath;
@override
HttpClient createHttpClient(SecurityContext? context) {
return super.createHttpClient(context)
..connectionFactory = (uri, proxyHost, proxyPort) {
if (proxyHost == null && allows(uri)) {
debugPrint(
'WorkoutSandbox: allowing the PC poke to ${uri.host}:${uri.port}',
);
return Socket.startConnect(uri.host, uri.port);
}
debugPrint(
'WorkoutSandbox: refused network connection to ${uri.host} — the '
'sandbox never talks to Firebase or GitHub.',

View File

@ -20,6 +20,7 @@ import 'package:workout_app/screens/github_mirror_screen.dart';
import 'package:workout_app/services/backup_service.dart';
import 'package:workout_app/services/firebase_backend.dart';
import 'package:workout_app/services/google_sign_in_backend.dart';
import 'package:workout_app/services/pc_pairing.dart';
import 'package:workout_app/services/progression_sync_service.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/ui/theme.dart';
@ -29,6 +30,7 @@ part 'settings_screen_actions.dart';
part 'settings_screen_deload.dart';
part 'settings_screen_exercise_list.dart';
part 'settings_screen_exercise_sections.dart';
part 'settings_screen_pc_link.dart';
part 'settings_screen_rows.dart';
part 'settings_screen_sandbox.dart';
part 'settings_screen_sections.dart';
@ -230,6 +232,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
onOpenGitHubMirror: () => unawaited(_openGitHubMirror()),
),
const SizedBox(height: 20),
_PcLinkSection(pairingLoader: widget.pcPairingLoader),
const SizedBox(height: 20),
_OfflineBackupSection(
storageGranted: _storageGranted,
onGrantStorage: _grantStorage,

View File

@ -0,0 +1,123 @@
// The PC LINK section: where the instant workout credit is sent.
//
// A `part` like the other sections. It owns its state: the address field and
// the paired flag come from PcPairing, never from the exercise state the
// surrounding screen edits. The key itself is never shown or editable here --
// it only ever arrives over adb (scripts/pair_phone.sh on the PC).
part of 'settings_screen.dart';
/// PC address field and the "paired" indicator.
class _PcLinkSection extends StatefulWidget {
const _PcLinkSection({required this.pairingLoader});
/// Loads the pairing; injected through [SettingsScreen.pcPairingLoader].
final Future<PcPairingState> Function() pairingLoader;
@override
State<_PcLinkSection> createState() => _PcLinkSectionState();
}
class _PcLinkSectionState extends State<_PcLinkSection> {
final TextEditingController _host = TextEditingController();
bool? _paired;
String? _status;
@override
void initState() {
super.initState();
unawaited(_load());
}
Future<void> _load() async {
final state = await widget.pairingLoader();
if (!mounted) return;
_host.text = state.host;
setState(() => _paired = state.paired);
}
@override
void dispose() {
_host.dispose();
super.dispose();
}
Future<void> _save() async {
final host = _host.text.trim();
if (!isValidPcHost(host)) {
setState(() => _status = 'Not an IPv4 address or hostname: "$host".');
return;
}
await PcPairing.saveHost(host);
SandboxLog.event('pc host saved', {'host': host});
setState(() => _status = 'Workouts are now sent to $host:$kPcPokePort.');
}
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final status = Theme.of(context).extension<AppStatusColors>()!;
final paired = _paired;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const _SectionHeader('PC LINK'),
const SizedBox(height: AppSpacing.xs),
Text(
'A finished workout is sent straight to the PC on the home Wi-Fi, '
'so the credit lands in a second. Sync still delivers it otherwise.',
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
const SizedBox(height: AppSpacing.sm),
Row(
children: [
Expanded(
child: TextField(
key: const Key('pc-host'),
controller: _host,
keyboardType: TextInputType.url,
decoration: const InputDecoration(
isDense: true,
labelText: 'PC address',
),
),
),
const SizedBox(width: AppSpacing.sm),
TextButton(
key: const Key('pc-host-save'),
onPressed: () => unawaited(_save()),
// Distinct label: the sandbox section has its own "Save", and
// two identical labels cannot be driven by element.
child: const Text('Save', semanticsLabel: 'Save PC address'),
),
],
),
const SizedBox(height: AppSpacing.sm),
Text(
switch (paired) {
null => 'PC paired: checking…',
true => 'PC paired ✓',
false => 'PC paired ✗ — run scripts/pair_phone.sh on the PC',
},
key: const Key('pc-paired'),
style: TextStyle(
color: paired ?? false ? status.success : status.warning,
fontSize: AppTextSize.caption,
),
),
if (_status != null) ...[
const SizedBox(height: AppSpacing.xs),
Text(
_status!,
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
],
],
);
}
}

View File

@ -69,8 +69,9 @@ class _SandboxSectionState extends State<_SandboxSection> {
const _SectionHeader('SANDBOX'),
const SizedBox(height: 4),
Text(
'This install is the sandbox: its own data, no network, no LAN '
'server. Nothing here can reach the daily build.',
'This install is the sandbox: its own data, no network (only the '
'signed sandbox poke to the PC LINK address, which the PC never '
'credits), no LAN server. Nothing here can reach the daily build.',
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,

View File

@ -34,6 +34,7 @@ class SettingsScreen extends StatefulWidget {
this.storageRequester,
this.progressionPuller,
this.progressionPusher,
this.pcPairingLoader = PcPairing.load,
});
/// Injectable HTTP client, passed through to [GitHubMirrorScreen] so its
@ -89,6 +90,10 @@ class SettingsScreen extends StatefulWidget {
/// Injected so tests never reach Firebase.
final Future<ProgressionSyncResult> Function()? progressionPusher;
/// Loads the PC pairing for the PC LINK section. Injected so tests need
/// neither the keystore nor the pairing channel.
final Future<PcPairingState> Function() pcPairingLoader;
@override
State<SettingsScreen> createState() => _SettingsScreenState();
}

View File

@ -22,6 +22,7 @@ import 'package:workout_app/services/break_service_controller.dart';
import 'package:workout_app/services/foreground_break_client.dart';
import 'package:workout_app/services/foreground_break_client_flutter.dart';
import 'package:workout_app/services/lock_mode.dart';
import 'package:workout_app/services/pc_poke_service.dart';
import 'package:workout_app/services/progression_sync_service.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/sync_service.dart';
@ -197,13 +198,13 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
/// Only the `setState` lives here — `setState` is `@protected` and cannot be
/// called from an extension, so the rest is in [_persistFinishedWorkout].
Future<void> _finishWorkout() async {
SandboxLog.event('workout finish', {'type': widget.workoutType});
_breakTimer?.cancel();
// Before the state flips: the service must not outlive the workout, and
// with stopWithTask="false" nothing else will ever stop it.
await _breaks.stop();
final sinceTap = Stopwatch()..start();
// The service stop starts first and is awaited last (see _beginFinish):
// the summary must not wait on the notification teardown.
final stopped = _beginFinish();
setState(() => _finished = true);
await _persistFinishedWorkout();
await _persistFinishedWorkout(sinceTap);
await stopped;
}
// ── Build ──────────────────────────────────────────────────────────────────

View File

@ -5,11 +5,35 @@ part of 'workout_screen.dart';
/// The write-everything step that runs once a workout is marked finished.
extension _WorkoutScreenFinish on _WorkoutScreenState {
/// Starts tearing down the break service and returns the stop, which the
/// caller awaits only after the summary is up.
///
/// The stop is *started* before `_finished` flips -- the service must not
/// outlive the workout, and with stopWithTask="false" nothing else stops it
/// -- and its synchronous part (dropping the drain-nudge listener) runs
/// right here. Only its completion (~120 ms of platform-channel teardown on
/// the phone, 2026-10-09) no longer gates the summary. If it fails, the
/// failure is logged loudly and the next launch's `stopStaleBreakService`
/// takes the service down, since the active session is cleared by then.
Future<void> _beginFinish() {
SandboxLog.event('workout finish', {'type': widget.workoutType});
_breakTimer?.cancel();
return _breaks.stop().catchError((Object error, StackTrace stack) {
log(
'Break service did not stop at finish ($error); the next launch '
'stops it as stale.',
level: 1000,
error: error,
stackTrace: stack,
);
});
}
/// Writes the finished session, applies progression, and shows the summary.
///
/// Called by [_WorkoutScreenState._finishWorkout], which owns the `setState`
/// that marks the workout finished before this runs.
Future<void> _persistFinishedWorkout() async {
Future<void> _persistFinishedWorkout(Stopwatch sinceTap) async {
final endTime = DateTime.now();
final results = <ExerciseResult>[];
@ -41,6 +65,16 @@ extension _WorkoutScreenFinish on _WorkoutScreenState {
endTime: endTime,
exercises: results,
);
// The direct PC poke starts the moment the session exists, before any
// local write: it needs nothing from storage, and every millisecond here
// is a millisecond of "instant" credit. It runs in parallel with the
// sync push below (never after it); the PC dedups by record id, so
// whichever lands first credits and the other reads as a duplicate.
// Bounded to 2 s and never throws.
final pcPoke = PcPokeService().poke(session);
SandboxLog.event('pc poke started', {
'ms_since_tap': sinceTap.elapsedMilliseconds,
});
final storage = StorageService.instance;
await storage.saveSession(
@ -99,12 +133,24 @@ extension _WorkoutScreenFinish on _WorkoutScreenState {
);
if (!mounted) return;
SandboxLog.event('summary shown', {
'ms_since_tap': sinceTap.elapsedMilliseconds,
});
// The first frame that draws the dialog: "finish tap -> summary visible".
WidgetsBinding.instance.addPostFrameCallback(
(_) => SandboxLog.event('summary first frame', {
'ms_since_tap': sinceTap.elapsedMilliseconds,
}),
);
unawaited(
showDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) =>
WorkoutSummaryDialog(session: session, syncResult: syncResult),
builder: (_) => WorkoutSummaryDialog(
session: session,
syncResult: syncResult,
pcPoke: pcPoke,
),
),
);
}

View File

@ -0,0 +1,131 @@
/// Where the PC is and the key the poke is signed with.
///
/// The key arrives over adb (`scripts/pair_phone.sh` -> `PairPcReceiver`).
/// A manifest receiver runs without a Dart isolate, so it parks the key in a
/// private no-backup file and Dart moves it into secure storage the next
/// time it asks -- at startup, in Settings, and before every poke.
library;
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:workout_app/sandbox/sandbox_http.dart';
import 'package:workout_app/services/pc_poke_wire.dart';
import 'package:workout_app/services/storage_service.dart';
export 'package:workout_app/services/pc_poke_wire.dart' show kPcPokePort;
/// Snapshot of the pairing. [keyHex] never leaves the services layer: the
/// UI only ever reads [paired].
@immutable
class PcPairingState {
/// Creates a snapshot.
const PcPairingState({required this.host, this.keyHex});
/// The PC's LAN host.
final String host;
/// The shared HMAC key, or null when this install is not paired.
final String? keyHex;
/// Whether a key is stored.
bool get paired => keyHex != null;
}
final RegExp _hostPattern = RegExp(r'^[A-Za-z0-9](?:[A-Za-z0-9.-]{0,252})$');
/// Whether [host] is usable as the PC address (an IPv4 or a hostname).
bool isValidPcHost(String host) => _hostPattern.hasMatch(host);
/// Reads and writes the pairing. Each package (daily, sandbox) has its own
/// keystore and database, so each has its own key slot by construction.
abstract final class PcPairing {
/// Channel `MainActivity` answers `takePending` / `clearPending` on.
static const MethodChannel channel = MethodChannel(
'com.kuhy.workout_app/pc_pairing',
);
/// Secure-storage entry the key is kept under.
static const String keyName = 'pc_poke_key';
/// The keystore; tests swap the platform channel, not this.
static const FlutterSecureStorage _secure = FlutterSecureStorage();
static bool _channelDown = false;
/// Absorbs any pending adb pairing, then returns the current pairing and
/// points the sandbox's network exception at its host.
static Future<PcPairingState> load() async {
await absorbPending();
final host = await StorageService.instance.getPcHost() ?? kDefaultPcHost;
String? key;
try {
key = await _secure.read(key: keyName);
} on Exception catch (error) {
log(
'PC pairing key unreadable ($error) -- treating as not paired',
name: 'PcPairing',
level: 900,
);
}
SandboxHttpOverrides.pokeHost = host;
return PcPairingState(
host: host,
keyHex: key != null && isValidPokeKeyHex(key) ? key : null,
);
}
/// Persists the PC address the Settings field holds.
static Future<void> saveHost(String host) async {
await StorageService.instance.setPcHost(host);
SandboxHttpOverrides.pokeHost = host;
}
/// Moves a key the receiver parked into secure storage. Returns what
/// happened as a sentence; the parked copy is deleted only after the
/// secure write succeeded, so a failure here loses nothing.
static Future<String> absorbPending() async {
if (_channelDown) return 'no pairing channel on this platform';
Map<Object?, Object?>? pending;
try {
pending = await channel.invokeMapMethod<Object?, Object?>('takePending');
} on MissingPluginException catch (error) {
_channelDown = true;
log(
'no pairing channel ($error) -- adb pairing is Android-only',
name: 'PcPairing',
level: 900,
);
return 'no pairing channel on this platform';
} on PlatformException catch (error) {
log('reading the parked pairing failed: $error', level: 1000);
return 'reading the parked pairing failed: $error';
}
if (pending == null) return 'nothing pending';
final key = pending['key'];
final host = pending['host'];
if (key is! String || !isValidPokeKeyHex(key)) {
log('parked pairing key is malformed -- discarded', level: 1000);
await channel.invokeMethod<void>('clearPending');
return 'parked pairing key is malformed';
}
try {
await _secure.write(key: keyName, value: key.toLowerCase());
} on PlatformException catch (error) {
log('storing the pairing key failed: $error', level: 1000);
return 'storing the pairing key failed: $error';
}
if (host is String && isValidPcHost(host)) {
await saveHost(host);
}
await channel.invokeMethod<void>('clearPending');
log('PC pairing absorbed from adb', name: 'PcPairing', level: 800);
return 'paired';
}
/// Forgets a failed channel so the next call retries it.
@visibleForTesting
static void resetForTesting() => _channelDown = false;
}

View File

@ -0,0 +1,150 @@
/// The typed outcome of one phone->PC workout poke.
library;
import 'dart:convert';
import 'package:flutter/foundation.dart';
/// What the PC did with the poke, as far as the phone can tell.
enum PokeOutcome {
/// Verified, ingested and credited just now.
credited,
/// Already in the PC's log (the sync got there first): nothing new to do.
duplicate,
/// A sandbox poke: verified and timed, never written or credited.
sandbox,
/// New to the PC, but today's workout slot was already paid (`ok:true,
/// credited:false, duplicate:false`).
alreadyPaidToday,
/// Correctly signed, but the session does not count (too short, no date):
/// HTTP 200 with `ok:false`. [PokeResult.reason] says why.
notCounted,
/// No usable answer: not paired, unreachable, timed out, rejected.
failed,
}
/// One poke's result. Never null, never thrown: [reason] is always a
/// sentence a human can act on.
@immutable
class PokeResult {
/// Creates a result.
const PokeResult({
required this.outcome,
required this.reason,
this.shutdown,
this.gamingBudgetMinutes,
this.roundTripMs,
});
/// A failure that never got a usable reply.
const PokeResult.failed(this.reason, {this.roundTripMs})
: outcome = PokeOutcome.failed,
shutdown = null,
gamingBudgetMinutes = null;
/// Parses the PC's JSON reply. Any shape the contract does not allow is a
/// [PokeOutcome.failed] naming what was wrong, not an exception.
factory PokeResult.fromReply(int status, String body, int roundTripMs) {
Object? decoded;
FormatException? notJson;
try {
decoded = jsonDecode(body);
} on FormatException catch (error) {
// Handed on in the result; PcPokeService logs every failed result.
notJson = error;
}
if (notJson != null) {
return PokeResult.failed(
'PC answered HTTP $status with a non-JSON body ($notJson)',
roundTripMs: roundTripMs,
);
}
if (decoded is! Map<String, dynamic>) {
return PokeResult.failed(
'PC answered HTTP $status with JSON that is not an object',
roundTripMs: roundTripMs,
);
}
final reason = decoded['reason'] is String
? decoded['reason'] as String
: 'PC gave no reason';
// 401/409/400/404/405/411/413/500 all carry JSON, but none of them is
// an answer about this workout: the sync fallback covers them.
if (status != 200) {
return PokeResult.failed(
'PC rejected the poke (HTTP $status): $reason',
roundTripMs: roundTripMs,
);
}
// shutdown / gaming_budget_minutes may be null (refusals): never assumed.
final budget = decoded['gaming_budget_minutes'];
final shutdown = decoded['shutdown'];
final PokeOutcome outcome;
if (decoded['ok'] != true) {
outcome = PokeOutcome.notCounted;
} else if (decoded['sandbox'] == true) {
outcome = PokeOutcome.sandbox;
} else if (decoded['duplicate'] == true) {
outcome = PokeOutcome.duplicate;
} else if (decoded['credited'] == true) {
outcome = PokeOutcome.credited;
} else {
outcome = PokeOutcome.alreadyPaidToday;
}
return PokeResult(
outcome: outcome,
reason: reason,
shutdown: shutdown is String ? shutdown : null,
gamingBudgetMinutes: budget is int ? budget : null,
roundTripMs: roundTripMs,
);
}
/// What happened.
final PokeOutcome outcome;
/// Why, in words.
final String reason;
/// The PC's shutdown time after this poke, `HH:MM`.
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.
final int? roundTripMs;
/// The one line the finish screen shows for this result.
String get label {
switch (outcome) {
case PokeOutcome.credited:
final parts = <String>['PC ✓'];
if (shutdown != null) parts.add('shutdown $shutdown');
final minutes = gamingBudgetMinutes;
final gaming = minutes == null
? ''
: ' · gaming ${(minutes / 60).toStringAsFixed(1)}h';
return '${parts.join(' ')}$gaming';
case PokeOutcome.duplicate:
return 'PC: already credited';
case PokeOutcome.sandbox:
return 'PC ✓ (sandbox, not credited) · ${roundTripMs ?? '?'} ms';
case PokeOutcome.alreadyPaidToday:
return 'PC: already credited today';
case PokeOutcome.notCounted:
return 'PC: not counted — $reason';
case PokeOutcome.failed:
return 'PC: will credit within 60 s (via sync)';
}
}
@override
String toString() =>
'PokeResult(${outcome.name}, rtt=${roundTripMs}ms, reason: $reason)';
}

View File

@ -0,0 +1,142 @@
/// Sends a finished workout straight to the PC so the credit lands in under
/// a second instead of waiting for the sync round trip.
library;
import 'dart:async';
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:http/io_client.dart';
import 'package:uuid/uuid.dart';
import 'package:workout_app/models/workout_session.dart';
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/sandbox/sandbox_log.dart';
import 'package:workout_app/services/pc_pairing.dart';
import 'package:workout_app/services/pc_poke_result.dart';
import 'package:workout_app/services/pc_poke_wire.dart';
import 'package:workout_app/services/workout_sync_service.dart';
export 'package:workout_app/services/pc_poke_result.dart';
/// Signs and POSTs one session to `http://<pc-host>:8773/v1/workout`.
///
/// Runs beside [WorkoutSyncService.push], never instead of it: the PC dedups
/// by record id, so whichever path lands first credits and the other is a
/// duplicate. Off the home LAN this fails fast and the sync is the only path.
class PcPokeService {
/// Creates a service. Every collaborator is injectable so tests need no
/// network, keystore or clock.
PcPokeService({
http.Client Function()? clientFactory,
Future<PcPairingState> Function()? pairingLoader,
DateTime Function()? clock,
String Function()? nonce,
this.sandboxOverride,
this.timeout = const Duration(seconds: 2),
}) : _clientFactory = clientFactory ?? IOClient.new,
_pairingLoader = pairingLoader ?? PcPairing.load,
_clock = clock ?? DateTime.now,
_nonce = nonce ?? const Uuid().v4;
/// A fresh client per call, so it is built under whatever `HttpOverrides`
/// are current (the sandbox's narrow exception included).
final http.Client Function() _clientFactory;
final Future<PcPairingState> Function() _pairingLoader;
final DateTime Function() _clock;
final String Function() _nonce;
/// Forces the body's `sandbox` flag; null follows [Sandbox.enabled].
final bool? sandboxOverride;
/// Budget for the whole poke, key load included. Past it the finish screen
/// says the sync will credit instead.
final Duration timeout;
/// Pokes the PC with [session]. Never throws; failures log at warning.
Future<PokeResult> poke(WorkoutSession session) async {
final watch = Stopwatch()..start();
http.Client? client;
// Set by the catch below and reported (at warning) right after it.
Exception failure;
try {
final pairing = await _pairingLoader().timeout(timeout);
final keyHex = pairing.keyHex;
if (keyHex == null) {
return _report(
const PokeResult.failed(
'this phone is not paired with the PC -- run '
'scripts/pair_phone.sh there; the sync will credit meanwhile',
),
);
}
final sandbox = sandboxOverride ?? Sandbox.enabled;
final body = buildPokeBody(
sentAtMs: _clock().millisecondsSinceEpoch,
nonce: _nonce(),
sandbox: sandbox,
recordId: workoutRecordId(session),
payload: workoutRecordPayload(session),
);
final signature = signPokeBody(decodePokeKeyHex(keyHex), body);
final uri = Uri(
scheme: 'http',
host: pairing.host,
port: kPcPokePort,
path: kPcPokePath,
);
client = _clientFactory();
final left = timeout - watch.elapsed;
final response = await client
.post(
uri,
headers: {
'Content-Type': 'application/json',
kPcPokeSignatureHeader: signature,
},
body: body,
)
.timeout(left.isNegative ? Duration.zero : left);
return _report(
PokeResult.fromReply(
response.statusCode,
response.body,
watch.elapsedMilliseconds,
),
);
} on Exception catch (error) {
failure = error;
} finally {
// Closing aborts a request the timeout gave up on, so a dead PC never
// keeps a socket open behind the finish screen.
client?.close();
}
return _report(
PokeResult.failed(
failure is TimeoutException
? 'no reply from the PC within ${timeout.inMilliseconds} ms'
: 'could not reach the PC: $failure',
roundTripMs: watch.elapsedMilliseconds,
),
);
}
/// Logs every result -- a poke that fails says so at warning level, never
/// silently -- and mirrors it into the sandbox trace.
PokeResult _report(PokeResult result) {
final failed =
result.outcome == PokeOutcome.failed ||
result.outcome == PokeOutcome.notCounted;
final line =
'PC poke ${result.outcome.name} in ${result.roundTripMs ?? '-'} ms: '
'${result.reason}';
log(line, name: 'PcPoke', level: failed ? 900 : 800);
debugPrint('WorkoutApp: $line');
SandboxLog.event('pc poke', {
'outcome': result.outcome.name,
'rtt_ms': result.roundTripMs,
'reason': result.reason,
});
return result;
}
}

View File

@ -0,0 +1,69 @@
/// Wire format of the phone->PC workout poke (v1).
///
/// Binding spec: `docs/DOCS-workout-poke-contract.md` at the screen-locker
/// repo root, with the literal fixture `contracts/workout_poke_v1.json` that
/// both this file and the Python receiver are tested against. Pure Dart, no
/// Flutter: the contract test loads it without a binding.
library;
import 'dart:convert';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';
/// TCP port the PC's poke listener binds (8771 belongs to another service).
const int kPcPokePort = 8773;
/// Request path on the PC.
const String kPcPokePath = '/v1/workout';
/// Header carrying `hex(HMAC-SHA256(key, raw body bytes))`.
const String kPcPokeSignatureHeader = 'X-Poke-Signature';
/// Wire-format version this phone speaks.
const int kPcPokeVersion = 1;
/// The PC's static LAN address; the Settings field starts here.
const String kDefaultPcHost = '192.168.1.43';
final RegExp _keyHex = RegExp(r'^[0-9a-fA-F]{64}$');
/// Whether [text] is a pairing key: exactly 32 bytes as 64 hex characters.
bool isValidPokeKeyHex(String text) => _keyHex.hasMatch(text);
/// Decodes a key accepted by [isValidPokeKeyHex]; throws [FormatException]
/// on anything else so a malformed key can never sign a request.
Uint8List decodePokeKeyHex(String keyHex) {
if (!isValidPokeKeyHex(keyHex)) {
throw const FormatException('pairing key must be exactly 64 hex chars');
}
final out = Uint8List(32);
for (var i = 0; i < 32; i++) {
out[i] = int.parse(keyHex.substring(i * 2, i * 2 + 2), radix: 16);
}
return out;
}
/// `hex(HMAC-SHA256(key, bodyBytes))` over the bytes exactly as sent.
String signPokeBody(List<int> key, List<int> bodyBytes) =>
Hmac(sha256, key).convert(bodyBytes).toString();
/// Serializes the request body ONCE; the caller signs and sends these exact
/// bytes. Key order follows the contract for readability only -- the PC
/// verifies the MAC over the received bytes and never re-serializes.
Uint8List buildPokeBody({
required int sentAtMs,
required String nonce,
required bool sandbox,
required String recordId,
required Map<String, dynamic> payload,
}) => utf8.encode(
jsonEncode({
'v': kPcPokeVersion,
'sent_at_ms': sentAtMs,
'nonce': nonce,
'sandbox': sandbox,
'record_id': recordId,
'payload': payload,
}),
);

View File

@ -26,6 +26,7 @@ export 'package:workout_app/models/progression.dart';
part 'storage_service_backup.dart';
part 'storage_service_deload.dart';
part 'storage_service_exercises.dart';
part 'storage_service_pc_link.dart';
part 'storage_service_sandbox.dart';
part 'storage_service_schema.dart';
part 'storage_service_sessions.dart';

View File

@ -0,0 +1,18 @@
// The PC address the workout poke is sent to.
//
// A `part` of StorageService for the same reason as the sandbox part: it
// needs `_getSetting`, and one setting does not earn a second storage layer.
// The key itself is NOT here -- it lives in secure storage (pc_pairing.dart).
part of 'storage_service.dart';
/// Settings key the PC host is stored under.
const String kPcHostKey = 'pc_host';
/// Persistence for the PC link.
extension StorageServicePcLink on StorageService {
/// The saved PC host, or null when the default should be used.
Future<String?> getPcHost() => _getSetting(kPcHostKey);
/// Persists the PC host.
Future<void> setPcHost(String host) => _setSetting(kPcHostKey, host);
}

View File

@ -1,7 +1,6 @@
/// Pushes completed workout sessions to the shared sync backend.
library;
import 'dart:convert';
import 'dart:developer';
import 'package:crdt_sync/crdt_sync.dart';
@ -27,6 +26,19 @@ Log _decode(String text) => (jsonDecode(text) as Map<String, dynamic>).map(
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
);
/// The sync record id a finished [session] is pushed under.
///
/// The PC's `ingest_session_records` keys on this (it equals the payload's
/// `start_time`), so the direct phone->PC poke and the regular push must
/// both build it here -- two constructions could drift and credit twice.
String workoutRecordId(WorkoutSession session) =>
session.startTime.toIso8601String();
/// The payload a finished [session] carries in its sync record; shared with
/// the poke for the same reason as [workoutRecordId].
Map<String, dynamic> workoutRecordPayload(WorkoutSession session) =>
session.toJson();
/// The outcome of a [WorkoutSyncService.push] / [WorkoutSyncService.pushManual].
///
/// A bare `Future<void>` used to hide every failure: the caller could not
@ -124,9 +136,12 @@ class WorkoutSyncService {
successReason: 'pushed',
failurePrefix: 'push failed',
addition: Record(
id: session.startTime.toIso8601String(),
id: workoutRecordId(session),
fields: {
'payload': (session.toJson(), Hlc.newTick(currentSyncDeviceId)),
'payload': (
workoutRecordPayload(session),
Hlc.newTick(currentSyncDeviceId),
),
},
),
);
@ -172,7 +187,6 @@ class WorkoutSyncService {
);
}
/// Pushes a pre-built manual-workout [record] to this device's log.
///
/// Same never-throw, always-report contract as [push].
@ -197,6 +211,7 @@ class WorkoutSyncService {
/// Returns an empty list if sync isn't configured or the repo is unreachable.
Future<List<Map<String, dynamic>>> readMergedManualPayloads() =>
_readMergedPayloads(kind: kManualWorkoutSyncKind);
/// Every synced workout, whatever kind — manual, StrongLifts or RunnerUp.
///
/// The PC publishes its whole `log.json` (including verified runs),
@ -205,6 +220,7 @@ class WorkoutSyncService {
/// uses [readMergedManualPayloads] instead.
Future<List<Map<String, dynamic>>> readMergedWorkoutPayloads() =>
_readMergedPayloads();
/// Whether this device has ANY sync credentials -- a GitHub token or a
/// Firebase account.
///

View File

@ -0,0 +1,63 @@
/// The one-line PC status on the workout summary.
library;
import 'package:flutter/material.dart';
import 'package:workout_app/services/pc_poke_result.dart';
import 'package:workout_app/ui/theme.dart';
/// Shows "PC: applying…" until [poke] resolves, then its [PokeResult.label].
///
/// The service bounds [poke] to 2 s, so this never spins forever: an
/// unreachable PC turns into the sync fallback line on its own.
class PcPokeLine extends StatelessWidget {
/// Creates the line for an in-flight [poke].
const PcPokeLine({required this.poke, super.key});
/// The poke started when the workout finished.
final Future<PokeResult> poke;
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final status = Theme.of(context).extension<AppStatusColors>()!;
return FutureBuilder<PokeResult>(
future: poke,
builder: (context, snapshot) {
final result = snapshot.data;
if (result == null) {
return Row(
key: const Key('pc-poke-pending'),
children: [
SizedBox.square(
dimension: AppTextSize.caption,
child: CircularProgressIndicator(
strokeWidth: 2,
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(width: AppSpacing.sm),
Text(
'PC: applying…',
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
],
);
}
final color = switch (result.outcome) {
PokeOutcome.credited || PokeOutcome.sandbox => status.success,
PokeOutcome.duplicate ||
PokeOutcome.alreadyPaidToday => colorScheme.onSurfaceVariant,
PokeOutcome.notCounted || PokeOutcome.failed => status.warning,
};
return Text(
result.label,
key: const Key('pc-poke-result'),
style: TextStyle(color: color, fontSize: AppTextSize.caption),
);
},
);
}
}

View File

@ -3,8 +3,10 @@ library;
import 'package:flutter/material.dart';
import 'package:workout_app/models/workout_session.dart';
import 'package:workout_app/services/pc_poke_result.dart';
import 'package:workout_app/services/sync_service.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/pc_poke_line.dart';
/// Dialog that summarises a completed workout and reports the sync status.
class WorkoutSummaryDialog extends StatelessWidget {
@ -12,6 +14,7 @@ class WorkoutSummaryDialog extends StatelessWidget {
const WorkoutSummaryDialog({
required this.session,
required this.syncResult,
this.pcPoke,
super.key,
});
@ -21,6 +24,10 @@ class WorkoutSummaryDialog extends StatelessWidget {
/// Result of writing the session to disk/HTTP server.
final SyncResult syncResult;
/// The direct phone->PC poke started at finish, shown as one status line;
/// null where none was sent.
final Future<PokeResult>? pcPoke;
String _fmt(Duration d) {
final m = d.inMinutes.remainder(60).toString().padLeft(2, '0');
final s = d.inSeconds.remainder(60).toString().padLeft(2, '0');
@ -70,6 +77,10 @@ class WorkoutSummaryDialog extends StatelessWidget {
fontSize: AppTextSize.caption,
),
),
if (pcPoke != null) ...[
const SizedBox(height: AppSpacing.sm),
PcPokeLine(poke: pcPoke!),
],
],
),
actions: [

View File

@ -147,7 +147,7 @@ packages:
source: git
version: "0.11.1"
crypto:
dependency: transitive
dependency: "direct main"
description:
name: crypto
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf

View File

@ -14,6 +14,8 @@ dependencies:
url: https://github.com/kuhyx/utils
ref: crdt_sync_dart-v0.11.1
path: crdt_sync_dart
# HMAC-SHA256 for the signed phone->PC workout poke (pc_poke_wire.dart).
crypto: 3.0.7
flutter:
sdk: flutter
# Keeps the rest-period deadline ticking with the screen off, and owns the

View File

@ -0,0 +1,7 @@
import 'package:workout_app/services/pc_pairing.dart';
/// A settled, unpaired pairing for screens that only need the PC LINK
/// section to render: no pairing channel, keystore or database involved, and
/// `SandboxHttpOverrides.pokeHost` stays untouched.
Future<PcPairingState> fakePcPairing() async =>
const PcPairingState(host: '10.0.0.2');

View File

@ -0,0 +1,50 @@
// The phone half of the cross-language contract check for the workout poke.
//
// `contracts/workout_poke_v1.json` (screen-locker repo root) is a literal key,
// body and signature the Python receiver is tested against too. Each side's
// own round-trip test would pass while the two disagreed; this one cannot.
import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/pc_poke_wire.dart';
/// Relative to the package root, which is `flutter test`'s cwd.
const _fixturePath = '../../contracts/workout_poke_v1.json';
void main() {
final fixture =
jsonDecode(File(_fixturePath).readAsStringSync()) as Map<String, dynamic>;
final keyHex = fixture['key_hex'] as String;
final body = fixture['body_utf8'] as String;
final expected = fixture['signature_hex'] as String;
test('signer reproduces the shared fixture signature byte for byte', () {
expect(signPokeBody(decodePokeKeyHex(keyHex), utf8.encode(body)), expected);
});
test('the fixture key is a valid pairing key', () {
expect(isValidPokeKeyHex(keyHex), isTrue);
});
test('buildPokeBody emits the fixture body byte for byte', () {
// Float (100.0, 7020.5), key order and raw non-ASCII are where encoders
// differ. The PC never re-serializes, so this is not required for the MAC
// to verify -- it pins that the phone's body looks like the documented one.
final reparsed = jsonDecode(body) as Map<String, dynamic>;
final rebuilt = buildPokeBody(
sentAtMs: reparsed['sent_at_ms'] as int,
nonce: reparsed['nonce'] as String,
sandbox: reparsed['sandbox'] as bool,
recordId: reparsed['record_id'] as String,
payload: reparsed['payload'] as Map<String, dynamic>,
);
expect(utf8.decode(rebuilt), body);
});
test('malformed keys are rejected before they can sign', () {
expect(isValidPokeKeyHex('ab' * 31), isFalse);
expect(isValidPokeKeyHex('zz' * 32), isFalse);
expect(() => decodePokeKeyHex('nope'), throwsFormatException);
});
}

View File

@ -3,6 +3,7 @@ import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/sandbox/sandbox_http.dart';
import 'package:workout_app/services/pc_poke_wire.dart';
void main() {
final printed = <String>[];
@ -10,7 +11,10 @@ void main() {
printed.clear();
debugPrint = (String? message, {int? wrapWidth}) => printed.add(message ?? '');
});
tearDown(() => debugPrint = debugPrintThrottled);
tearDown(() {
debugPrint = debugPrintThrottled;
SandboxHttpOverrides.pokeHost = null;
});
test('refuses every connection before a socket is opened', () async {
final client = SandboxHttpOverrides().createHttpClient(null);
@ -23,4 +27,73 @@ void main() {
expect(printed.single, contains('refused network connection to firebase.example.invalid'));
client.close(force: true);
});
group('the one PC-poke exception', () {
const host = '127.0.0.1';
final poke = Uri.parse('http://$host:$kPcPokePort$kPcPokePath');
test('allows nothing until a PC host is configured', () {
expect(SandboxHttpOverrides.allows(poke), isFalse);
});
test('allows exactly http + configured host + 8773 + /v1/workout', () {
SandboxHttpOverrides.pokeHost = host;
expect(SandboxHttpOverrides.allows(poke), isTrue);
for (final other in [
poke.replace(scheme: 'https'),
poke.replace(host: '127.0.0.2'),
poke.replace(port: 443),
poke.replace(path: '/v1/other'),
Uri.parse('https://firebaseio.com/x.json'),
]) {
expect(SandboxHttpOverrides.allows(other), isFalse, reason: '$other');
}
});
test('https to the same host and port is still refused', () async {
SandboxHttpOverrides.pokeHost = host;
final client = SandboxHttpOverrides().createHttpClient(null);
await expectLater(
() async => client.postUrl(
Uri.parse('https://$host:$kPcPokePort$kPcPokePath'),
),
throwsA(isA<SocketException>()),
);
expect(printed.single, contains('refused network connection to $host'));
client.close(force: true);
});
test('another host is still refused', () async {
SandboxHttpOverrides.pokeHost = host;
final client = SandboxHttpOverrides().createHttpClient(null);
await expectLater(
() async => client.postUrl(
Uri.parse('http://10.0.0.9:$kPcPokePort$kPcPokePath'),
),
throwsA(isA<SocketException>()),
);
expect(printed.single, contains('refused network connection to 10.0.0.9'));
client.close(force: true);
});
test('the poke itself reaches the socket layer', () async {
SandboxHttpOverrides.pokeHost = host;
final client = SandboxHttpOverrides().createHttpClient(null);
Object outcome = 'connected';
try {
// Nothing is sent: the request is opened, never written.
final request = await client.postUrl(poke);
request.abort();
} on SocketException catch (error) {
outcome = error;
}
// No listener on this host's 8773 is fine -- what matters is that a
// refusal, if any, did not come from the sandbox.
if (outcome is SocketException) {
expect(outcome.message, isNot(contains('sandbox')));
}
expect(printed.first, contains('allowing the PC poke to $host:8773'));
client.close(force: true);
});
});
}

View File

@ -10,6 +10,7 @@ import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/exercise_settings_sheet.dart';
import '../fake_pc_pairing.dart';
import '../fake_secure_storage.dart';
const _situp = 'Situp exercise settings';
@ -42,6 +43,7 @@ void main() {
MaterialApp(
theme: buildAppTheme(),
home: SettingsScreen(
pcPairingLoader: fakePcPairing,
firebaseFactory: () async => null,
accountLoader: () async => null,
sessionProbe: () async => false,

View File

@ -9,6 +9,7 @@ import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/exercise_settings_sheet.dart';
import '../fake_pc_pairing.dart';
import '../fake_secure_storage.dart';
const _situp = 'Situp exercise settings';
@ -36,6 +37,7 @@ void main() {
MaterialApp(
theme: buildAppTheme(),
home: SettingsScreen(
pcPairingLoader: fakePcPairing,
firebaseFactory: () async => null,
accountLoader: () async => null,
sessionProbe: () async => false,

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