mirror of
https://github.com/kuhyx/wake-alarm.git
synced 2026-11-29 11:43:26 +01:00
Compare commits
10 Commits
v1.0.0-bui
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| fa3d41ef4a | |||
| d23752d369 | |||
| 2c41e41b33 | |||
| 295d93c7e7 | |||
| af503f465f | |||
| 10625bd29f | |||
| 4e946483f5 | |||
| 0059d44571 | |||
| be45e5969a | |||
| 0432a9968f |
8
.github/workflows/pre-commit.yml
vendored
8
.github/workflows/pre-commit.yml
vendored
@ -16,18 +16,12 @@ jobs:
|
|||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
- group: mypy
|
|
||||||
hooks: mypy
|
|
||||||
skip: ""
|
|
||||||
- group: pylint
|
|
||||||
hooks: pylint
|
|
||||||
skip: ""
|
|
||||||
# free-days-interop needs Flutter and the freedays venv; it runs as
|
# free-days-interop needs Flutter and the freedays venv; it runs as
|
||||||
# its own job in python-tests.yml, so skipping it here is not
|
# its own job in python-tests.yml, so skipping it here is not
|
||||||
# fail-open.
|
# fail-open.
|
||||||
- group: rest
|
- group: rest
|
||||||
hooks: ""
|
hooks: ""
|
||||||
skip: mypy,pylint,free-days-interop,dependency-freshness
|
skip: "free-days-interop,dependency-freshness"
|
||||||
name: pre-commit (${{ matrix.group }})
|
name: pre-commit (${{ matrix.group }})
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|||||||
@ -24,8 +24,6 @@ repos:
|
|||||||
- id: check-merge-conflict
|
- id: check-merge-conflict
|
||||||
- id: detect-private-key
|
- id: detect-private-key
|
||||||
- id: debug-statements
|
- id: debug-statements
|
||||||
- id: name-tests-test
|
|
||||||
args: [--pytest-test-first]
|
|
||||||
- id: check-ast
|
- id: check-ast
|
||||||
- id: mixed-line-ending
|
- id: mixed-line-ending
|
||||||
args: [--fix=lf]
|
args: [--fix=lf]
|
||||||
@ -59,77 +57,9 @@ repos:
|
|||||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||||
rev: v0.15.2
|
rev: v0.15.2
|
||||||
hooks:
|
hooks:
|
||||||
- id: ruff
|
|
||||||
args: [--fix, --unsafe-fixes, --exit-non-zero-on-fix, --show-fixes]
|
|
||||||
types_or: [python, pyi]
|
|
||||||
- id: ruff-format
|
- id: ruff-format
|
||||||
types_or: [python, pyi]
|
types_or: [python, pyi]
|
||||||
|
|
||||||
- repo: https://github.com/pre-commit/mirrors-mypy
|
|
||||||
rev: v1.13.0
|
|
||||||
hooks:
|
|
||||||
- id: mypy
|
|
||||||
args:
|
|
||||||
- --ignore-missing-imports
|
|
||||||
- --no-error-summary
|
|
||||||
- --disable-error-code=no-untyped-def
|
|
||||||
- --disable-error-code=no-untyped-call
|
|
||||||
- --disable-error-code=var-annotated
|
|
||||||
- --disable-error-code=no-any-unimported
|
|
||||||
- --disable-error-code=type-arg
|
|
||||||
- --disable-error-code=no-any-return
|
|
||||||
- --disable-error-code=misc
|
|
||||||
- --disable-error-code=unused-ignore
|
|
||||||
- --disable-error-code=unreachable
|
|
||||||
- --disable-error-code=assignment
|
|
||||||
- --disable-error-code=no-redef
|
|
||||||
- --disable-error-code=attr-defined
|
|
||||||
- --disable-error-code=arg-type
|
|
||||||
- --disable-error-code=union-attr
|
|
||||||
- --disable-error-code=call-overload
|
|
||||||
- --disable-error-code=return-value
|
|
||||||
- --disable-error-code=redundant-cast
|
|
||||||
- --disable-error-code=empty-body
|
|
||||||
- --disable-error-code=list-item
|
|
||||||
|
|
||||||
- repo: https://github.com/pylint-dev/pylint
|
|
||||||
rev: v3.3.2
|
|
||||||
hooks:
|
|
||||||
- id: pylint
|
|
||||||
# dill (pylint --jobs) crashes on 3.15 (co_lnotab gone); 3.14 until it catches up.
|
|
||||||
language_version: python3.14
|
|
||||||
args:
|
|
||||||
- --rcfile=pyproject.toml
|
|
||||||
- --fail-under=10
|
|
||||||
- --jobs=4
|
|
||||||
additional_dependencies:
|
|
||||||
- pytest
|
|
||||||
# Kept in step with pyproject.toml: pip refuses two different
|
|
||||||
# direct URLs for one distribution, so any pin that drifts from
|
|
||||||
# the manifest becomes an unresolvable hook environment rather
|
|
||||||
# than merely an old one.
|
|
||||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock
|
|
||||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
|
|
||||||
- kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
|
|
||||||
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
|
|
||||||
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays
|
|
||||||
# Test suites intentionally use patterns (protected-access, magic-value
|
|
||||||
# comparisons) that don't belong in the source-code 10/10 gate.
|
|
||||||
exclude: ^(\.venv/)|(^|/)(tests/|conftest\.py)
|
|
||||||
|
|
||||||
- repo: https://github.com/PyCQA/bandit
|
|
||||||
rev: 1.7.10
|
|
||||||
hooks:
|
|
||||||
- id: bandit
|
|
||||||
args:
|
|
||||||
- -c
|
|
||||||
- pyproject.toml
|
|
||||||
- --severity-level=high
|
|
||||||
- --confidence-level=medium
|
|
||||||
- --skip=B113
|
|
||||||
additional_dependencies: ["bandit[toml]"]
|
|
||||||
exclude: ^(tests/|.*test.*\.py$)
|
|
||||||
|
|
||||||
- repo: local
|
- repo: local
|
||||||
hooks:
|
hooks:
|
||||||
- id: ci-mirror
|
- id: ci-mirror
|
||||||
@ -141,13 +71,6 @@ repos:
|
|||||||
require_serial: true
|
require_serial: true
|
||||||
stages: [manual]
|
stages: [manual]
|
||||||
|
|
||||||
- repo: https://github.com/codespell-project/codespell
|
|
||||||
rev: v2.3.0
|
|
||||||
hooks:
|
|
||||||
- id: codespell
|
|
||||||
args:
|
|
||||||
- --skip=*.json,*.lock,.git,__pycache__,.venv
|
|
||||||
|
|
||||||
- repo: local
|
- repo: local
|
||||||
hooks:
|
hooks:
|
||||||
# Fails a commit that still points crdt_sync at a local path. Local
|
# Fails a commit that still points crdt_sync at a local path. Local
|
||||||
@ -167,18 +90,6 @@ repos:
|
|||||||
language: system
|
language: system
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
files: (phone_app/lib/services/free_day_pool\.dart|phone_app/test/free_day_interop_writer_test\.dart|scripts/free_days_interop/.*)$
|
files: (phone_app/lib/services/free_day_pool\.dart|phone_app/test/free_day_interop_writer_test\.dart|scripts/free_days_interop/.*)$
|
||||||
- id: shellcheck
|
|
||||||
name: shellcheck
|
|
||||||
entry: bash -c 'printf "%s\0" "$@" | xargs -0 -n 40 shellcheck --severity=warning' --
|
|
||||||
language: system
|
|
||||||
types: [shell]
|
|
||||||
# The shared 250-line cap. This repo used to run a local script with a
|
|
||||||
# higher limit under this same hook id, so it looked gated while letting
|
|
||||||
# through files every other repo rejects.
|
|
||||||
- id: file-length
|
|
||||||
name: file length <= 250 lines
|
|
||||||
entry: scripts/check_file_length.sh
|
|
||||||
language: system
|
|
||||||
|
|
||||||
# Four markdown namespaces (README / CLAUDE* / DOCS* / TODO*), plus the
|
# Four markdown namespaces (README / CLAUDE* / DOCS* / TODO*), plus the
|
||||||
# rule that a TODO carries "REMOVE ME AFTER FINISH" and nothing else may.
|
# rule that a TODO carries "REMOVE ME AFTER FINISH" and nothing else may.
|
||||||
|
|||||||
@ -217,9 +217,9 @@ self-wake's `rtcwake` and the root ring unit's `systemctl` lines live there.
|
|||||||
- run: n/a: no single entry point; systemd timers (`install.sh`) drive it, inspect with `python -m wake_alarm._sync --show`, `python -m wake_alarm._session --show`, `python -m wake_alarm._trigger --dry-run`
|
- run: n/a: no single entry point; systemd timers (`install.sh`) drive it, inspect with `python -m wake_alarm._sync --show`, `python -m wake_alarm._session --show`, `python -m wake_alarm._trigger --dry-run`
|
||||||
- test: `python -m pytest -q wake_alarm/tests/ && cd phone_app && flutter test --reporter=compact`
|
- test: `python -m pytest -q wake_alarm/tests/ && cd phone_app && flutter test --reporter=compact`
|
||||||
- test-changed: `scripts/test_changed.sh`
|
- test-changed: `scripts/test_changed.sh`
|
||||||
- lint: `pre-commit run ruff --all-files && cd phone_app && flutter analyze --fatal-infos --fatal-warnings`
|
- lint: n/a: dropped (kuhy, 2026-11-27)
|
||||||
- coverage: `python -m pytest -q wake_alarm/tests/ --cov=wake_alarm --cov-branch --cov-report=xml --cov-fail-under=100`
|
- coverage: n/a: dropped (kuhy, 2026-11-27)
|
||||||
- coverage-gaps: `coverage-gaps coverage.xml`
|
- coverage-gaps: n/a: dropped (kuhy, 2026-11-27)
|
||||||
- deploy: `git -C ~/src/wake-alarm pull --ff-only && ~/src/wake-alarm/scripts/deploy.sh` (editable install under /usr/bin/python3 + timers and `_trigger --dry-run` health check, then the release APK onto the Pixel via phone_deploy, health = installed base.apk equals the built one; `--build-only` for board sessions, `--check` for the health check alone; unit or root-file changes still need `bash install.sh`)
|
- deploy: `git -C ~/src/wake-alarm pull --ff-only && ~/src/wake-alarm/scripts/deploy.sh` (editable install under /usr/bin/python3 + timers and `_trigger --dry-run` health check, then the release APK onto the Pixel via phone_deploy, health = installed base.apk equals the built one; `--build-only` for board sessions, `--check` for the health check alone; unit or root-file changes still need `bash install.sh`)
|
||||||
|
|
||||||
Other: full lint gate `pre-commit run --all-files`; live log
|
Other: full lint gate `pre-commit run --all-files`; live log
|
||||||
|
|||||||
@ -50,6 +50,7 @@ live. Causes (`bypass` phone event, `data.cause`):
|
|||||||
| `notifications_off` | ring start and every launch (`Bypass.checkOnLaunch`) |
|
| `notifications_off` | ring start and every launch (`Bypass.checkOnLaunch`) |
|
||||||
| `fsi_revoked` | the same; uid app-op `USE_FULL_SCREEN_INTENT` denied |
|
| `fsi_revoked` | the same; uid app-op `USE_FULL_SCREEN_INTENT` denied |
|
||||||
| `ring_killed` | every launch and boot: today's ring fired, was never dismissed, and is not sounding |
|
| `ring_killed` | every launch and boot: today's ring fired, was never dismissed, and is not sounding |
|
||||||
|
| `uninstalled` | focus-owner, every pass, any day: `com.kuhy.wake_alarm_sync` not installed for user 0 (see below) |
|
||||||
|
|
||||||
`ring_killed` reads `watched_fired_date`, a stamp only builds with `Bypass`
|
`ring_killed` reads `watched_fired_date`, a stamp only builds with `Bypass`
|
||||||
write, so a ring fired by an older build (11-22, paused, never dismissed) does
|
write, so a ring fired by an older build (11-22, paused, never dismissed) does
|
||||||
@ -88,6 +89,44 @@ a minute is recorded once (both activities run the launch check).
|
|||||||
--published <file>` reads the phone's logs from a JSON list of
|
--published <file>` reads the phone's logs from a JSON list of
|
||||||
`[device_id, alarm.json]` pairs instead of Firebase (`_published_file`).
|
`[device_id, alarm.json]` pairs instead of Firebase (`_published_file`).
|
||||||
|
|
||||||
|
## An uninstall that gets through (focus-owner, 2026-11-23)
|
||||||
|
|
||||||
|
WakeAlarm cannot be uninstalled: focus-owner holds `setUninstallBlocked`
|
||||||
|
and `setUserControlDisabledPackages` on it every pass. The Pixel's
|
||||||
|
`dumpsys device_policy` shows `packageUninstallBlocked` for it (2026-11-23).
|
||||||
|
On the AVD, `adb uninstall`, `pm uninstall --user 0` and `-k --user 0` all
|
||||||
|
fail with `DELETE_FAILED_INTERNAL_ERROR` ("Attempted to delete protected
|
||||||
|
package"): the user-control pin refuses it before the uninstall block is
|
||||||
|
asked. Deploys use `adb install -r`, which both allow.
|
||||||
|
|
||||||
|
If WakeAlarm is gone anyway, WakeAlarm cannot record a bypass, so
|
||||||
|
focus-owner does (`phone-focus-mode` `focus-owner/.../UninstallLockdown.kt`,
|
||||||
|
`UninstallEvents.kt`, `lib/sync/`):
|
||||||
|
|
||||||
|
- **Missing** means not found, or found with `FLAG_INSTALLED` clear. A
|
||||||
|
hidden app is installed.
|
||||||
|
- **Lockdown**, every day including free and sick days: the lockdown
|
||||||
|
allowlist while the app is missing and through the day after it returns.
|
||||||
|
Its own prefs, so wake_alarm's `LIFT_LOCKDOWN` does not clear it (a
|
||||||
|
reinstalled WakeAlarm would send one at once). No day cap.
|
||||||
|
- **Event**: `bypass` with `cause: uninstalled` and the phone-local `date`,
|
||||||
|
under device `focus-owner`, record `alarm`, field `phone_events`. One at
|
||||||
|
once when the app goes missing (it rings the PC only inside a tick
|
||||||
|
window), then one per later day at the first pass at or after the alarm
|
||||||
|
time focus-owner read from the sync (08:00 if none). The PC rings every
|
||||||
|
morning until a full dismiss logs `dismissed`; on a free or sick day it
|
||||||
|
stays silent while the phone stays locked.
|
||||||
|
- **Queue**: the lockdown never waits on the push. An unsent event is
|
||||||
|
retried every pass, a failure is logged once a day, nothing is dropped.
|
||||||
|
- **Push-only**: focus-owner writes its own file and never merges a peer's
|
||||||
|
log into it (a pulled list would replace its events, field by field).
|
||||||
|
Its `phone_events` HLC is the newest event's own `at`, so a late retry
|
||||||
|
never out-ranks a list the reinstalled phone published.
|
||||||
|
- `newest_push` skips device `focus-owner`: its write is not the phone's.
|
||||||
|
- Set up once per install: Google sign-in plus the passphrase (the cloud
|
||||||
|
and lock icons in focus-owner's app bar). Each success pushes a harmless
|
||||||
|
`install_check` field that no PC policy reads.
|
||||||
|
|
||||||
## Testing against a backend: the RTDB emulator
|
## Testing against a backend: the RTDB emulator
|
||||||
|
|
||||||
The AVD never signs in to prod. A probe build with
|
The AVD never signs in to prod. A probe build with
|
||||||
@ -110,6 +149,37 @@ debug manifest only). Release builds never set the define.
|
|||||||
http://127.0.0.1:9000 out.json`, then `_fallback --dry-run --at <instant>
|
http://127.0.0.1:9000 out.json`, then `_fallback --dry-run --at <instant>
|
||||||
--published out.json`.
|
--published out.json`.
|
||||||
|
|
||||||
|
Traps on the shared AVD:
|
||||||
|
|
||||||
|
- It can boot `RUNNING_LOCKED` with PIN 1234, and then `/sdcard` is missing.
|
||||||
|
Unlock it before you write the passphrase.
|
||||||
|
- `dpm remove-active-admin` refuses the admin ("non-test admin"). Use
|
||||||
|
Settings → Device admin apps → WakeAlarm → Deactivate.
|
||||||
|
- An active admin makes `cmd package suspend` fail, so suspend first, then
|
||||||
|
activate the admin.
|
||||||
|
- The probe's `ringNow` does not mark the ring as fired, so `Bypass.record`
|
||||||
|
logs "no ring or session live". Set the AVD clock (`adb root`,
|
||||||
|
`settings put global auto_time 0`, `date`) to just before the armed
|
||||||
|
`AlarmReceiver` time and let the alarm fire. Afterwards set `auto_time`
|
||||||
|
back to 1.
|
||||||
|
|
||||||
|
### Live check 2026-11-22: bypass events on the RTDB emulator
|
||||||
|
|
||||||
|
C5 and C6 were checked on emulator-5556 with the `main_session_probe.dart`
|
||||||
|
build (`WAKE_SYNC_EMULATOR`), with the clock moved to Mon 2026-11-23 07:56
|
||||||
|
so the 07:57 alarm rang through `AlarmReceiver`. With the alarm still
|
||||||
|
ringing: `cmd package suspend` at 07:57:34 logged `bypass: suspended`,
|
||||||
|
and deactivating the admin in Settings at 07:58:04 logged
|
||||||
|
`bypass: admin_removed`. Each one logged "signalling focus-owner lockdown
|
||||||
|
through 2026-11-24". `emu_published.py` then read both from the RTDB emulator:
|
||||||
|
`{"kind":"bypass","data":{"cause":"suspended","date":"2026-11-23"}}` and
|
||||||
|
`{"kind":"bypass","data":{"cause":"admin_removed","date":"2026-11-23"}}`
|
||||||
|
(a `notifications_off` bypass from 07:57:11 was also there, because the AVD
|
||||||
|
has the app's notifications off). Then
|
||||||
|
`_fallback --dry-run --at 2026-11-23T08:03 --published out.json` answered
|
||||||
|
`WOULD RING: bypass` (`bypass_at=07:58:04`). focus-owner is not on that AVD:
|
||||||
|
its unsuspend and its applied lockdown are the earlier C6 check at 83e1e15.
|
||||||
|
|
||||||
## The 21:00 notifications check
|
## The 21:00 notifications check
|
||||||
|
|
||||||
Android lets nothing lock "All WakeAlarm notifications", and with them off
|
Android lets nothing lock "All WakeAlarm notifications", and with them off
|
||||||
@ -160,7 +230,11 @@ silence to each monitor with IEC958 muted (restored afterwards) and logs one
|
|||||||
`ring_probe` line per monitor. `_ring_probe.maybe_probe` starts
|
`ring_probe` line per monitor. `_ring_probe.maybe_probe` starts
|
||||||
`wake-alarm-ring-probe.service` once, at `A − 5` on the first morning with no
|
`wake-alarm-ring-probe.service` once, at `A − 5` on the first morning with no
|
||||||
graphical session (the state a fallback ring meets), and writes
|
graphical session (the state a fallback ring meets), and writes
|
||||||
`ring_probe_done`. Read it with `journalctl -u wake-alarm-ring-probe`.
|
`ring_probe_done`. "No graphical session" means greeter only: lightdm is
|
||||||
|
masked only before 05:00, when no ring can happen. A morning kuhy is already
|
||||||
|
logged in at `A − 5` logs one `ring_probe: waiting_for_no_session` event a
|
||||||
|
day instead. Read it with `journalctl -u wake-alarm-ring-probe` and
|
||||||
|
`grep ring_probe ~/.local/state/wake_alarm/events.jsonl`.
|
||||||
vmbox gate: `ring-alsa-monitor-sinks`, `ring-alsa-monitor-probe`
|
vmbox gate: `ring-alsa-monitor-sinks`, `ring-alsa-monitor-probe`
|
||||||
(`scripts/vmbox/guest_cases_monitors.sh`).
|
(`scripts/vmbox/guest_cases_monitors.sh`).
|
||||||
|
|
||||||
|
|||||||
@ -54,10 +54,13 @@ went quiet after 07:43 on 11-01 is a separate phone question.
|
|||||||
|
|
||||||
**Sound.** 100 %, unmuted, a tone that rises over the first 60 s.
|
**Sound.** 100 %, unmuted, a tone that rises over the first 60 s.
|
||||||
- Active graphical session on seat0 → user PipeWire (`wpctl` + `pw-play`).
|
- Active graphical session on seat0 → user PipeWire (`wpctl` + `pw-play`).
|
||||||
- Otherwise (night lockdown: lightdm masked, nobody logged in; kuhy is not in
|
- Otherwise (kuhy is not in `audio`) → root system unit `wake-alarm-ring-alsa.service` playing straight
|
||||||
`audio`) → root system unit `wake-alarm-ring-alsa.service` playing straight
|
|
||||||
to the speakers' card (`ALC897 Analog`, card name `Generic_1`) via `aplay`.
|
to the speakers' card (`ALC897 Analog`, card name `Generic_1`) via `aplay`.
|
||||||
- Both paths also ring every connected monitor (2026-11-22, `DOCS-bypass.md`).
|
- Both paths also ring every connected monitor (2026-11-22, `DOCS-bypass.md`).
|
||||||
|
- A morning ring meets the "otherwise" state: the night lockdown masks
|
||||||
|
lightdm 23:00-05:00 only, and from 05:00 seat0 holds lightdm's greeter
|
||||||
|
(an X server, but no kuhy session) until kuhy logs in. 2026-11-22: greeter
|
||||||
|
at 05:00, ALSA ring 07:51, kuhy's session 10:09.
|
||||||
|
|
||||||
### PC wakes itself (nights before Tue/Wed/Thu)
|
### PC wakes itself (nights before Tue/Wed/Thu)
|
||||||
|
|
||||||
|
|||||||
@ -176,9 +176,12 @@ class _FreeDaysScreenState extends State<FreeDaysScreen> {
|
|||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
// title removed
|
// title removed
|
||||||
actions: [
|
actions: [
|
||||||
IconButton(
|
Tooltip(
|
||||||
icon: const Icon(Icons.sync, semanticLabel: 'Sync now'),
|
message: 'Sync',
|
||||||
onPressed: _busy ? null : () => unawaited(_sync()),
|
child: IconButton(
|
||||||
|
icon: const Icon(Icons.sync, semanticLabel: 'Sync now'),
|
||||||
|
onPressed: _busy ? null : () => unawaited(_sync()),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|||||||
@ -94,33 +94,42 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
|
|||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
Icon(
|
Tooltip(
|
||||||
isConnected ? Icons.link : Icons.link_off,
|
message: isConnected ? 'Connected' : 'Disconnected',
|
||||||
color: isConnected
|
child: Icon(
|
||||||
? Theme.of(context).colorScheme.tertiary
|
isConnected ? Icons.link : Icons.link_off,
|
||||||
: Theme.of(context).colorScheme.onSurfaceVariant,
|
color: isConnected
|
||||||
size: 32,
|
? Theme.of(context).colorScheme.tertiary
|
||||||
semanticLabel: isConnected
|
: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
? 'Connected to GitHub.'
|
size: 32,
|
||||||
: 'Not connected to GitHub.',
|
semanticLabel: isConnected
|
||||||
|
? 'Connected to GitHub.'
|
||||||
|
: 'Not connected to GitHub.',
|
||||||
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
if (!isConnected)
|
if (!isConnected)
|
||||||
ElevatedButton(
|
Tooltip(
|
||||||
key: const ValueKey<String>('github-connect'),
|
message: 'Connect',
|
||||||
onPressed: _busy ? null : _connectGitHub,
|
child: ElevatedButton(
|
||||||
child: const Icon(
|
key: const ValueKey<String>('github-connect'),
|
||||||
Icons.link,
|
onPressed: _busy ? null : _connectGitHub,
|
||||||
semanticLabel: 'Connect GitHub',
|
child: const Icon(
|
||||||
|
Icons.link,
|
||||||
|
semanticLabel: 'Connect GitHub',
|
||||||
|
),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
else
|
else
|
||||||
OutlinedButton(
|
Tooltip(
|
||||||
key: const ValueKey<String>('github-disconnect'),
|
message: 'Disconnect',
|
||||||
onPressed: _busy ? null : _disconnect,
|
child: OutlinedButton(
|
||||||
child: const Icon(
|
key: const ValueKey<String>('github-disconnect'),
|
||||||
Icons.link_off,
|
onPressed: _busy ? null : _disconnect,
|
||||||
semanticLabel: 'Disconnect GitHub',
|
child: const Icon(
|
||||||
|
Icons.link_off,
|
||||||
|
semanticLabel: 'Disconnect GitHub',
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
|
|||||||
@ -55,8 +55,10 @@ class HomeBody extends StatelessWidget {
|
|||||||
final VoidCallback? onEscaped;
|
final VoidCallback? onEscaped;
|
||||||
|
|
||||||
IconData? _statusIcon(String status) {
|
IconData? _statusIcon(String status) {
|
||||||
if (status.startsWith('Connect a sync backend')) return Icons.cloud_off;
|
if (status.contains('Connect a sync backend')) return Icons.cloud_off;
|
||||||
if (status.startsWith('Sync store unavailable')) return Icons.sync_problem;
|
if (status.contains('Sync store unavailable')) return Icons.sync_problem;
|
||||||
|
// Saved and armed offline; the push rides the next sync.
|
||||||
|
if (status.contains('Saved locally')) return Icons.cloud_upload;
|
||||||
if (status.contains('✓')) return Icons.cloud_done;
|
if (status.contains('✓')) return Icons.cloud_done;
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -77,11 +79,14 @@ class HomeBody extends StatelessWidget {
|
|||||||
child: Column(
|
child: Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
Icon(
|
Tooltip(
|
||||||
Icons.alarm_on,
|
message: 'Armed',
|
||||||
size: 32,
|
child: Icon(
|
||||||
color: theme.colorScheme.primary,
|
Icons.alarm_on,
|
||||||
semanticLabel: 'Alarm is armed for',
|
size: 32,
|
||||||
|
color: theme.colorScheme.primary,
|
||||||
|
semanticLabel: 'Alarm is armed for',
|
||||||
|
),
|
||||||
),
|
),
|
||||||
HomePresenceLine(key: ValueKey<int>(syncEpoch)),
|
HomePresenceLine(key: ValueKey<int>(syncEpoch)),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
@ -96,22 +101,28 @@ class HomeBody extends StatelessWidget {
|
|||||||
Row(
|
Row(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
Icon(
|
Tooltip(
|
||||||
Icons.restore,
|
message: 'Oneshot',
|
||||||
size: 18,
|
child: Icon(
|
||||||
semanticLabel:
|
Icons.restore,
|
||||||
'One-shot early start, back to $baseline '
|
size: 18,
|
||||||
'after it rings',
|
semanticLabel:
|
||||||
|
'One-shot early start, back to $baseline '
|
||||||
|
'after it rings',
|
||||||
|
),
|
||||||
),
|
),
|
||||||
Text(baseline),
|
Text(baseline),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
else
|
else
|
||||||
Icon(
|
Tooltip(
|
||||||
Icons.all_inclusive,
|
message: 'Daily',
|
||||||
size: 18,
|
child: Icon(
|
||||||
color: theme.colorScheme.onSurfaceVariant,
|
Icons.all_inclusive,
|
||||||
semanticLabel: 'Every day. It cannot be turned off.',
|
size: 18,
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
semanticLabel: 'Every day. It cannot be turned off.',
|
||||||
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 32),
|
const SizedBox(height: 32),
|
||||||
SizedBox(
|
SizedBox(
|
||||||
@ -139,11 +150,14 @@ class HomeBody extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
if (!configured) ...[
|
if (!configured) ...[
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Icon(
|
Tooltip(
|
||||||
Icons.cloud_off,
|
message: 'Offline',
|
||||||
size: 28,
|
child: Icon(
|
||||||
color: theme.extension<AppStatusColors>()!.warning,
|
Icons.cloud_off,
|
||||||
semanticLabel: 'Open Settings to connect Firebase',
|
size: 28,
|
||||||
|
color: theme.extension<AppStatusColors>()!.warning,
|
||||||
|
semanticLabel: 'Open Settings to connect Firebase',
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
|
|||||||
@ -183,6 +183,7 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
semanticLabel: 'Free days',
|
semanticLabel: 'Free days',
|
||||||
),
|
),
|
||||||
|
tooltip: 'Free-days',
|
||||||
onPressed: () => Navigator.push<void>(
|
onPressed: () => Navigator.push<void>(
|
||||||
context,
|
context,
|
||||||
appRoute<void>(context, (_) => const FreeDaysScreen()),
|
appRoute<void>(context, (_) => const FreeDaysScreen()),
|
||||||
@ -194,6 +195,7 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
semanticLabel: 'Sick days',
|
semanticLabel: 'Sick days',
|
||||||
),
|
),
|
||||||
|
tooltip: 'Sick-days',
|
||||||
onPressed: () => Navigator.push<void>(
|
onPressed: () => Navigator.push<void>(
|
||||||
context,
|
context,
|
||||||
appRoute<void>(context, (_) => const SickDaysScreen()),
|
appRoute<void>(context, (_) => const SickDaysScreen()),
|
||||||
|
|||||||
@ -62,13 +62,19 @@ class _RingStakesLineState extends State<RingStakesLine> {
|
|||||||
child: Row(
|
child: Row(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
Icon(Icons.gavel_outlined, color: warningColor),
|
Tooltip(
|
||||||
|
message: 'Deadline',
|
||||||
|
child: Icon(Icons.gavel_outlined, color: warningColor),
|
||||||
|
),
|
||||||
const SizedBox(width: 4),
|
const SizedBox(width: 4),
|
||||||
Text(hhmm(stakes.by), style: TextStyle(color: warningColor)),
|
Text(hhmm(stakes.by), style: TextStyle(color: warningColor)),
|
||||||
const SizedBox(width: 4),
|
const SizedBox(width: 4),
|
||||||
const Icon(Icons.arrow_forward, size: 16),
|
const Icon(Icons.arrow_forward, size: 16),
|
||||||
const SizedBox(width: 4),
|
const SizedBox(width: 4),
|
||||||
Icon(Icons.lock_outline, color: warningColor),
|
Tooltip(
|
||||||
|
message: 'Lock',
|
||||||
|
child: Icon(Icons.lock_outline, color: warningColor),
|
||||||
|
),
|
||||||
const SizedBox(width: 4),
|
const SizedBox(width: 4),
|
||||||
Text(
|
Text(
|
||||||
_formatLockDate(stakes.lockThrough),
|
_formatLockDate(stakes.lockThrough),
|
||||||
|
|||||||
@ -93,20 +93,26 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
locked: locked,
|
locked: locked,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
IconButton(
|
Tooltip(
|
||||||
key: const Key('settings-export'),
|
message: 'Export',
|
||||||
icon: const Icon(Icons.upload_file, semanticLabel: 'Export data'),
|
child: IconButton(
|
||||||
onPressed: () => _run(context, () async {
|
key: const Key('settings-export'),
|
||||||
await (onExport ?? () => saveExport(alarm: alarmService))();
|
icon: const Icon(Icons.upload_file, semanticLabel: 'Export data'),
|
||||||
return true;
|
onPressed: () => _run(context, () async {
|
||||||
}),
|
await (onExport ?? () => saveExport(alarm: alarmService))();
|
||||||
|
return true;
|
||||||
|
}),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
IconButton(
|
Tooltip(
|
||||||
key: const Key('settings-import'),
|
message: 'Import',
|
||||||
icon: const Icon(Icons.download, semanticLabel: 'Import data'),
|
child: IconButton(
|
||||||
onPressed: () => _run(
|
key: const Key('settings-import'),
|
||||||
context,
|
icon: const Icon(Icons.download, semanticLabel: 'Import data'),
|
||||||
onImport ?? () => pickAndImport(alarm: alarmService),
|
onPressed: () => _run(
|
||||||
|
context,
|
||||||
|
onImport ?? () => pickAndImport(alarm: alarmService),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
|||||||
@ -32,7 +32,10 @@ class StakesMarks extends StatelessWidget {
|
|||||||
};
|
};
|
||||||
final rows = <Widget>[
|
final rows = <Widget>[
|
||||||
_row('title', view.title, <Widget>[
|
_row('title', view.title, <Widget>[
|
||||||
Icon(kindIcon, color: theme.colorScheme.primary),
|
Tooltip(
|
||||||
|
message: 'Stakes',
|
||||||
|
child: Icon(kindIcon, color: theme.colorScheme.primary),
|
||||||
|
),
|
||||||
Icon(view.isToday ? Icons.today : Icons.event, size: 18),
|
Icon(view.isToday ? Icons.today : Icons.event, size: 18),
|
||||||
Text(_dm(view.day), style: theme.textTheme.titleMedium),
|
Text(_dm(view.day), style: theme.textTheme.titleMedium),
|
||||||
]),
|
]),
|
||||||
@ -46,34 +49,39 @@ class StakesMarks extends StatelessWidget {
|
|||||||
if (dismissBy != null && lock != null) {
|
if (dismissBy != null && lock != null) {
|
||||||
rows.add(
|
rows.add(
|
||||||
_row('stick', words.first, <Widget>[
|
_row('stick', words.first, <Widget>[
|
||||||
const Icon(Icons.alarm),
|
const Tooltip(message: 'Alarm', child: Icon(Icons.alarm)),
|
||||||
Text(hhmm(dismissBy)),
|
Text(hhmm(dismissBy)),
|
||||||
const Icon(Icons.arrow_forward, size: 16),
|
const Icon(Icons.arrow_forward, size: 16),
|
||||||
const Icon(Icons.lock_outline),
|
const Tooltip(message: 'Lock', child: Icon(Icons.lock_outline)),
|
||||||
Text(_dm(lock)),
|
Text(_dm(lock)),
|
||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
} else if (finishBy != null && open != null) {
|
} else if (finishBy != null && open != null) {
|
||||||
rows.add(
|
rows.add(
|
||||||
_row('carrot', words.first, <Widget>[
|
_row('carrot', words.first, <Widget>[
|
||||||
const Icon(Icons.flag_outlined),
|
const Tooltip(message: 'Finish', child: Icon(Icons.flag_outlined)),
|
||||||
Text(hhmm(finishBy)),
|
Text(hhmm(finishBy)),
|
||||||
const Icon(Icons.arrow_forward, size: 16),
|
const Icon(Icons.arrow_forward, size: 16),
|
||||||
const Icon(Icons.computer),
|
const Tooltip(message: 'PC', child: Icon(Icons.computer)),
|
||||||
Text(_hm(open.hour, open.minute)),
|
Text(_hm(open.hour, open.minute)),
|
||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
} else if (view.kind != StakesDayKind.free &&
|
} else if (view.kind != StakesDayKind.free &&
|
||||||
view.kind != StakesDayKind.sick) {
|
view.kind != StakesDayKind.sick) {
|
||||||
rows.add(
|
rows.add(
|
||||||
_row('unarmed', words.first, const <Widget>[Icon(Icons.alarm_off)]),
|
_row('unarmed', words.first, const <Widget>[
|
||||||
|
Tooltip(message: 'Off', child: Icon(Icons.alarm_off)),
|
||||||
|
]),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (ring != null) {
|
if (ring != null) {
|
||||||
rows.add(
|
rows.add(
|
||||||
_row('pc-ring', words.last, <Widget>[
|
_row('pc-ring', words.last, <Widget>[
|
||||||
const Icon(Icons.computer),
|
const Tooltip(message: 'PC', child: Icon(Icons.computer)),
|
||||||
const Icon(Icons.notifications_active_outlined),
|
const Tooltip(
|
||||||
|
message: 'Ring',
|
||||||
|
child: Icon(Icons.notifications_active_outlined),
|
||||||
|
),
|
||||||
Text(hhmm(ring)),
|
Text(hhmm(ring)),
|
||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
@ -104,18 +112,30 @@ class StakesMarks extends StatelessWidget {
|
|||||||
return <Widget>[
|
return <Widget>[
|
||||||
if (view.escapedToday)
|
if (view.escapedToday)
|
||||||
_row('escaped', next(), <Widget>[
|
_row('escaped', next(), <Widget>[
|
||||||
Icon(Icons.bug_report_outlined, color: warning),
|
Tooltip(
|
||||||
|
message: 'Escaped',
|
||||||
|
child: Icon(Icons.bug_report_outlined, color: warning),
|
||||||
|
),
|
||||||
Icon(Icons.check, color: warning),
|
Icon(Icons.check, color: warning),
|
||||||
]),
|
]),
|
||||||
if (locked != null)
|
if (locked != null)
|
||||||
_row('locked', next(), <Widget>[
|
_row('locked', next(), <Widget>[
|
||||||
Icon(Icons.lock_outline, color: warning),
|
Tooltip(
|
||||||
|
message: 'Lock',
|
||||||
|
child: Icon(Icons.lock_outline, color: warning),
|
||||||
|
),
|
||||||
Text(_dm(locked), style: style),
|
Text(_dm(locked), style: style),
|
||||||
]),
|
]),
|
||||||
if (view.missedToday)
|
if (view.missedToday)
|
||||||
_row('missed', next(), <Widget>[
|
_row('missed', next(), <Widget>[
|
||||||
Icon(Icons.close, color: warning),
|
Tooltip(
|
||||||
Icon(Icons.computer, color: warning),
|
message: 'Missed',
|
||||||
|
child: Icon(Icons.close, color: warning),
|
||||||
|
),
|
||||||
|
Tooltip(
|
||||||
|
message: 'PC',
|
||||||
|
child: Icon(Icons.computer, color: warning),
|
||||||
|
),
|
||||||
]),
|
]),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,3 +1,4 @@
|
|||||||
|
import 'package:http/http.dart' as http;
|
||||||
import 'package:wake_alarm_sync/services/alarm_arming.dart';
|
import 'package:wake_alarm_sync/services/alarm_arming.dart';
|
||||||
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
||||||
import 'package:wake_alarm_sync/services/alarm_sync_service.dart';
|
import 'package:wake_alarm_sync/services/alarm_sync_service.dart';
|
||||||
@ -10,6 +11,10 @@ import 'package:wake_alarm_sync/services/sync_settings.dart';
|
|||||||
/// Split out of `home_screen.dart` for the 250-line gate, and because none of
|
/// Split out of `home_screen.dart` for the 250-line gate, and because none of
|
||||||
/// this is UI: it returns a message for the screen to render rather than
|
/// this is UI: it returns a message for the screen to render rather than
|
||||||
/// calling `setState` itself, which also makes it testable without a widget.
|
/// calling `setState` itself, which also makes it testable without a widget.
|
||||||
|
///
|
||||||
|
/// Offline-first: the local half — storing the time and arming the phone —
|
||||||
|
/// always runs. The sync half degrades to a status line, and the next
|
||||||
|
/// publish (app start, settings return, an earlier tap) retries it.
|
||||||
class AlarmPublisher {
|
class AlarmPublisher {
|
||||||
/// Creates a publisher; [arming] is injectable for tests.
|
/// Creates a publisher; [arming] is injectable for tests.
|
||||||
AlarmPublisher({AlarmArming? arming})
|
AlarmPublisher({AlarmArming? arming})
|
||||||
@ -21,53 +26,88 @@ class AlarmPublisher {
|
|||||||
/// Publishes [hour]:[minute] and arms the alarm, returning a status line.
|
/// Publishes [hour]:[minute] and arms the alarm, returning a status line.
|
||||||
///
|
///
|
||||||
/// Never throws: this runs unattended from the app's init seam, so a sync
|
/// Never throws: this runs unattended from the app's init seam, so a sync
|
||||||
/// failure must degrade to a message rather than take the screen down. The
|
/// failure must degrade to a message rather than take the screen down.
|
||||||
/// alarm itself is already armed by `main()` regardless of what happens
|
|
||||||
/// here — publishing is how the PC learns the time, not how the phone rings.
|
|
||||||
Future<String> publish({
|
Future<String> publish({
|
||||||
required AlarmSyncService? service,
|
required AlarmSyncService? service,
|
||||||
required int hour,
|
required int hour,
|
||||||
required int minute,
|
required int minute,
|
||||||
|
http.Client? httpClient,
|
||||||
}) async {
|
}) async {
|
||||||
final settings = await SyncSettings.load();
|
// The local half first: store the time (when a store exists) and arm the
|
||||||
// syncBackend() falls back to GitHub alone, or pushes to Firebase alone
|
// phone. Neither depends on a backend or the network, so the alarm is set
|
||||||
// via the mirror, so either credential is enough to proceed.
|
// even on a plane — the sync status below is the only thing that cannot
|
||||||
final hasFirebase = await loadAccount() != null;
|
// complete offline.
|
||||||
if (!settings.isConfigured && !hasFirebase) {
|
String? armProblem;
|
||||||
return 'Connect a sync backend in Settings first.';
|
var inClock = false;
|
||||||
}
|
Exception? saveError;
|
||||||
// Distinct from the above on purpose. Both used to report "connect a
|
if (service != null) {
|
||||||
// backend", so a store that failed to open looked like a configuration
|
try {
|
||||||
// the user had never done -- and the advice was to fix something that
|
await service.setLocal(hour, minute);
|
||||||
// was not broken.
|
} on Exception catch (e) {
|
||||||
if (service == null) {
|
// The log could not be written, so the PC must not be told
|
||||||
return 'Sync store unavailable — reopen the app.';
|
// "synced": pushing now would publish the previous time.
|
||||||
|
saveError = e;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
await service.setLocal(hour, minute);
|
armProblem = await arming.arm(hour, minute);
|
||||||
// Tags and home ride on the same record: stage local edits, sync
|
if (armProblem == null) {
|
||||||
// (pull, merge, push), then take whatever won back into prefs. That
|
inClock = await arming.registerWithClockApp(hour, minute);
|
||||||
// last step is how a fresh install gets its tags back.
|
}
|
||||||
await stageLocalSettings(service);
|
|
||||||
await service.push(settings.token);
|
|
||||||
await applySyncedSettings(service);
|
|
||||||
final problem = await arming.arm(hour, minute);
|
|
||||||
if (problem != null) return problem;
|
|
||||||
final inClock = await arming.registerWithClockApp(hour, minute);
|
|
||||||
return syncedStatus(hour, minute, inClock: inClock);
|
|
||||||
} on Exception catch (e) {
|
} on Exception catch (e) {
|
||||||
return 'Error: $e';
|
armProblem ??= 'Error: $e';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (saveError != null) {
|
||||||
|
return armProblem ?? '${armedFor(hour, minute)}Error: $saveError';
|
||||||
|
}
|
||||||
|
|
||||||
|
// The sync half: stage the settings that ride on the record, push, take
|
||||||
|
// the winners back into prefs (how a fresh install gets its tags).
|
||||||
|
if (service != null) {
|
||||||
|
final settings = await SyncSettings.load();
|
||||||
|
// syncBackend() falls back to GitHub alone, or pushes to Firebase alone
|
||||||
|
// via the mirror, so either credential is enough to proceed.
|
||||||
|
final configured = settings.isConfigured || await loadAccount() != null;
|
||||||
|
if (configured) {
|
||||||
|
try {
|
||||||
|
await stageLocalSettings(service);
|
||||||
|
await service.push(settings.token, httpClient: httpClient);
|
||||||
|
await applySyncedSettings(service);
|
||||||
|
} on Exception catch (e) {
|
||||||
|
// The local save and the arming are already done; only the push
|
||||||
|
// failed. Say so — the time is not lost, it rides the next publish.
|
||||||
|
return armProblem ??
|
||||||
|
'${armedFor(hour, minute)}Saved locally — will sync to PC. '
|
||||||
|
'Error: $e';
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return armProblem ??
|
||||||
|
'${armedFor(hour, minute)}'
|
||||||
|
'Connect a sync backend in Settings first.';
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Distinct from the "connect a backend" line on purpose. Both used to
|
||||||
|
// report the same thing, so a store that failed to open looked like a
|
||||||
|
// configuration the user had never done.
|
||||||
|
return armProblem ??
|
||||||
|
'${armedFor(hour, minute)}Sync store unavailable — reopen the app.';
|
||||||
|
}
|
||||||
|
return armProblem ?? syncedStatus(hour, minute, inClock: inClock);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The "Armed for HH:MM." prefix every status line shares: the local arm is
|
||||||
|
/// what succeeded, whatever the sync half reports.
|
||||||
|
String armedFor(int hour, int minute) =>
|
||||||
|
'Armed for '
|
||||||
|
'${hour.toString().padLeft(2, '0')}:'
|
||||||
|
'${minute.toString().padLeft(2, '0')}. ';
|
||||||
|
|
||||||
/// The success line, naming the armed time; names the Clock app only when
|
/// The success line, naming the armed time; names the Clock app only when
|
||||||
/// the handoff to it completed before its timeout, so a silent timeout
|
/// the handoff to it completed before its timeout, so a silent timeout
|
||||||
/// never claims it. Only reached after `arm()` succeeded.
|
/// never claims it.
|
||||||
String syncedStatus(int hour, int minute, {required bool inClock}) {
|
String syncedStatus(int hour, int minute, {required bool inClock}) {
|
||||||
final time =
|
final synced = '${armedFor(hour, minute)}Synced to PC ✓';
|
||||||
'${hour.toString().padLeft(2, '0')}:'
|
|
||||||
'${minute.toString().padLeft(2, '0')}';
|
|
||||||
final synced = 'Armed for $time. Synced to PC ✓';
|
|
||||||
return inClock ? '$synced Clock app set ✓' : synced;
|
return inClock ? '$synced Clock app set ✓' : synced;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -37,6 +37,15 @@ enum CueKind {
|
|||||||
CueKind? cueKindOf(String status) {
|
CueKind? cueKindOf(String status) {
|
||||||
if (status.isEmpty) return null;
|
if (status.isEmpty) return null;
|
||||||
if (status.endsWith('…') || status.endsWith('...')) return CueKind.busy;
|
if (status.endsWith('…') || status.endsWith('...')) return CueKind.busy;
|
||||||
|
// Checked before the error/ok keywords: an offline-first publish prefixes
|
||||||
|
// every line with "Armed for HH:MM." (the local half succeeded), so a
|
||||||
|
// pending sync must not read as a plain success, nor a dead network as a
|
||||||
|
// failure — the time is saved and rides the next sync.
|
||||||
|
if (status.contains('Saved locally') ||
|
||||||
|
status.contains('Connect a sync backend') ||
|
||||||
|
status.contains('Open Settings')) {
|
||||||
|
return CueKind.warning;
|
||||||
|
}
|
||||||
|
|
||||||
const errorKeywords = [
|
const errorKeywords = [
|
||||||
'Error',
|
'Error',
|
||||||
@ -72,10 +81,6 @@ CueKind? cueKindOf(String status) {
|
|||||||
if (status.contains(kw)) return CueKind.ok;
|
if (status.contains(kw)) return CueKind.ok;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (status.contains('Connect a sync backend') ||
|
|
||||||
status.contains('Open Settings')) {
|
|
||||||
return CueKind.warning;
|
|
||||||
}
|
|
||||||
return CueKind.info;
|
return CueKind.info;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,9 +1,65 @@
|
|||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'dart:io';
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
|
||||||
import 'package:wake_alarm_sync/services/alarm_publisher.dart';
|
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/alarm_arming.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/alarm_publisher.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/alarm_sync_service.dart';
|
||||||
|
|
||||||
|
import '../e2e_support.dart';
|
||||||
|
import '../fake_day_pool_store.dart';
|
||||||
import '../fake_secure_storage.dart';
|
import '../fake_secure_storage.dart';
|
||||||
|
|
||||||
|
/// Persistence whose writes start failing once [failing] is set.
|
||||||
|
class _FailingWrites extends MemPersistence {
|
||||||
|
bool failing = false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> write(String value) async {
|
||||||
|
if (failing) throw const FileSystemException('disk gone');
|
||||||
|
await super.write(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records the platform arms instead of touching the real channel.
|
||||||
|
class _RecordingScheduler extends AlarmScheduler {
|
||||||
|
_RecordingScheduler() : super(channel: const MethodChannel('test/alarm'));
|
||||||
|
|
||||||
|
final List<String> calls = [];
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> canUseFullScreenIntent() async => true;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> schedule(int hour, int minute) async {
|
||||||
|
calls.add('schedule $hour:$minute');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Completes the Clock handoff without launching an intent.
|
||||||
|
class _RecordingArming extends AlarmArming {
|
||||||
|
_RecordingArming(super.scheduler);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> registerWithClockApp(int hour, int minute) async => true;
|
||||||
|
}
|
||||||
|
|
||||||
|
class _OfflineClient extends http.BaseClient {
|
||||||
|
@override
|
||||||
|
Future<http.StreamedResponse> send(http.BaseRequest request) =>
|
||||||
|
throw http.ClientException('offline');
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<AlarmSyncService> _service({LogPersistence? persistence}) =>
|
||||||
|
AlarmSyncService.open(
|
||||||
|
persistence: persistence ?? MemPersistence(),
|
||||||
|
deviceId: 'test-device',
|
||||||
|
);
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
TestWidgetsFlutterBinding.ensureInitialized();
|
TestWidgetsFlutterBinding.ensureInitialized();
|
||||||
|
|
||||||
@ -13,12 +69,17 @@ void main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('an unconfigured install is told to connect a backend', () async {
|
test('an unconfigured install is told to connect a backend', () async {
|
||||||
final message = await AlarmPublisher().publish(
|
final scheduler = _RecordingScheduler();
|
||||||
service: null,
|
final service = await _service();
|
||||||
hour: 8,
|
final message = await AlarmPublisher(
|
||||||
minute: 0,
|
arming: _RecordingArming(scheduler),
|
||||||
);
|
).publish(service: service, hour: 8, minute: 0);
|
||||||
|
// Offline-first: the time is stored locally and the phone is armed even
|
||||||
|
// though nothing can be pushed yet.
|
||||||
|
expect(service.currentAlarm, (hour: 8, minute: 0));
|
||||||
|
expect(message, contains('Armed for 08:00'));
|
||||||
expect(message, contains('Connect a sync backend'));
|
expect(message, contains('Connect a sync backend'));
|
||||||
|
expect(scheduler.calls, ['schedule 8:0']);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('a missing store is not reported as a missing backend', () async {
|
test('a missing store is not reported as a missing backend', () async {
|
||||||
@ -30,13 +91,78 @@ void main() {
|
|||||||
SharedPreferences.setMockInitialValues(<String, Object>{
|
SharedPreferences.setMockInitialValues(<String, Object>{
|
||||||
'github_token': 'ghp_configured',
|
'github_token': 'ghp_configured',
|
||||||
});
|
});
|
||||||
final message = await AlarmPublisher().publish(
|
final scheduler = _RecordingScheduler();
|
||||||
service: null,
|
final message = await AlarmPublisher(
|
||||||
hour: 8,
|
arming: _RecordingArming(scheduler),
|
||||||
minute: 0,
|
).publish(service: null, hour: 8, minute: 0);
|
||||||
);
|
expect(message, contains('Armed for 08:00'));
|
||||||
expect(message, isNot(contains('Connect a sync backend')));
|
expect(message, isNot(contains('Connect a sync backend')));
|
||||||
expect(message, contains('Sync store unavailable'));
|
expect(message, contains('Sync store unavailable'));
|
||||||
|
expect(scheduler.calls, ['schedule 8:0']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a failed push keeps the phone armed and says it will sync', () async {
|
||||||
|
installE2eTestStorage();
|
||||||
|
SharedPreferences.setMockInitialValues(<String, Object>{
|
||||||
|
'github_token': 'ghp_configured',
|
||||||
|
});
|
||||||
|
final scheduler = _RecordingScheduler();
|
||||||
|
final service = await _service();
|
||||||
|
final message = await AlarmPublisher(arming: _RecordingArming(scheduler))
|
||||||
|
.publish(
|
||||||
|
service: service,
|
||||||
|
hour: 7,
|
||||||
|
minute: 30,
|
||||||
|
httpClient: _OfflineClient(),
|
||||||
|
);
|
||||||
|
expect(service.currentAlarm, (hour: 7, minute: 30));
|
||||||
|
expect(message, contains('Armed for 07:30'));
|
||||||
|
expect(message, contains('Saved locally'));
|
||||||
|
expect(message, contains('Error'));
|
||||||
|
expect(scheduler.calls, ['schedule 7:30']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a failed local save is reported, never "synced"', () async {
|
||||||
|
installE2eTestStorage();
|
||||||
|
SharedPreferences.setMockInitialValues(<String, Object>{
|
||||||
|
'github_token': 'ghp_configured',
|
||||||
|
});
|
||||||
|
final github = MemGitHub();
|
||||||
|
final persistence = _FailingWrites();
|
||||||
|
final service = await _service(persistence: persistence);
|
||||||
|
persistence.failing = true;
|
||||||
|
final message =
|
||||||
|
await AlarmPublisher(
|
||||||
|
arming: _RecordingArming(_RecordingScheduler()),
|
||||||
|
).publish(
|
||||||
|
service: service,
|
||||||
|
hour: 6,
|
||||||
|
minute: 45,
|
||||||
|
httpClient: github.httpClient,
|
||||||
|
);
|
||||||
|
expect(message, contains('Armed for 06:45'));
|
||||||
|
expect(message, contains('Error'));
|
||||||
|
expect(message, isNot(contains('Synced')));
|
||||||
|
expect(github.putPaths, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a push on a live mirror ends with the synced line', () async {
|
||||||
|
installE2eTestStorage();
|
||||||
|
SharedPreferences.setMockInitialValues(<String, Object>{
|
||||||
|
'github_token': 'ghp_configured',
|
||||||
|
});
|
||||||
|
final github = MemGitHub();
|
||||||
|
final scheduler = _RecordingScheduler();
|
||||||
|
final message = await AlarmPublisher(arming: _RecordingArming(scheduler))
|
||||||
|
.publish(
|
||||||
|
service: await _service(),
|
||||||
|
hour: 7,
|
||||||
|
minute: 15,
|
||||||
|
httpClient: github.httpClient,
|
||||||
|
);
|
||||||
|
expect(message, 'Armed for 07:15. Synced to PC ✓ Clock app set ✓');
|
||||||
|
expect(scheduler.calls, ['schedule 7:15']);
|
||||||
|
expect(github.putPaths, isNotEmpty);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('the Clock line names the time only when the handoff completed', () {
|
test('the Clock line names the time only when the handoff completed', () {
|
||||||
|
|||||||
@ -9,14 +9,17 @@ import 'package:wake_alarm_sync/services/sync_emulator.dart';
|
|||||||
class _Github extends Fake implements RemoteStore {}
|
class _Github extends Fake implements RemoteStore {}
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
test('a build without the define syncs to prod, never the emulator', () async {
|
test(
|
||||||
expect(kSyncEmulatorUrl, isEmpty);
|
'a build without the define syncs to prod, never the emulator',
|
||||||
expect(syncEmulatorOn, isFalse);
|
() async {
|
||||||
expect(kProject.databaseUrl, contains('kuhy-syncs'));
|
expect(kSyncEmulatorUrl, isEmpty);
|
||||||
final github = _Github();
|
expect(syncEmulatorOn, isFalse);
|
||||||
// No Firebase session in tests: prod's rollback path, GitHub alone.
|
expect(kProject.databaseUrl, contains('kuhy-syncs'));
|
||||||
expect(await syncBackend(github), same(github));
|
final github = _Github();
|
||||||
});
|
// No Firebase session in tests: prod's rollback path, GitHub alone.
|
||||||
|
expect(await syncBackend(github), same(github));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
test('the emulator client signs as owner against the given origin', () async {
|
test('the emulator client signs as owner against the given origin', () async {
|
||||||
final seen = <Uri>[];
|
final seen = <Uri>[];
|
||||||
|
|||||||
@ -51,7 +51,14 @@ void _collectSubtree(Element element, Set<Element> out) {
|
|||||||
void expectNoWords(WidgetTester tester, String screen) {
|
void expectNoWords(WidgetTester tester, String screen) {
|
||||||
final words = wordsOnScreen(tester);
|
final words = wordsOnScreen(tester);
|
||||||
expect(words, isEmpty, reason: 'words on $screen: $words');
|
expect(words, isEmpty, reason: 'words on $screen: $words');
|
||||||
expect(find.byType(Tooltip), findsNothing, reason: 'tooltip on $screen');
|
final tooltips = tester.widgetList<Tooltip>(find.byType(Tooltip));
|
||||||
|
for (final tooltip in tooltips) {
|
||||||
|
expect(
|
||||||
|
tooltip.message,
|
||||||
|
matches(RegExp(r'^[^\s.!?,;:]{1,20}$')),
|
||||||
|
reason: 'tooltip on $screen: ${tooltip.message}',
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pixel 6a portrait: 1080x2400 physical at 2.625.
|
/// Pixel 6a portrait: 1080x2400 physical at 2.625.
|
||||||
|
|||||||
32
phone_app/test/tooltips_test.dart
Normal file
32
phone_app/test/tooltips_test.dart
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
import 'package:wake_alarm_sync/screens/free_days_screen.dart';
|
||||||
|
import 'package:wake_alarm_sync/screens/settings_screen.dart'
|
||||||
|
show SettingsScreen;
|
||||||
|
import 'package:wake_alarm_sync/services/free_day_sync.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/theme.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('settings export/import have one-word tooltips', (tester) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(theme: buildAppTheme(), home: const SettingsScreen()),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(find.byTooltip('Export'), findsOneWidget);
|
||||||
|
expect(find.byTooltip('Import'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('free days sync has one-word tooltip', (tester) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
theme: buildAppTheme(),
|
||||||
|
home: FreeDaysScreen(
|
||||||
|
openPool: () async => throw Exception('test'),
|
||||||
|
syncer: FreeDaySync(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(find.byTooltip('Sync'), findsOneWidget);
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -3,6 +3,7 @@ library;
|
|||||||
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
import 'package:material_ui/material_ui.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/alarm_publisher.dart';
|
||||||
import 'package:wake_alarm_sync/ui/cues.dart';
|
import 'package:wake_alarm_sync/ui/cues.dart';
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
@ -60,6 +61,24 @@ void main() {
|
|||||||
expect(cueKindOf('Open Settings to connect'), equals(CueKind.warning));
|
expect(cueKindOf('Open Settings to connect'), equals(CueKind.warning));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('every offline-first publish line keeps its own cue', () {
|
||||||
|
// Each line is built by AlarmPublisher, so a reworded prefix that
|
||||||
|
// flips a pending sync to "ok" (or a dead network to "error") fails.
|
||||||
|
expect(
|
||||||
|
cueKindOf('${armedFor(8, 0)}Connect a sync backend in Settings first.'),
|
||||||
|
equals(CueKind.warning),
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
cueKindOf('${armedFor(8, 0)}Saved locally — will sync to PC. Error: x'),
|
||||||
|
equals(CueKind.warning),
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
cueKindOf('${armedFor(8, 0)}Sync store unavailable — reopen the app.'),
|
||||||
|
equals(CueKind.error),
|
||||||
|
);
|
||||||
|
expect(cueKindOf(syncedStatus(8, 0, inClock: false)), equals(CueKind.ok));
|
||||||
|
});
|
||||||
|
|
||||||
test('default info', () {
|
test('default info', () {
|
||||||
expect(cueKindOf('hello'), equals(CueKind.info));
|
expect(cueKindOf('hello'), equals(CueKind.info));
|
||||||
expect(cueKindOf('Syncing now'), equals(CueKind.info));
|
expect(cueKindOf('Syncing now'), equals(CueKind.info));
|
||||||
|
|||||||
@ -8,7 +8,7 @@ version = "1.0.0"
|
|||||||
description = "Trigger that starts the morning routine at the phone's alarm time"
|
description = "Trigger that starts the morning routine at the phone's alarm time"
|
||||||
requires-python = ">=3.14"
|
requires-python = ">=3.14"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock",
|
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.2#subdirectory=gatelock",
|
||||||
# Firebase transport for the alarm read. _sync.py imports it lazily and
|
# Firebase transport for the alarm read. _sync.py imports it lazily and
|
||||||
# falls back to its stdlib GitHub path if the import fails, so a broken
|
# falls back to its stdlib GitHub path if the import fails, so a broken
|
||||||
# install degrades the read instead of killing the per-minute trigger.
|
# install degrades the read instead of killing the per-minute trigger.
|
||||||
@ -169,10 +169,6 @@ addopts = [
|
|||||||
"--strict-markers",
|
"--strict-markers",
|
||||||
"--strict-config",
|
"--strict-config",
|
||||||
"-ra",
|
"-ra",
|
||||||
"--cov=wake_alarm",
|
|
||||||
"--cov-branch",
|
|
||||||
"--cov-report=term-missing",
|
|
||||||
"--cov-report=lcov",
|
|
||||||
]
|
]
|
||||||
filterwarnings = [
|
filterwarnings = [
|
||||||
"error",
|
"error",
|
||||||
@ -190,7 +186,6 @@ omit = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[tool.coverage.report]
|
[tool.coverage.report]
|
||||||
fail_under = 100
|
|
||||||
show_missing = true
|
show_missing = true
|
||||||
skip_covered = false
|
skip_covered = false
|
||||||
exclude_lines = [
|
exclude_lines = [
|
||||||
|
|||||||
@ -4,10 +4,10 @@
|
|||||||
# it is missing — but it is required here for mypy/pylint/tests.
|
# it is missing — but it is required here for mypy/pylint/tests.
|
||||||
bandit==1.9.4
|
bandit==1.9.4
|
||||||
codespell==2.4.3
|
codespell==2.4.3
|
||||||
coverage==7.17.4
|
coverage==7.17.5
|
||||||
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
|
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
|
||||||
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
|
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
|
||||||
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock
|
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.2#subdirectory=gatelock
|
||||||
kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
|
kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
|
||||||
mypy==2.4.1
|
mypy==2.4.1
|
||||||
pre-commit==4.7.0
|
pre-commit==4.7.0
|
||||||
|
|||||||
@ -21,7 +21,13 @@ import json
|
|||||||
import logging
|
import logging
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from wake_alarm._constants import MAX_HOUR, MAX_MINUTE, MIN_HOUR, MIN_MINUTE
|
from wake_alarm._constants import (
|
||||||
|
FOCUS_OWNER_DEVICE_ID,
|
||||||
|
MAX_HOUR,
|
||||||
|
MAX_MINUTE,
|
||||||
|
MIN_HOUR,
|
||||||
|
MIN_MINUTE,
|
||||||
|
)
|
||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@ -188,6 +194,10 @@ def newest_alarm(
|
|||||||
"""
|
"""
|
||||||
ranked: list[tuple[str, str, tuple[int, int]]] = []
|
ranked: list[tuple[str, str, tuple[int, int]]] = []
|
||||||
for device_id, raw in published:
|
for device_id, raw in published:
|
||||||
|
# focus-owner publishes only its bypass events, never an alarm; parsing
|
||||||
|
# it would log a WARNING on every live fetch.
|
||||||
|
if device_id == FOCUS_OWNER_DEVICE_ID:
|
||||||
|
continue
|
||||||
parsed = parse_log(raw)
|
parsed = parse_log(raw)
|
||||||
if parsed is None:
|
if parsed is None:
|
||||||
_logger.info("Ignoring unusable alarm published by %r", device_id)
|
_logger.info("Ignoring unusable alarm published by %r", device_id)
|
||||||
|
|||||||
@ -49,6 +49,11 @@ SYNC_TOKEN_FALLBACK_FILES: tuple[Path, ...] = (
|
|||||||
# Where a successful read is cached, so a network blip can't cost a wake-up.
|
# Where a successful read is cached, so a network blip can't cost a wake-up.
|
||||||
ALARM_CACHE_FILE: Path = Path.home() / ".config" / "wake_alarm" / "alarm_cache.json"
|
ALARM_CACHE_FILE: Path = Path.home() / ".config" / "wake_alarm" / "alarm_cache.json"
|
||||||
|
|
||||||
|
# The last successful Firebase fetch of every device's log, served offline.
|
||||||
|
SYNC_LOGS_CACHE_FILE: Path = (
|
||||||
|
Path.home() / ".config" / "wake_alarm" / "synced_logs_cache.json"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# Structured logs live under XDG state, not .config: they are churning runtime
|
# Structured logs live under XDG state, not .config: they are churning runtime
|
||||||
# data, not configuration. The JSONL file is additive -- the journal keeps
|
# data, not configuration. The JSONL file is additive -- the journal keeps
|
||||||
@ -76,6 +81,10 @@ SYNC_LEGACY_PREFIX: str = "wake-alarm-sync/devices"
|
|||||||
# lists. Copied over from the plaintext prefix like everything else.
|
# lists. Copied over from the plaintext prefix like everything else.
|
||||||
SYNC_ALARM_PATH: str = f"{SYNC_DEVICES_PREFIX}/phone/alarm.json"
|
SYNC_ALARM_PATH: str = f"{SYNC_DEVICES_PREFIX}/phone/alarm.json"
|
||||||
|
|
||||||
|
# focus-owner's own device directory. It publishes ``bypass`` with cause
|
||||||
|
# ``uninstalled`` when WakeAlarm is gone, so it is never the phone's push.
|
||||||
|
FOCUS_OWNER_DEVICE_ID: str = "focus-owner"
|
||||||
|
|
||||||
# The file each device publishes its alarm as, inside its own directory.
|
# The file each device publishes its alarm as, inside its own directory.
|
||||||
SYNC_ALARM_FILENAME: str = "alarm.json"
|
SYNC_ALARM_FILENAME: str = "alarm.json"
|
||||||
|
|
||||||
|
|||||||
@ -25,6 +25,7 @@ from wake_alarm._constants import (
|
|||||||
ESCAPE_HATCH_LAST_DAY,
|
ESCAPE_HATCH_LAST_DAY,
|
||||||
ESCAPE_REASON_MIN_CHARS,
|
ESCAPE_REASON_MIN_CHARS,
|
||||||
ESCAPES_FIELD,
|
ESCAPES_FIELD,
|
||||||
|
FOCUS_OWNER_DEVICE_ID,
|
||||||
PHONE_EVENTS_FIELD,
|
PHONE_EVENTS_FIELD,
|
||||||
RING_STARTED_FIELD,
|
RING_STARTED_FIELD,
|
||||||
STICK_STATE_FIELD,
|
STICK_STATE_FIELD,
|
||||||
@ -204,10 +205,13 @@ def newest_push(logs: list[tuple[str, dict[str, Any]]]) -> float | None:
|
|||||||
|
|
||||||
Every phone write stamps the field it changed, so the largest instant is
|
Every phone write stamps the field it changed, so the largest instant is
|
||||||
when the phone last uploaded anything. A stamp that cannot be dated is
|
when the phone last uploaded anything. A stamp that cannot be dated is
|
||||||
skipped: None means "cannot tell", never "old".
|
skipped: None means "cannot tell", never "old". focus-owner's writes are
|
||||||
|
not the phone's: it publishes exactly when WakeAlarm is uninstalled.
|
||||||
"""
|
"""
|
||||||
stamps: list[float] = []
|
stamps: list[float] = []
|
||||||
for _, log in logs:
|
for device_id, log in logs:
|
||||||
|
if device_id == FOCUS_OWNER_DEVICE_ID:
|
||||||
|
continue
|
||||||
record = log.get("alarm")
|
record = log.get("alarm")
|
||||||
fields = record.get("fields") if isinstance(record, dict) else None
|
fields = record.get("fields") if isinstance(record, dict) else None
|
||||||
for name in fields if isinstance(fields, dict) else ():
|
for name in fields if isinstance(fields, dict) else ():
|
||||||
|
|||||||
@ -64,7 +64,8 @@ def latest_field[T](
|
|||||||
field: str, parse: Callable[[object, str], T | None], *, what: str
|
field: str, parse: Callable[[object, str], T | None], *, what: str
|
||||||
) -> T | None:
|
) -> T | None:
|
||||||
"""``newest_field`` over a live Firebase read; None when unreadable."""
|
"""``newest_field`` over a live Firebase read; None when unreadable."""
|
||||||
published = fetch_firebase_logs()
|
# Offline-first: a dead network serves the last synced logs.
|
||||||
|
published = fetch_firebase_logs(offline_cache=True)
|
||||||
if published is None:
|
if published is None:
|
||||||
return None
|
return None
|
||||||
value = newest_field(published, field, parse)
|
value = newest_field(published, field, parse)
|
||||||
|
|||||||
@ -16,7 +16,7 @@ from datetime import timedelta
|
|||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from wake_alarm._constants import LOG_STATE_DIR
|
from wake_alarm._constants import LOG_STATE_DIR
|
||||||
from wake_alarm._events import emit
|
from wake_alarm._events import emit, emit_on_change
|
||||||
from wake_alarm._ring_player import _ok, graphical_session
|
from wake_alarm._ring_player import _ok, graphical_session
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
@ -33,8 +33,12 @@ def maybe_probe(now: datetime, alarm_at: datetime) -> str | None:
|
|||||||
return None
|
return None
|
||||||
graphical, why = graphical_session()
|
graphical, why = graphical_session()
|
||||||
if graphical:
|
if graphical:
|
||||||
# Not the state a fallback ring meets; try again tomorrow.
|
# Not the state a fallback ring meets; try again tomorrow. Logged
|
||||||
return "waiting_for_no_session"
|
# once a day, so a morning with no ring_probe line is a bug.
|
||||||
|
reason = "waiting_for_no_session"
|
||||||
|
key = f"{now.date().isoformat()}|{reason}"
|
||||||
|
emit_on_change("ring_probe", key, reason, session=why)
|
||||||
|
return reason
|
||||||
started, out = _ok(["sudo", "-n", "systemctl", "start", PROBE_UNIT])
|
started, out = _ok(["sudo", "-n", "systemctl", "start", PROBE_UNIT])
|
||||||
emit("ring_probe", "started" if started else "failed", session=why, output=out)
|
emit("ring_probe", "started" if started else "failed", session=why, output=out)
|
||||||
if not started:
|
if not started:
|
||||||
|
|||||||
65
wake_alarm/_sync_log_cache.py
Normal file
65
wake_alarm/_sync_log_cache.py
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
"""The last successfully-fetched Firebase logs, read back when offline.
|
||||||
|
|
||||||
|
``fetch_firebase_logs`` writes the cache after every success and, for the
|
||||||
|
display readers that ask for it (``_weight``, ``_energy`` via
|
||||||
|
``_field_reader``), serves it when a fetch fails, so they still answer with
|
||||||
|
the newest known data while the network is down. The alarm path and the
|
||||||
|
enforcement checks do not ask: they must see a failed read as a failure.
|
||||||
|
The alarm time keeps its own ``ALARM_CACHE_FILE``; this is the *details*
|
||||||
|
half of offline-first: the raw per-device logs, not just the hour and
|
||||||
|
minute.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from wake_alarm._constants import SYNC_LOGS_CACHE_FILE
|
||||||
|
|
||||||
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
#: The arity of one cached ``(device_id, raw_log_json)`` pair.
|
||||||
|
_PAIR_ARITY = 2
|
||||||
|
|
||||||
|
|
||||||
|
def write_synced_logs_cache(published: list[tuple[str, str]]) -> None:
|
||||||
|
"""Persist [published] ``(device_id, raw_log_json)`` pairs.
|
||||||
|
|
||||||
|
A failed write is logged and swallowed: the fetch already succeeded, and
|
||||||
|
losing the cache must not crash the per-minute trigger or a reader.
|
||||||
|
"""
|
||||||
|
entry = {"logs": [[device_id, raw] for device_id, raw in published]}
|
||||||
|
try:
|
||||||
|
SYNC_LOGS_CACHE_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
SYNC_LOGS_CACHE_FILE.write_text(json.dumps(entry, indent=2))
|
||||||
|
except OSError as exc:
|
||||||
|
_logger.warning("Cannot write synced-logs cache: %s", exc)
|
||||||
|
|
||||||
|
|
||||||
|
def read_synced_logs_cache() -> list[tuple[str, str]] | None:
|
||||||
|
"""The cached pairs, or None when absent, unreadable or malformed.
|
||||||
|
|
||||||
|
A corrupt cache degrades to "nothing cached" — the fetch then degrades
|
||||||
|
further to its own fallbacks — never to a crash.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
cached = json.loads(SYNC_LOGS_CACHE_FILE.read_text())
|
||||||
|
except OSError, json.JSONDecodeError:
|
||||||
|
return None
|
||||||
|
if not isinstance(cached, dict):
|
||||||
|
return None
|
||||||
|
logs = cached.get("logs")
|
||||||
|
if not isinstance(logs, list) or not logs:
|
||||||
|
return None
|
||||||
|
pairs = [
|
||||||
|
(pair[0], pair[1])
|
||||||
|
for pair in logs
|
||||||
|
if (
|
||||||
|
isinstance(pair, list)
|
||||||
|
and len(pair) == _PAIR_ARITY
|
||||||
|
and isinstance(pair[0], str)
|
||||||
|
and isinstance(pair[1], str)
|
||||||
|
)
|
||||||
|
]
|
||||||
|
return pairs or None
|
||||||
@ -36,6 +36,7 @@ from wake_alarm._constants import (
|
|||||||
SYNC_REPO_NAME,
|
SYNC_REPO_NAME,
|
||||||
SYNC_REPO_OWNER,
|
SYNC_REPO_OWNER,
|
||||||
)
|
)
|
||||||
|
from wake_alarm._sync_log_cache import read_synced_logs_cache, write_synced_logs_cache
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from crdt_sync import Argon2Params, RemoteStore
|
from crdt_sync import Argon2Params, RemoteStore
|
||||||
@ -122,7 +123,7 @@ def _read_published(client: RemoteStore) -> list[tuple[str, str]]:
|
|||||||
return published
|
return published
|
||||||
|
|
||||||
|
|
||||||
def fetch_firebase_logs() -> list[tuple[str, str]] | None:
|
def fetch_firebase_logs(*, offline_cache: bool = False) -> list[tuple[str, str]] | None:
|
||||||
"""Fetch every device's decrypted ``alarm.json`` from Firebase.
|
"""Fetch every device's decrypted ``alarm.json`` from Firebase.
|
||||||
|
|
||||||
Shared by the alarm reader and ``_weight``: the morning session's
|
Shared by the alarm reader and ``_weight``: the morning session's
|
||||||
@ -133,6 +134,15 @@ def fetch_firebase_logs() -> list[tuple[str, str]] | None:
|
|||||||
(no or wrong passphrase) store, so the caller can fall back to GitHub and
|
(no or wrong passphrase) store, so the caller can fall back to GitHub and
|
||||||
then to the cache.
|
then to the cache.
|
||||||
|
|
||||||
|
Every successful fetch rewrites the synced-logs cache. Only a caller that
|
||||||
|
passes *offline_cache* gets that cache back when the fetch fails: the
|
||||||
|
display readers (``_weight``, ``_energy``) want the newest known value
|
||||||
|
offline, while the alarm path (which has its own cache *after* the
|
||||||
|
GitHub fallback) and the enforcement checks must still see the failure.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
offline_cache: Serve the last cached logs when the fetch fails.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
``(device_id, raw_json)`` per device, or None if unconfigured,
|
``(device_id, raw_json)`` per device, or None if unconfigured,
|
||||||
locked or unreadable.
|
locked or unreadable.
|
||||||
@ -156,10 +166,11 @@ def fetch_firebase_logs() -> list[tuple[str, str]] | None:
|
|||||||
E2eLockedError,
|
E2eLockedError,
|
||||||
) as exc:
|
) as exc:
|
||||||
_logger.info("Cannot fetch the alarm from Firebase: %s", exc)
|
_logger.info("Cannot fetch the alarm from Firebase: %s", exc)
|
||||||
return None
|
return read_synced_logs_cache() if offline_cache else None
|
||||||
if not published:
|
if not published:
|
||||||
_logger.info("No alarm published to Firebase yet")
|
_logger.info("No alarm published to Firebase yet")
|
||||||
return None
|
return None
|
||||||
|
write_synced_logs_cache(published)
|
||||||
return published
|
return published
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -186,6 +186,12 @@ def _hermetic(tmp_path: Path) -> Generator[None]:
|
|||||||
# the trigger's cache. A missing Firebase config keeps fetches
|
# the trigger's cache. A missing Firebase config keeps fetches
|
||||||
# off the network unless a test patches the fetch itself.
|
# off the network unless a test patches the fetch itself.
|
||||||
patch("wake_alarm._sync.ALARM_CACHE_FILE", tmp_path / "alarm_cache.json"),
|
patch("wake_alarm._sync.ALARM_CACHE_FILE", tmp_path / "alarm_cache.json"),
|
||||||
|
# The raw per-device logs (weigh-in, energy, ...) are the *details*
|
||||||
|
# half of offline-first; keep that cache off the live file too.
|
||||||
|
patch(
|
||||||
|
"wake_alarm._sync_log_cache.SYNC_LOGS_CACHE_FILE",
|
||||||
|
tmp_path / "synced_logs_cache.json",
|
||||||
|
),
|
||||||
patch(
|
patch(
|
||||||
"wake_alarm._sync_transport.FIREBASE_CONFIG_FILE",
|
"wake_alarm._sync_transport.FIREBASE_CONFIG_FILE",
|
||||||
tmp_path / "no-firebase.json",
|
tmp_path / "no-firebase.json",
|
||||||
|
|||||||
@ -215,3 +215,19 @@ class TestHlcInstant:
|
|||||||
def test_an_unparsable_prefix_is_undated(self) -> None:
|
def test_an_unparsable_prefix_is_undated(self) -> None:
|
||||||
"""Garbage before the Z must not raise out of a per-minute tick."""
|
"""Garbage before the Z must not raise out of a per-minute tick."""
|
||||||
assert hlc_instant("not-a-timestampZ-0000-device") is None
|
assert hlc_instant("not-a-timestampZ-0000-device") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_newest_alarm_skips_focus_owner_without_a_warning(
|
||||||
|
caplog: pytest.LogCaptureFixture,
|
||||||
|
) -> None:
|
||||||
|
"""focus-owner's log never carries an alarm; reading it is not a fault."""
|
||||||
|
hlc = "2026-11-23T06:00:00.000Z-0000-p"
|
||||||
|
phone = json.dumps(
|
||||||
|
{"alarm": {"fields": {"alarm_hour": [7, hlc], "alarm_minute": [30, hlc]}}}
|
||||||
|
)
|
||||||
|
owner = json.dumps({"alarm": {"fields": {"phone_events": [[], hlc]}}})
|
||||||
|
with caplog.at_level("INFO"):
|
||||||
|
result = newest_alarm([("focus-owner", owner), ("p", phone)])
|
||||||
|
assert result is not None
|
||||||
|
assert result[:2] == (7, 30)
|
||||||
|
assert not [r for r in caplog.records if r.levelname == "WARNING"]
|
||||||
|
|||||||
@ -102,3 +102,11 @@ def test_last_push_is_the_newest_dated_hlc_of_any_field_on_any_device() -> None:
|
|||||||
def test_last_push_is_none_without_a_dated_stamp() -> None:
|
def test_last_push_is_none_without_a_dated_stamp() -> None:
|
||||||
assert enforcement_view([("a", _log(alarm_hour=(7, "h")))]).last_push is None
|
assert enforcement_view([("a", _log(alarm_hour=(7, "h")))]).last_push is None
|
||||||
assert enforcement_view([]).last_push is None
|
assert enforcement_view([]).last_push is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_last_push_ignores_focus_owner_writes() -> None:
|
||||||
|
"""focus-owner publishes ``bypass:uninstalled``; that is not a phone push."""
|
||||||
|
phone = _log(alarm_hour=(7, "2026-11-20T06:00:00.000Z-0000-p"))
|
||||||
|
owner = _log(phone_events=([], "2026-11-23T09:00:00.000Z-0000-f"))
|
||||||
|
view = enforcement_view([("p", phone), ("focus-owner", owner)])
|
||||||
|
assert view.last_push == datetime(2026, 11, 20, 6, 0, tzinfo=UTC).timestamp()
|
||||||
|
|||||||
@ -67,3 +67,16 @@ def test_it_waits_for_a_morning_with_no_session(done_file: Path) -> None:
|
|||||||
def test_a_refused_start_is_retried_next_morning(done_file: Path) -> None:
|
def test_a_refused_start_is_retried_next_morning(done_file: Path) -> None:
|
||||||
assert _run(-3, graphical=False, started=False) == "failed"
|
assert _run(-3, graphical=False, started=False) == "failed"
|
||||||
assert not done_file.exists()
|
assert not done_file.exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_skipped_morning_is_logged_once_a_day() -> None:
|
||||||
|
# Without it, a missing ring_probe line at 08:00 cannot tell "kuhy was
|
||||||
|
# logged in" from "the probe never ran".
|
||||||
|
with patch.object(_ring_probe, "emit_on_change") as emit:
|
||||||
|
assert _run(-3, graphical=True) == "waiting_for_no_session"
|
||||||
|
emit.assert_called_once_with(
|
||||||
|
"ring_probe",
|
||||||
|
"2026-11-23|waiting_for_no_session",
|
||||||
|
"waiting_for_no_session",
|
||||||
|
session="why",
|
||||||
|
)
|
||||||
|
|||||||
200
wake_alarm/tests/test_sync_log_cache.py
Normal file
200
wake_alarm/tests/test_sync_log_cache.py
Normal file
@ -0,0 +1,200 @@
|
|||||||
|
"""The offline-first fallback of every Firebase-log reader.
|
||||||
|
|
||||||
|
``fetch_firebase_logs`` caches its last success (``_sync_log_cache``) and
|
||||||
|
serves it when a fetch fails, so the field readers (``_weight``,
|
||||||
|
``_energy``, ...) answer with the newest known data while the network is
|
||||||
|
down. These tests pin that contract.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from crdt_sync import RemoteSyncError
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from wake_alarm import _sync_log_cache
|
||||||
|
from wake_alarm._sync_log_cache import (
|
||||||
|
read_synced_logs_cache,
|
||||||
|
write_synced_logs_cache,
|
||||||
|
)
|
||||||
|
from wake_alarm._sync_transport import fetch_firebase_logs, fetch_remote_alarm
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import NoReturn
|
||||||
|
|
||||||
|
_LOGS = [("device-a", '{"alarm": {}}')]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _cache_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
"""Point the cache at tmp for every test here; the autouse conftest
|
||||||
|
redirect covers the rest of the suite."""
|
||||||
|
monkeypatch.setattr(
|
||||||
|
_sync_log_cache, "SYNC_LOGS_CACHE_FILE", tmp_path / "logs_cache.json"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_write_then_read_roundtrip() -> None:
|
||||||
|
write_synced_logs_cache(_LOGS)
|
||||||
|
assert read_synced_logs_cache() == _LOGS
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_missing_file_is_none() -> None:
|
||||||
|
assert read_synced_logs_cache() is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_corrupt_file_is_none() -> None:
|
||||||
|
file = _sync_log_cache.SYNC_LOGS_CACHE_FILE
|
||||||
|
file.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
file.write_text("not json")
|
||||||
|
assert read_synced_logs_cache() is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_wrong_shape_is_none() -> None:
|
||||||
|
file = _sync_log_cache.SYNC_LOGS_CACHE_FILE
|
||||||
|
file.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
file.write_text(json.dumps({"logs": [{"wrong": "shape"}]}))
|
||||||
|
assert read_synced_logs_cache() is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_cache_not_a_dict_is_none() -> None:
|
||||||
|
file = _sync_log_cache.SYNC_LOGS_CACHE_FILE
|
||||||
|
file.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
file.write_text(json.dumps(["logs"]))
|
||||||
|
assert read_synced_logs_cache() is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_logs_not_a_list_is_none() -> None:
|
||||||
|
file = _sync_log_cache.SYNC_LOGS_CACHE_FILE
|
||||||
|
file.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
file.write_text(json.dumps({"logs": 5}))
|
||||||
|
assert read_synced_logs_cache() is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_empty_logs_is_none() -> None:
|
||||||
|
file = _sync_log_cache.SYNC_LOGS_CACHE_FILE
|
||||||
|
file.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
file.write_text(json.dumps({"logs": []}))
|
||||||
|
assert read_synced_logs_cache() is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_write_failure_is_swallowed() -> None:
|
||||||
|
# The cache path is a directory, so write_text raises; the failure must
|
||||||
|
# be swallowed, not crash the reader it protects.
|
||||||
|
blocker = _sync_log_cache.SYNC_LOGS_CACHE_FILE
|
||||||
|
blocker.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
blocker.mkdir()
|
||||||
|
write_synced_logs_cache(_LOGS) # must not raise
|
||||||
|
|
||||||
|
|
||||||
|
def _configured_transport(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||||
|
"""A transport that *is* configured: the fetch reaches the backend."""
|
||||||
|
config = tmp_path / "firebase-config.json"
|
||||||
|
config.write_text("{}")
|
||||||
|
monkeypatch.setattr("wake_alarm._sync_transport.FIREBASE_CONFIG_FILE", config)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"wake_alarm._sync_transport.firebase_client_for", lambda _app: object()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_failed_fetch_serves_the_cache(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
_configured_transport(monkeypatch, tmp_path)
|
||||||
|
write_synced_logs_cache(_LOGS)
|
||||||
|
|
||||||
|
def _fail(_client: object) -> NoReturn:
|
||||||
|
msg = "offline"
|
||||||
|
raise RemoteSyncError(msg)
|
||||||
|
|
||||||
|
monkeypatch.setattr("wake_alarm._sync_transport._read_published", _fail)
|
||||||
|
assert fetch_firebase_logs(offline_cache=True) == _LOGS
|
||||||
|
# Callers that did not ask (alarm path, audit, fallback ring) still see
|
||||||
|
# the failure: stale logs must not pass for a live read there.
|
||||||
|
assert fetch_firebase_logs() is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_log_cache_does_not_skip_the_github_alarm_fallback(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
_configured_transport(monkeypatch, tmp_path)
|
||||||
|
write_synced_logs_cache(_LOGS)
|
||||||
|
|
||||||
|
def _fail(_client: object) -> NoReturn:
|
||||||
|
msg = "offline"
|
||||||
|
raise RemoteSyncError(msg)
|
||||||
|
|
||||||
|
monkeypatch.setattr("wake_alarm._sync_transport._read_published", _fail)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"wake_alarm._sync_transport._fetch_github_alarm", lambda: (6, 30, None)
|
||||||
|
)
|
||||||
|
assert fetch_remote_alarm() == (6, 30, None)
|
||||||
|
|
||||||
|
|
||||||
|
def test_unconfigured_fetch_without_cache_is_none(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
# Conftest default: the config file does not exist, no cache written.
|
||||||
|
assert fetch_firebase_logs() is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_success_writes_the_cache(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
_configured_transport(monkeypatch, tmp_path)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"wake_alarm._sync_transport._read_published", lambda _client: _LOGS
|
||||||
|
)
|
||||||
|
assert fetch_firebase_logs() == _LOGS
|
||||||
|
assert read_synced_logs_cache() == _LOGS
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_empty_fetch_returns_none_and_keeps_the_cache(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
# An empty *successful* fetch (no devices, no exception) means "nothing
|
||||||
|
# is published right now", not "the last value is still live". Serving
|
||||||
|
# the old cache here would resurrect a phone that deliberately cleared
|
||||||
|
# its alarm, so the fetch returns None and leaves the cache untouched.
|
||||||
|
_configured_transport(monkeypatch, tmp_path)
|
||||||
|
write_synced_logs_cache(_LOGS)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"wake_alarm._sync_transport._read_published", lambda _client: []
|
||||||
|
)
|
||||||
|
assert fetch_firebase_logs() is None
|
||||||
|
assert read_synced_logs_cache() == _LOGS
|
||||||
|
|
||||||
|
|
||||||
|
def test_weight_offline_comes_from_the_cache(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
# The reader half of offline-first: with the network down, the newest
|
||||||
|
# known weigh-in is still the one last synced, not "none".
|
||||||
|
_configured_transport(monkeypatch, tmp_path)
|
||||||
|
log = json.dumps(
|
||||||
|
{
|
||||||
|
"alarm": {
|
||||||
|
"fields": {
|
||||||
|
"latest_weight_kg": [
|
||||||
|
{"date": "2026-11-26", "kg": 81.5},
|
||||||
|
"2026-11-26T07:00:00.000Z-0-device-a",
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
write_synced_logs_cache([("device-a", log)])
|
||||||
|
|
||||||
|
def _fail(_client: object) -> NoReturn:
|
||||||
|
msg = "offline"
|
||||||
|
raise RemoteSyncError(msg)
|
||||||
|
|
||||||
|
monkeypatch.setattr("wake_alarm._sync_transport._read_published", _fail)
|
||||||
|
from wake_alarm._weight import latest_weight
|
||||||
|
|
||||||
|
weight = latest_weight()
|
||||||
|
assert weight is not None
|
||||||
|
assert (weight.date, weight.kg) == ("2026-11-26", 81.5)
|
||||||
Loading…
Reference in New Issue
Block a user