mirror of
https://github.com/kuhyx/wake-alarm.git
synced 2026-11-29 14:03:24 +01:00
Compare commits
28 Commits
v1.0.0-bui
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| fa3d41ef4a | |||
| d23752d369 | |||
| 2c41e41b33 | |||
| 295d93c7e7 | |||
| af503f465f | |||
| 10625bd29f | |||
| 4e946483f5 | |||
| 0059d44571 | |||
| be45e5969a | |||
| 0432a9968f | |||
| 00cc8ca223 | |||
| 6be954afd4 | |||
| 032358cc03 | |||
| 9d98a57909 | |||
| 96e4388297 | |||
| 65df7f6682 | |||
| 1df4f64393 | |||
| 8253836612 | |||
| 83e1e158fd | |||
| 0d66b64fb5 | |||
| df314d5dbe | |||
| 69cfc6270b | |||
| 8c511c148c | |||
| 35d6d07d8e | |||
| 0781c42222 | |||
| 7a2340bbf8 | |||
| cf0d243ffd | |||
| 863b94a7d5 |
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.12.0#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.1#subdirectory=kuhy_credit
|
|
||||||
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays
|
|
||||||
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.4#subdirectory=sickdays
|
|
||||||
# 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.
|
||||||
|
|||||||
26
AGENTS.md
26
AGENTS.md
@ -15,6 +15,10 @@ two pieces came back, because the phone **cannot** ring while powered off: a
|
|||||||
temporary escape hatch (until 2026-10-15). All of it, and the data contract
|
temporary escape hatch (until 2026-10-15). All of it, and the data contract
|
||||||
the phone, PC and focus-owner share: **`DOCS-wake-enforcement.md`**. Anything
|
the phone, PC and focus-owner share: **`DOCS-wake-enforcement.md`**. Anything
|
||||||
else from the old PC alarm still needs a reason the phone can't do it.
|
else from the old PC alarm still needs a reason the phone can't do it.
|
||||||
|
**Bypasses** (launcher "Pause app" silenced the ring 11-20 and 11-22):
|
||||||
|
focus-owner pins the enforcement apps, WakeAlarm is a device admin, and a
|
||||||
|
pause, admin removal, revoked permission or killed ring that gets through is a
|
||||||
|
miss plus an immediate PC ring: **`DOCS-bypass.md`**.
|
||||||
|
|
||||||
## The dismiss sequence (phone)
|
## The dismiss sequence (phone)
|
||||||
|
|
||||||
@ -71,7 +75,7 @@ clock, and everything that is a hard crash or a silent no-ring:
|
|||||||
does not ring: `AlarmReceiver` checks a native cache Dart rewrites after every
|
does not ring: `AlarmReceiver` checks a native cache Dart rewrites after every
|
||||||
mark/release/sync. Picker, cache, fail-closed contract: **`DOCS-free-days.md`**.
|
mark/release/sync. Picker, cache, fail-closed contract: **`DOCS-free-days.md`**.
|
||||||
Sick days (`~/src/utils/sickdays`, never a free day): phone + pre-alarm sync
|
Sick days (`~/src/utils/sickdays`, never a free day): phone + pre-alarm sync
|
||||||
**`DOCS-sick-days.md`**, PC **`DOCS-wake-enforcement.md`**.
|
**`DOCS-sick-days.md`**, PC **`DOCS-sick-days-pc.md`**.
|
||||||
|
|
||||||
## Scheduling — a per-minute timer
|
## Scheduling — a per-minute timer
|
||||||
|
|
||||||
@ -197,16 +201,13 @@ old `/usr/local/bin/shutdown` wrapper wherever one survives. `install.sh` calls
|
|||||||
installing** — renaming or deleting it breaks a fresh install. That call is
|
installing** — renaming or deleting it breaks a fresh install. That call is
|
||||||
non-fatal and gated on `sudo -n`: the cleanup needs root, and a hard failure
|
non-fatal and gated on `sudo -n`: the cleanup needs root, and a hard failure
|
||||||
would abort an install that had already placed the package and the timer.
|
would abort an install that had already placed the package and the timer.
|
||||||
|
**`/etc/sudoers.d/wake-alarm` stays even after a full uninstall:** the RTC
|
||||||
**`/etc/sudoers.d/wake-alarm` is deliberately left in place** even by a full
|
self-wake's `rtcwake` and the root ring unit's `systemctl` lines live there.
|
||||||
uninstall. Since 2026-10-01 it is live again: the RTC self-wake's `rtcwake`
|
|
||||||
and the root ring unit's `systemctl start|stop` lines live there.
|
|
||||||
|
|
||||||
## Operational gotchas
|
## Operational gotchas
|
||||||
|
|
||||||
- **`wake_state.json` is runtime state, not tracked.** It holds the
|
- **`wake_state.json` is runtime state, not tracked** (the HMAC-signed
|
||||||
HMAC-signed once-per-day latch. It was accidentally committed in the
|
once-per-day latch). It was once committed in the monorepo; keep it ignored.
|
||||||
monorepo and must stay gitignored here.
|
|
||||||
- **`WAKE_STATE_FILE` is redirected in `tests/conftest.py`, not per-file.** A
|
- **`WAKE_STATE_FILE` is redirected in `tests/conftest.py`, not per-file.** A
|
||||||
per-file redirect gets forgotten when a new writer appears (`_trigger` was
|
per-file redirect gets forgotten when a new writer appears (`_trigger` was
|
||||||
one), and the failure is silent: a green suite that stamped the live file.
|
one), and the failure is silent: a green suite that stamped the live file.
|
||||||
@ -216,9 +217,9 @@ and the root ring unit's `systemctl start|stop` 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
|
||||||
@ -239,8 +240,7 @@ alarm). The dev venv lacks `gatelock`: anything importing `_state` (incl.
|
|||||||
- Don't point the trigger at anything but `morning-routine.service` (or the
|
- Don't point the trigger at anything but `morning-routine.service` (or the
|
||||||
workout lock never runs), don't remove its once-per-day latch, and don't
|
workout lock never runs), don't remove its once-per-day latch, and don't
|
||||||
raise the log level of `_sync`'s degraded-read paths.
|
raise the log level of `_sync`'s degraded-read paths.
|
||||||
- Don't let the bypass skip the walk, and don't add a challenge kind that
|
- Don't let the bypass skip the walk or add a challenge that hides its prompt.
|
||||||
hides its own prompt.
|
|
||||||
- Don't close the ring screen on dismiss when a session should follow, don't
|
- Don't close the ring screen on dismiss when a session should follow, don't
|
||||||
add a re-ring cancel beyond the session's own `finishSession`, and don't
|
add a re-ring cancel beyond the session's own `finishSession`, and don't
|
||||||
restore a re-ring instant that has passed (BOOT_COMPLETED replays on launch).
|
restore a re-ring instant that has passed (BOOT_COMPLETED replays on launch).
|
||||||
|
|||||||
245
DOCS-bypass.md
Normal file
245
DOCS-bypass.md
Normal file
@ -0,0 +1,245 @@
|
|||||||
|
# Bypasses of the alarm (2026-11-22)
|
||||||
|
|
||||||
|
On 2026-11-20 and 11-22 kuhy long-pressed WakeAlarm on the home screen and
|
||||||
|
tapped "Wstrzymaj aplikację" (Digital Wellbeing's *Pause app*). The pause
|
||||||
|
suspended the app, the ring stopped, and he went back to sleep. This file
|
||||||
|
covers the three layers that now stop that, what counts as a bypass when
|
||||||
|
one gets through anyway, and what a bypass costs.
|
||||||
|
|
||||||
|
## Layer 1: the pause is refused (focus-owner, `~/src/phone-focus-mode`)
|
||||||
|
|
||||||
|
Every focus-owner pass, for the eight enforcement apps in
|
||||||
|
`focus_policy/packages.py` `ENFORCEMENT_PACKAGES` (wake_alarm_sync,
|
||||||
|
workout_app, diet_guard_app, leetcode_guard, book_guard_app, home_guard,
|
||||||
|
daily_limits, habit_stack):
|
||||||
|
|
||||||
|
- `setUserControlDisabledPackages`: Android refuses to suspend them
|
||||||
|
(`Cannot suspend package ...: protected package`), and Settings' Force stop
|
||||||
|
and Clear storage are greyed out. `am force-stop` and `pm clear` are refused
|
||||||
|
too; `adb install -r` still works, so deploys are unaffected.
|
||||||
|
- `setUninstallBlocked`.
|
||||||
|
- `setPermissionGrantState(POST_NOTIFICATIONS, GRANTED)`. The full-screen
|
||||||
|
intent is an app-op and cannot be pinned (`setPermissionGrantState`
|
||||||
|
returns false), so revoking it is a bypass instead (below).
|
||||||
|
- A suspension found anyway is lifted. Measured on the emulator: a pause
|
||||||
|
made before the pins were applied was lifted 4.3 s later, by the pass that
|
||||||
|
wake_alarm's `UNSUSPEND` signal started.
|
||||||
|
|
||||||
|
Digital Wellbeing itself is hidden in every state (`ALWAYS_BLOCKED_PACKAGES`),
|
||||||
|
so the Pause button is gone as well.
|
||||||
|
|
||||||
|
## Layer 2: WakeAlarm is a device admin
|
||||||
|
|
||||||
|
`WakeAdminReceiver` (`res/xml/wake_admin.xml`, no policies). Android refuses
|
||||||
|
to suspend an active admin. It is activated over adb, never by a tap:
|
||||||
|
|
||||||
|
adb shell dpm set-active-admin com.kuhy.wake_alarm_sync/.WakeAdminReceiver
|
||||||
|
|
||||||
|
Deactivating it in Settings cannot be prevented, so it is a bypass.
|
||||||
|
|
||||||
|
## Layer 3: what counts as a bypass (`Bypass.kt`)
|
||||||
|
|
||||||
|
A bypass counts only on a ringing day (an alarm is stored, not a free or sick
|
||||||
|
day, the ring did not stand down) while the ring or the morning session is
|
||||||
|
live. Causes (`bypass` phone event, `data.cause`):
|
||||||
|
|
||||||
|
| cause | seen by |
|
||||||
|
|---|---|
|
||||||
|
| `suspended` | `SuspendReceiver` on `MY_PACKAGE_SUSPENDED`; also sends focus-owner `UNSUSPEND` |
|
||||||
|
| `admin_removed` | `WakeAdminReceiver.onDisabled` |
|
||||||
|
| `notifications_off` | ring start and every launch (`Bypass.checkOnLaunch`) |
|
||||||
|
| `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 |
|
||||||
|
| `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`
|
||||||
|
write, so a ring fired by an older build (11-22, paused, never dismissed) does
|
||||||
|
not count the first time the new build starts. The same cause twice within
|
||||||
|
a minute is recorded once (both activities run the launch check).
|
||||||
|
|
||||||
|
## What a bypass costs
|
||||||
|
|
||||||
|
- **A miss** (`StickCheck`), on any weekday, at once, whatever the dismiss
|
||||||
|
does afterwards: a lockdown through the next day, stacking. The streak
|
||||||
|
links penalty days, stick days (Tue–Thu) plus bypass days; free and sick
|
||||||
|
days are skipped. A plain late dismiss on Fri–Mon still changes nothing.
|
||||||
|
A later check or bypass on the day already penalised sends the stored
|
||||||
|
lockdown (`locked_through`, if today or later) again, same date and
|
||||||
|
streak, so a signal focus-owner missed (not running, not yet Device
|
||||||
|
Owner) still lands.
|
||||||
|
- **The phone rings again** (`Bypass.ringAgain`). During a session it is a
|
||||||
|
re-ring: only the full dismiss sequence silences it and `re_rings` goes up
|
||||||
|
by one when it does (`SessionHandoff.afterDismiss`). It is recorded as
|
||||||
|
`bypass:<cause>` in `re_ring_reasons` (`bypass:fsi_revoked`,
|
||||||
|
`bypass:suspended`, ...): `Bypass.record` stamps the cause
|
||||||
|
(`BypassReRing`, dated) before it restarts the ring, and the session takes
|
||||||
|
it once over `takeBypassReRing`, on the screen's tick or on the dismiss. A
|
||||||
|
bypass while a deadline re-ring already sounds stamps nothing: one sound,
|
||||||
|
one re-ring, reason `deadline:<leg>`; the `bypass` event, its publish and
|
||||||
|
the lockdown still happen.
|
||||||
|
- **The PC rings** (`_fallback_policy`, reason `bypass`). The phone pushes
|
||||||
|
the event at once through the headless `publishNowMain` engine. The PC
|
||||||
|
rings from the bypass for up to 30 min (`FALLBACK_RING_CAP` from the
|
||||||
|
bypass, not the day's cap), outside the window, after a session started
|
||||||
|
and after the day's own ring was used. It stops on a `dismissed` newer
|
||||||
|
than the bypass, which the phone also pushes at once. Free and sick days
|
||||||
|
and an escape stand it down. The tick reads the phone until `A + 4 h`
|
||||||
|
(`BYPASS_WATCH`); the fallback timer ticks 04:00-11:59 (and 21:xx, below).
|
||||||
|
To see these answers without a backend, `_fallback --dry-run --at <instant>
|
||||||
|
--published <file>` reads the phone's logs from a JSON list of
|
||||||
|
`[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
|
||||||
|
|
||||||
|
The AVD never signs in to prod. A probe build with
|
||||||
|
`--dart-define=WAKE_SYNC_EMULATOR=http://10.0.2.2:9000` syncs to the
|
||||||
|
Firebase RTDB emulator on the PC instead of prod Firebase *and* the GitHub
|
||||||
|
mirror (`sync_emulator.dart`; plain HTTP is allowed to `10.0.2.2` in the
|
||||||
|
debug manifest only). Release builds never set the define.
|
||||||
|
|
||||||
|
1. `systemd-run --user --collect --unit=wa-rtdb-emu /usr/bin/java -jar
|
||||||
|
~/.cache/firebase/emulators/firebase-database-emulator-v4.11.2.jar --host
|
||||||
|
127.0.0.1 --port 9000` (one default namespace; `auth=owner` is admin).
|
||||||
|
2. Write a dummy passphrase to `files/passphrase` under the app's
|
||||||
|
`Android/data/<pkg>/` dir; the probe moves it into the keystore on launch
|
||||||
|
(`probe_passphrase.dart`). Without one every push is `sync locked`.
|
||||||
|
A probe's `-t` file must re-export the headless entrypoints
|
||||||
|
(`publishNowMain`, ...): Kotlin resolves them by name in the root library,
|
||||||
|
and without them the bypass publish never ran.
|
||||||
|
3. After the bypass: `HOME=<scratch with .config/crdt-sync/password>
|
||||||
|
PYTHONUSERBASE=~/.local /usr/bin/python3 scripts/emu_published.py
|
||||||
|
http://127.0.0.1:9000 out.json`, then `_fallback --dry-run --at <instant>
|
||||||
|
--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
|
||||||
|
|
||||||
|
Android lets nothing lock "All WakeAlarm notifications", and with them off
|
||||||
|
the ring has no screen. The ring-time check above still counts it as a
|
||||||
|
bypass; this one catches it the evening before, while kuhy can still fix it.
|
||||||
|
|
||||||
|
- **Phone.** `NotifState` (the same rule `Bypass.checkPermissions` uses: app
|
||||||
|
notifications off, or the ring channel at `IMPORTANCE_NONE`) logs a
|
||||||
|
`notifications` event, data `enabled` (bool) and `trigger`, and pushes it
|
||||||
|
at once through `publishNowMain`. Triggers: an exact alarm at 21:00
|
||||||
|
(`NotifAlarm`, request code 1007, `evening`; re-armed by its receiver, by
|
||||||
|
every `AlarmScheduler.schedule`, boot and the watchdog, always the next
|
||||||
|
future 21:00) and `NotifBlockReceiver` on `APP_BLOCK_STATE_CHANGED` /
|
||||||
|
`NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED` for the ring channel
|
||||||
|
(`app_block`, `channel_block`). Both receivers hold the broadcast open
|
||||||
|
(`NotifRules.holdMs`: 8 s for a foreground broadcast, whose ANR budget is
|
||||||
|
10 s, else 25 s) so the headless engine is not frozen mid-push.
|
||||||
|
- **PC** (`_fallback_evening`, rule in `_evening_policy`). The fallback
|
||||||
|
timer also ticks 21:00-21:59; those ticks skip the morning code. When
|
||||||
|
today's newest `notifications` event says off, the PC rings
|
||||||
|
(`notifications_off`) until a newer one says on, or 30 min
|
||||||
|
(`FALLBACK_RING_CAP`) from the evening's first ring. The cap has its own
|
||||||
|
latch, `evening_ring.json`, so it never eats the morning's or a bypass's.
|
||||||
|
The hour gates only *starting*; a ring started at 21:50 runs its 30 min.
|
||||||
|
- **No ring** when tomorrow is a free or sick day (`free_tomorrow`,
|
||||||
|
`sick_tomorrow`), when no event was published today (phone off), or when
|
||||||
|
Firebase does not answer at the tick. An unreachable poll mid-ring keeps
|
||||||
|
ringing. Events: `evening_tick`, `evening_ring_start`, `evening_ring_stop`
|
||||||
|
(never the morning's names, so the audit does not count them).
|
||||||
|
|
||||||
|
## The monitors ring too
|
||||||
|
|
||||||
|
kuhy turns the speakers off at the knob for the night, so the 11-22 fallback
|
||||||
|
ring played 30 min into silence. Both rings now also play to every connected
|
||||||
|
monitor (ELD name in `aplay -l`: `G27Q` on HDMI, `VG28UQL1A` on DP, both on
|
||||||
|
the NVidia card):
|
||||||
|
|
||||||
|
- root path: `ring_alsa.sh` starts one `aplay` loop per monitor, IEC958
|
||||||
|
unmuted;
|
||||||
|
- PipeWire path: `_ring_monitors.MonitorLoops` runs
|
||||||
|
`ring_alsa.sh --monitors` as the user beside `pw-play` (PipeWire does not
|
||||||
|
expose the NVidia outputs).
|
||||||
|
|
||||||
|
Each monitor logs one `ring_sink sink=<name> ... result=ok|error` line.
|
||||||
|
|
||||||
|
**Silent probe.** `ring_alsa.sh --probe` writes two seconds of digital
|
||||||
|
silence to each monitor with IEC958 muted (restored afterwards) and logs one
|
||||||
|
`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
|
||||||
|
graphical session (the state a fallback ring meets), and writes
|
||||||
|
`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`
|
||||||
|
(`scripts/vmbox/guest_cases_monitors.sh`).
|
||||||
|
|
||||||
|
## Found on the way: lockdown signals never arrived
|
||||||
|
|
||||||
|
focus-owner defined `SIGNAL_LOCKDOWN` but did not request it, and wake_alarm
|
||||||
|
sends with it as the receiver permission, so every `LOCKDOWN_UNTIL_EOD` and
|
||||||
|
`LIFT_LOCKDOWN` was dropped. focus-owner now holds it (eeb0def).
|
||||||
@ -61,7 +61,9 @@ the first leg by itself — there is nothing to walk to.
|
|||||||
of recreating it.
|
of recreating it.
|
||||||
- **Silencing a re-ring is the full dismiss sequence**: tag 1, the walk,
|
- **Silencing a re-ring is the full dismiss sequence**: tag 1, the walk,
|
||||||
tag 2, three questions. The ring screen's `_finishDismiss` sees a live
|
tag 2, three questions. The ring screen's `_finishDismiss` sees a live
|
||||||
session for today and resumes it with `reRings + 1`.
|
session for today and resumes it with `reRings + 1`. `re_ring_reasons`
|
||||||
|
says why: `deadline:<leg>`, or `bypass:<cause>` when a bypass restarted
|
||||||
|
the ring (`DOCS-bypass.md`).
|
||||||
- **A silent buzz 3 min before each deadline** (`SessionWarn.kt`, request
|
- **A silent buzz 3 min before each deadline** (`SessionWarn.kt`, request
|
||||||
code 1004), armed and cleared only with the re-ring.
|
code 1004), armed and cleared only with the re-ring.
|
||||||
- **One re-ring per leg.** After a deadline re-ring is dismissed the leg is
|
- **One re-ring per leg.** After a deadline re-ring is dismissed the leg is
|
||||||
@ -182,3 +184,24 @@ leg and during a ring. `flutter build apk --debug --target`
|
|||||||
produced an APK that ran `main.dart` instead; `flutter run -t` did not.
|
produced an APK that ran `main.dart` instead; `flutter run -t` did not.
|
||||||
The phone remains the only test of the AlarmManager deadline with the
|
The phone remains the only test of the AlarmManager deadline with the
|
||||||
screen off and the app swiped away.
|
screen off and the app swiped away.
|
||||||
|
|
||||||
|
A clean-tree `flutter build apk --debug -t lib/main_session_probe.dart`
|
||||||
|
held a build slot for 62 s (board build, load ~18). Measured back to back
|
||||||
|
on 2026-11-22 at load ~12: 54.5 s at the old HEAD, 41.5 s and 35.7 s with
|
||||||
|
these three changes (59.4 s before them at load ~18):
|
||||||
|
|
||||||
|
- `org.gradle.caching=true` (`android/gradle.properties`): a fresh worktree
|
||||||
|
pulls plugin, Kotlin and dex outputs from `~/.gradle/caches/build-cache-1`.
|
||||||
|
- `app/build.gradle.kts` runs `compileFlutterBuild<Variant>` (the ~20 s Dart
|
||||||
|
kernel compile) before `pre<Variant>Build`. Gradle runs one task per
|
||||||
|
project at a time without the configuration cache, which FlutterTask does
|
||||||
|
not support; the compile used to start 8 s late and block Kotlin, dex and
|
||||||
|
manifests behind it.
|
||||||
|
- Debug APKs drop `lib/armeabi-v7a`, `lib/x86` and the engine's Vulkan
|
||||||
|
validation layer: debug installs only reach the arm64 Pixel and the
|
||||||
|
x86_64 emulator. The APK shrinks from 182 MB to 134 MB, and merging and
|
||||||
|
zipping it gets faster. Release keeps every ABI.
|
||||||
|
|
||||||
|
What stays fixed: ~20 s of Gradle start and configuration (`~/.gradle`
|
||||||
|
sets `daemon=false`, so every build pays a cold JVM) and the Dart compile
|
||||||
|
of a 106 MB `app.dill`.
|
||||||
|
|||||||
72
DOCS-sick-days-pc.md
Normal file
72
DOCS-sick-days-pc.md
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
# Sick days -- PC side (2026-10-16)
|
||||||
|
|
||||||
|
Split out of `DOCS-wake-enforcement.md` (250-line gate). The phone half and
|
||||||
|
the pool itself: `DOCS-sick-days.md`.
|
||||||
|
|
||||||
|
|
||||||
|
A sick day (that does not keep `alarm`, see below) is a date in the shared `sickdays` pool (`~/src/utils/sickdays`):
|
||||||
|
uncapped, no reason, today or later, and **not a free day** -- its own pool,
|
||||||
|
its own reason strings (`sick_day` / `sick day`). On a sick day `D` (the
|
||||||
|
alarm's day, so the RTC asks about *tomorrow* the evening before):
|
||||||
|
|
||||||
|
| piece | on a sick day |
|
||||||
|
|---|---|
|
||||||
|
| fallback ring | never starts; a ring in progress stops (`stop_reason` `sick_day`) |
|
||||||
|
| RTC self-wake | not armed for `D`; an alarm we armed for `D` is disarmed (`rtc_skip` / `rtc_disarmed`, reason `sick day`) |
|
||||||
|
| trigger | `morning-routine.service` is not started (`sick day`), like a free day |
|
||||||
|
| workday penalty | never written for `D`; one *issued* on `D` before `D` was marked is deleted (`penalty_cancelled`, `cause: sick_day`) by the next `_session --refresh` or `_rtc --arm` |
|
||||||
|
| `morning_session.json` | unchanged: it only *grants* exemptions, and every locker stands down on a sick day by its own check |
|
||||||
|
| audit | RTC / up-by-A / ring / lockdown checks are n/a; a penalty for `D` on disk or a `lockdown_sent` for a miss on `D` is flagged |
|
||||||
|
|
||||||
|
All of it lives behind `wake_alarm/_sick.py`. **Fail closed:** an
|
||||||
|
unreadable pool, or `sickdays` not importable under `/usr/bin/python`, is
|
||||||
|
"not sick" -- enforcement runs.
|
||||||
|
|
||||||
|
**Sync.** The decisions read the local pool, and the act modes pull it from
|
||||||
|
Firebase first (`sickdays.sync_quietly()`), because the sickdays sync timer
|
||||||
|
alone cannot be trusted at the moment that matters: it is a monotonic
|
||||||
|
15-minute timer, paused during hibernate and with no `Persistent` catch-up,
|
||||||
|
so right after the RTC resume the pool can be an interval stale. Pulled:
|
||||||
|
`_rtc --arm` when the target is a stick day that is not free; the fallback
|
||||||
|
tick whenever it already goes to the network (`A-5 .. A+45`, and every poll
|
||||||
|
of a ring in progress, so a day marked sick mid-ring stops it); the day's
|
||||||
|
first penalty write. The trigger reads only the local file -- the fallback
|
||||||
|
has pulled from `A-5`. `--dry-run` / `--show` never pull (a pull rewrites
|
||||||
|
the pool file).
|
||||||
|
|
||||||
|
**Other readers of `workday_penalty.json`** (screen-locker, leetcode-guard)
|
||||||
|
must treat the file as void when **either** its `issued_date` is a day the
|
||||||
|
*alarm* stands down on (`sickdays.stands_down(sickdays.LOCKER_ALARM,
|
||||||
|
date.fromisoformat(issued_date))`) **or** its `penalty_date` is a day *their
|
||||||
|
own* locker stands down on (`stands_down(LOCKER_WORKOUT, ...)` for
|
||||||
|
screen-locker, `LOCKER_LEETCODE` for leetcode-guard). `issued_date` covers a
|
||||||
|
miss at 08:15 marked sick at 14:00 -- the deletion runs on the next RTC tick
|
||||||
|
(<= 15 min) or the next morning's refresh, and a reader must not depend on
|
||||||
|
that; the ring day belongs to the alarm switch, the penalty day to whatever
|
||||||
|
the penalty charges.
|
||||||
|
|
||||||
|
**Keeping the alarm (`sickdays` 0.2.0).** A sick day may keep lockers
|
||||||
|
(`sickdays add --keep alarm`). Everything in the table above is the single
|
||||||
|
`alarm` switch (`_sick.alarm_stands_down`): on a sick day that keeps `alarm`
|
||||||
|
the fallback ring, RTC self-wake, trigger, workday penalty (written, and not
|
||||||
|
retracted) and audit behave exactly as on a normal stick day.
|
||||||
|
|
||||||
|
**Phone, assumed name:** the phone's `alarm_fired` on a sick day carries
|
||||||
|
`data.reason = "sick_day"` (by analogy with `free_day`); the audit treats
|
||||||
|
it as not the morning's ring.
|
||||||
|
|
||||||
|
**A stand-down latches at ring time (fixed 2026-11-16).** On 2026-11-11 the
|
||||||
|
07:40 ring stood down for a sick day (`alarm_fired reason=sick_day`), the
|
||||||
|
phone cleared the mark at 11:38, and the 19:31 stick check re-read the cache,
|
||||||
|
found a normal Wednesday with no dismissal and sent a lockdown. That punished
|
||||||
|
a day whose alarm never rang, so no dismiss was possible. `AlarmReceiver` now
|
||||||
|
records the skip (`RingWatch.markSkipped`, a `DateHistory` per reason), and
|
||||||
|
`StickCheck.decideDay` returns `sick_day`/`free_day` for a latched day even
|
||||||
|
after a clear. The streak look-back skips it too. A phone that was off at A
|
||||||
|
latches nothing, so a clear still makes that day a stick day (hole 1).
|
||||||
|
Tests: `StickCheckSickTest`.
|
||||||
|
|
||||||
|
**Still open: on-device check.** At the next real miss (Tue/Wed/Thu), right
|
||||||
|
after 09:30 run `adb -s 23181JEGR08034 logcat -d | grep -E
|
||||||
|
"LOCKDOWN_ACTIVATED|WORKDAY_LOCKDOWN"` (read-only) and confirm
|
||||||
|
`LOCKDOWN_ACTIVATED` is followed by `WORKDAY_LOCKDOWN`.
|
||||||
@ -10,7 +10,7 @@ nothing ring-related is recorded -- **unless the day keeps the alarm**.
|
|||||||
Since sickdays 0.2.0 a sick day carries a per-locker `keep` set (README
|
Since sickdays 0.2.0 a sick day carries a per-locker `keep` set (README
|
||||||
"keep (0.2.0)"): a kept locker behaves exactly as on a normal day, every other
|
"keep (0.2.0)"): a kept locker behaves exactly as on a normal day, every other
|
||||||
one stands down. This app is the `alarm` locker (ring, PC fallback ring, RTC
|
one stands down. This app is the `alarm` locker (ring, PC fallback ring, RTC
|
||||||
self-wake, missed-alarm penalty / stick, morning routine). It is **not** a free day: separate pool,
|
self-wake, missed-alarm penalty / stick, morning routine; PC side: `DOCS-sick-days-pc.md`). It is **not** a free day: separate pool,
|
||||||
separate RTDB node (`sickdays-sync/devices`), separate native cache, separate
|
separate RTDB node (`sickdays-sync/devices`), separate native cache, separate
|
||||||
screen, and every log line and event says `sick_day`.
|
screen, and every log line and event says `sick_day`.
|
||||||
|
|
||||||
|
|||||||
@ -30,6 +30,10 @@ trigger). Not on a free day, not on a sick day (below). Per-minute tick, `A-5min
|
|||||||
| `now ≥ A + 2 min` and no `ring_started` for today | ring — `phone_silent` |
|
| `now ≥ A + 2 min` and no `ring_started` for today | ring — `phone_silent` |
|
||||||
| `now ≥ A + 15 min` (`SESSION_NONE_GRACE`) | ring — `no_session` |
|
| `now ≥ A + 15 min` (`SESSION_NONE_GRACE`) | ring — `no_session` |
|
||||||
|
|
||||||
|
A **bypass** (the app paused, its admin removed, a permission revoked, the
|
||||||
|
ring killed) rings before this table, outside the window, until a newer
|
||||||
|
dismiss or 30 min: **`DOCS-bypass.md`**.
|
||||||
|
|
||||||
A ring stops on: session start, escape, or the 30-min cap. Firebase
|
A ring stops on: session start, escape, or the 30-min cap. Firebase
|
||||||
unreachable counts as "no ping, no session" (fail toward ringing) and is
|
unreachable counts as "no ping, no session" (fail toward ringing) and is
|
||||||
logged as `firebase_unreachable`. While ringing, stop conditions are polled
|
logged as `firebase_unreachable`. While ringing, stop conditions are polled
|
||||||
@ -50,9 +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`).
|
||||||
|
- 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)
|
||||||
|
|
||||||
@ -97,72 +105,8 @@ wake-alarm, todo) — narrower than the night list.
|
|||||||
|
|
||||||
### Sick days (PC side, 2026-10-16)
|
### Sick days (PC side, 2026-10-16)
|
||||||
|
|
||||||
A sick day (that does not keep `alarm`, see below) is a date in the shared `sickdays` pool (`~/src/utils/sickdays`):
|
A sick day stands down the fallback ring, RTC self-wake, trigger, workday
|
||||||
uncapped, no reason, today or later, and **not a free day** -- its own pool,
|
penalty and audit: **`DOCS-sick-days-pc.md`**.
|
||||||
its own reason strings (`sick_day` / `sick day`). On a sick day `D` (the
|
|
||||||
alarm's day, so the RTC asks about *tomorrow* the evening before):
|
|
||||||
|
|
||||||
| piece | on a sick day |
|
|
||||||
|---|---|
|
|
||||||
| fallback ring | never starts; a ring in progress stops (`stop_reason` `sick_day`) |
|
|
||||||
| RTC self-wake | not armed for `D`; an alarm we armed for `D` is disarmed (`rtc_skip` / `rtc_disarmed`, reason `sick day`) |
|
|
||||||
| trigger | `morning-routine.service` is not started (`sick day`), like a free day |
|
|
||||||
| workday penalty | never written for `D`; one *issued* on `D` before `D` was marked is deleted (`penalty_cancelled`, `cause: sick_day`) by the next `_session --refresh` or `_rtc --arm` |
|
|
||||||
| `morning_session.json` | unchanged: it only *grants* exemptions, and every locker stands down on a sick day by its own check |
|
|
||||||
| audit | RTC / up-by-A / ring / lockdown checks are n/a; a penalty for `D` on disk or a `lockdown_sent` for a miss on `D` is flagged |
|
|
||||||
|
|
||||||
All of it lives behind `wake_alarm/_sick.py`. **Fail closed:** an
|
|
||||||
unreadable pool, or `sickdays` not importable under `/usr/bin/python`, is
|
|
||||||
"not sick" -- enforcement runs.
|
|
||||||
|
|
||||||
**Sync.** The decisions read the local pool, and the act modes pull it from
|
|
||||||
Firebase first (`sickdays.sync_quietly()`), because the sickdays sync timer
|
|
||||||
alone cannot be trusted at the moment that matters: it is a monotonic
|
|
||||||
15-minute timer, paused during hibernate and with no `Persistent` catch-up,
|
|
||||||
so right after the RTC resume the pool can be an interval stale. Pulled:
|
|
||||||
`_rtc --arm` when the target is a stick day that is not free; the fallback
|
|
||||||
tick whenever it already goes to the network (`A-5 .. A+45`, and every poll
|
|
||||||
of a ring in progress, so a day marked sick mid-ring stops it); the day's
|
|
||||||
first penalty write. The trigger reads only the local file -- the fallback
|
|
||||||
has pulled from `A-5`. `--dry-run` / `--show` never pull (a pull rewrites
|
|
||||||
the pool file).
|
|
||||||
|
|
||||||
**Other readers of `workday_penalty.json`** (screen-locker, leetcode-guard)
|
|
||||||
must treat the file as void when **either** its `issued_date` is a day the
|
|
||||||
*alarm* stands down on (`sickdays.stands_down(sickdays.LOCKER_ALARM,
|
|
||||||
date.fromisoformat(issued_date))`) **or** its `penalty_date` is a day *their
|
|
||||||
own* locker stands down on (`stands_down(LOCKER_WORKOUT, ...)` for
|
|
||||||
screen-locker, `LOCKER_LEETCODE` for leetcode-guard). `issued_date` covers a
|
|
||||||
miss at 08:15 marked sick at 14:00 -- the deletion runs on the next RTC tick
|
|
||||||
(<= 15 min) or the next morning's refresh, and a reader must not depend on
|
|
||||||
that; the ring day belongs to the alarm switch, the penalty day to whatever
|
|
||||||
the penalty charges.
|
|
||||||
|
|
||||||
**Keeping the alarm (`sickdays` 0.2.0).** A sick day may keep lockers
|
|
||||||
(`sickdays add --keep alarm`). Everything in the table above is the single
|
|
||||||
`alarm` switch (`_sick.alarm_stands_down`): on a sick day that keeps `alarm`
|
|
||||||
the fallback ring, RTC self-wake, trigger, workday penalty (written, and not
|
|
||||||
retracted) and audit behave exactly as on a normal stick day.
|
|
||||||
|
|
||||||
**Phone, assumed name:** the phone's `alarm_fired` on a sick day carries
|
|
||||||
`data.reason = "sick_day"` (by analogy with `free_day`); the audit treats
|
|
||||||
it as not the morning's ring.
|
|
||||||
|
|
||||||
**A stand-down latches at ring time (fixed 2026-11-16).** On 2026-11-11 the
|
|
||||||
07:40 ring stood down for a sick day (`alarm_fired reason=sick_day`), the
|
|
||||||
phone cleared the mark at 11:38, and the 19:31 stick check re-read the cache,
|
|
||||||
found a normal Wednesday with no dismissal and sent a lockdown. That punished
|
|
||||||
a day whose alarm never rang, so no dismiss was possible. `AlarmReceiver` now
|
|
||||||
records the skip (`RingWatch.markSkipped`, a `DateHistory` per reason), and
|
|
||||||
`StickCheck.decideDay` returns `sick_day`/`free_day` for a latched day even
|
|
||||||
after a clear. The streak look-back skips it too. A phone that was off at A
|
|
||||||
latches nothing, so a clear still makes that day a stick day (hole 1).
|
|
||||||
Tests: `StickCheckSickTest`.
|
|
||||||
|
|
||||||
**Still open: on-device check.** At the next real miss (Tue/Wed/Thu), right
|
|
||||||
after 09:30 run `adb -s 23181JEGR08034 logcat -d | grep -E
|
|
||||||
"LOCKDOWN_ACTIVATED|WORKDAY_LOCKDOWN"` (read-only) and confirm
|
|
||||||
`LOCKDOWN_ACTIVATED` is followed by `WORKDAY_LOCKDOWN`.
|
|
||||||
|
|
||||||
### Escape hatch (until 2026-10-15 inclusive)
|
### Escape hatch (until 2026-10-15 inclusive)
|
||||||
|
|
||||||
@ -196,6 +140,7 @@ shown comes from Dart constants mirrored against the Python ones by
|
|||||||
- `com.kuhy.focus_owner.action.LOCKDOWN_UNTIL_EOD` — extra `until`
|
- `com.kuhy.focus_owner.action.LOCKDOWN_UNTIL_EOD` — extra `until`
|
||||||
(`YYYY-MM-DD`, inclusive). Missing extra = today (old senders keep working).
|
(`YYYY-MM-DD`, inclusive). Missing extra = today (old senders keep working).
|
||||||
- `com.kuhy.focus_owner.action.LIFT_LOCKDOWN` — clears any lockdown now.
|
- `com.kuhy.focus_owner.action.LIFT_LOCKDOWN` — clears any lockdown now.
|
||||||
|
- `com.kuhy.focus_owner.action.UNSUSPEND` — run a pass now (lifts a pause).
|
||||||
|
|
||||||
### PC files (`~/.local/state/wake_alarm/`)
|
### PC files (`~/.local/state/wake_alarm/`)
|
||||||
|
|
||||||
@ -212,8 +157,11 @@ Phone (`phone_events.kind`): `alarm_fired` (data: `reason` =
|
|||||||
`daily`|`rering`|`free_day`|`sick_day` — only `daily` is the morning's ring),
|
`daily`|`rering`|`free_day`|`sick_day` — only `daily` is the morning's ring),
|
||||||
`ring_screen_opened`, `ring_started_published` (data: `date`, `source` =
|
`ring_screen_opened`, `ring_started_published` (data: `date`, `source` =
|
||||||
`alarm`|`ring_screen`), `dismissed`, `stick_check` (data: `trigger` =
|
`alarm`|`ring_screen`), `dismissed`, `stick_check` (data: `trigger` =
|
||||||
`exact`|`boot`|`watchdog`, `date` judged, `verdict`, incl. `free_day`|`sick_day`), `lockdown_sent` (data:
|
`exact`|`boot`|`watchdog`, `date` judged, `verdict`, incl. `free_day`|`sick_day`), `bypass` (data: `cause`, `date`, `session`; `DOCS-bypass.md`),
|
||||||
`until`, `streak`), `lift_sent`, `escape_used`, `boot`.
|
`bypass_ignored`, `notifications` (data: `enabled`, `trigger` =
|
||||||
|
`evening`|`app_block`|`channel_block`; `DOCS-bypass.md`), `unsuspended`, `lockdown_sent` (data:
|
||||||
|
`until`, `streak`, `resend`: true when a day already penalised sent its
|
||||||
|
stored lockdown again), `lift_sent`, `escape_used`, `boot`.
|
||||||
|
|
||||||
`ring_started` is published twice over: a headless Dart engine started by
|
`ring_started` is published twice over: a headless Dart engine started by
|
||||||
`AlarmReceiver` at the fire (so a full-screen intent downgraded to a heads-up
|
`AlarmReceiver` at the fire (so a full-screen intent downgraded to a heads-up
|
||||||
@ -223,7 +171,8 @@ The A+15 check uses `setExactAndAllowWhileIdle` (falls back to
|
|||||||
system's next alarm. Boot/watchdog catch up on up to 5 unchecked past days.
|
system's next alarm. Boot/watchdog catch up on up to 5 unchecked past days.
|
||||||
|
|
||||||
PC (`events.jsonl` `event`): `fallback_tick` (only on decision change),
|
PC (`events.jsonl` `event`): `fallback_tick` (only on decision change),
|
||||||
`fallback_ring_start`, `fallback_ring_stop`, `ring_backend`, `rtc_armed`,
|
`fallback_ring_start`, `fallback_ring_stop`, `evening_tick`,
|
||||||
|
`evening_ring_start`, `evening_ring_stop`, `ring_backend`, `rtc_armed`,
|
||||||
`rtc_skip`, `firebase_unreachable`, `escape_seen`, `penalty_written`,
|
`rtc_skip`, `firebase_unreachable`, `escape_seen`, `penalty_written`,
|
||||||
`penalty_cancelled` (field `cause`: `escape` | `sick_day`), `audit_written`.
|
`penalty_cancelled` (field `cause`: `escape` | `sick_day`), `audit_written`.
|
||||||
|
|
||||||
|
|||||||
@ -57,6 +57,8 @@ readonly PC_DIR="$SCRIPT_DIR/scripts/pc"
|
|||||||
readonly WAV_DIR="/usr/local/share/wake-alarm"
|
readonly WAV_DIR="/usr/local/share/wake-alarm"
|
||||||
readonly RING_SCRIPT_DST="/usr/local/lib/wake-alarm/ring_alsa.sh"
|
readonly RING_SCRIPT_DST="/usr/local/lib/wake-alarm/ring_alsa.sh"
|
||||||
readonly ALSA_UNIT="wake-alarm-ring-alsa.service"
|
readonly ALSA_UNIT="wake-alarm-ring-alsa.service"
|
||||||
|
# The silent monitor check (wake_alarm/_ring_probe.py starts it once).
|
||||||
|
readonly PROBE_UNIT="wake-alarm-ring-probe.service"
|
||||||
readonly SUDOERS_FILE="/etc/sudoers.d/wake-alarm"
|
readonly SUDOERS_FILE="/etc/sudoers.d/wake-alarm"
|
||||||
readonly POWERKEY_DST="/etc/systemd/logind.conf.d/wake-alarm-powerkey.conf"
|
readonly POWERKEY_DST="/etc/systemd/logind.conf.d/wake-alarm-powerkey.conf"
|
||||||
INSTALL_USER="$(id -un)"
|
INSTALL_USER="$(id -un)"
|
||||||
@ -64,6 +66,7 @@ readonly INSTALL_USER
|
|||||||
readonly SUDOERS_LINES=(
|
readonly SUDOERS_LINES=(
|
||||||
"$INSTALL_USER ALL=(root) NOPASSWD: /usr/bin/systemctl start $ALSA_UNIT"
|
"$INSTALL_USER ALL=(root) NOPASSWD: /usr/bin/systemctl start $ALSA_UNIT"
|
||||||
"$INSTALL_USER ALL=(root) NOPASSWD: /usr/bin/systemctl stop $ALSA_UNIT"
|
"$INSTALL_USER ALL=(root) NOPASSWD: /usr/bin/systemctl stop $ALSA_UNIT"
|
||||||
|
"$INSTALL_USER ALL=(root) NOPASSWD: /usr/bin/systemctl start $PROBE_UNIT"
|
||||||
)
|
)
|
||||||
|
|
||||||
TEMP_DIR=""
|
TEMP_DIR=""
|
||||||
@ -84,8 +87,9 @@ install_ring_audio() {
|
|||||||
sudo install -D -m 0755 "$PC_DIR/ring_alsa.sh" "$RING_SCRIPT_DST"
|
sudo install -D -m 0755 "$PC_DIR/ring_alsa.sh" "$RING_SCRIPT_DST"
|
||||||
sed "s/@USER@/$INSTALL_USER/" "$PC_DIR/$ALSA_UNIT" >"$TEMP_DIR/$ALSA_UNIT"
|
sed "s/@USER@/$INSTALL_USER/" "$PC_DIR/$ALSA_UNIT" >"$TEMP_DIR/$ALSA_UNIT"
|
||||||
sudo install -m 0644 "$TEMP_DIR/$ALSA_UNIT" "/etc/systemd/system/$ALSA_UNIT"
|
sudo install -m 0644 "$TEMP_DIR/$ALSA_UNIT" "/etc/systemd/system/$ALSA_UNIT"
|
||||||
|
sudo install -m 0644 "$PC_DIR/$PROBE_UNIT" "/etc/systemd/system/$PROBE_UNIT"
|
||||||
sudo systemctl daemon-reload
|
sudo systemctl daemon-reload
|
||||||
echo " Ring WAVs, $RING_SCRIPT_DST and $ALSA_UNIT installed."
|
echo " Ring WAVs, $RING_SCRIPT_DST, $ALSA_UNIT and $PROBE_UNIT installed."
|
||||||
}
|
}
|
||||||
|
|
||||||
install_sudoers() {
|
install_sudoers() {
|
||||||
@ -102,7 +106,7 @@ install_sudoers() {
|
|||||||
done
|
done
|
||||||
sudo visudo -cf "$merged" >/dev/null
|
sudo visudo -cf "$merged" >/dev/null
|
||||||
sudo install -m 0440 -o root -g root "$merged" "$SUDOERS_FILE"
|
sudo install -m 0440 -o root -g root "$merged" "$SUDOERS_FILE"
|
||||||
echo " $SUDOERS_FILE: rtcwake + start/stop $ALSA_UNIT (validated)."
|
echo " $SUDOERS_FILE: rtcwake, start/stop $ALSA_UNIT, start $PROBE_UNIT (validated)."
|
||||||
}
|
}
|
||||||
|
|
||||||
install_powerkey_dropin() {
|
install_powerkey_dropin() {
|
||||||
|
|||||||
1
phone_app/android/.gitignore
vendored
1
phone_app/android/.gitignore
vendored
@ -12,3 +12,4 @@ GeneratedPluginRegistrant.java
|
|||||||
key.properties
|
key.properties
|
||||||
**/*.keystore
|
**/*.keystore
|
||||||
**/*.jks
|
**/*.jks
|
||||||
|
.kotlin/
|
||||||
|
|||||||
@ -84,3 +84,30 @@ dependencies {
|
|||||||
// that needs a Context stays out of them.
|
// that needs a Context stays out of them.
|
||||||
testImplementation("junit:junit:4.13.2")
|
testImplementation("junit:junit:4.13.2")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Start the Dart compile first. Without the configuration cache (Flutter's
|
||||||
|
// FlutterTask does not support it) Gradle runs one :app task at a time, and
|
||||||
|
// `compileFlutterBuild<Variant>` sat ~190th in the plan: on a clean tree it
|
||||||
|
// started ~8 s in, after :app had idled waiting on plugin resources, then
|
||||||
|
// held :app for ~20 s while Kotlin, dex and manifests queued behind it.
|
||||||
|
// Running it before pre<Variant>Build overlaps it with the plugin projects.
|
||||||
|
// mustRunAfter only orders; it pulls the compile into no task graph.
|
||||||
|
tasks.matching { it.name.matches(Regex("pre\\w+Build")) }.configureEach {
|
||||||
|
val variant = name.removePrefix("pre").removeSuffix("Build")
|
||||||
|
mustRunAfter(tasks.matching { it.name == "compileFlutterBuild$variant" })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debug APKs only reach the Pixel 6a (arm64-v8a) and the x86_64 emulator.
|
||||||
|
// Flutter packs three ABIs into every debug APK (182 MB), and merging,
|
||||||
|
// stripping and zipping libraries no debug install loads cost the clean
|
||||||
|
// probe build seconds it does not have: the 32-bit ABIs, and the engine's
|
||||||
|
// 15 MB Vulkan validation layer, loaded only when the manifest sets
|
||||||
|
// io.flutter.embedding.android.EnableVulkanValidation (it does not).
|
||||||
|
// Release keeps every ABI.
|
||||||
|
androidComponents {
|
||||||
|
onVariants(selector().withBuildType("debug")) { variant ->
|
||||||
|
variant.packaging.jniLibs.excludes.addAll(
|
||||||
|
listOf("lib/armeabi-v7a/**", "lib/x86/**", "**/libVkLayer_khronos_validation.so"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -4,4 +4,5 @@
|
|||||||
to allow setting breakpoints, to provide hot reload, etc.
|
to allow setting breakpoints, to provide hot reload, etc.
|
||||||
-->
|
-->
|
||||||
<uses-permission android:name="android.permission.INTERNET"/>
|
<uses-permission android:name="android.permission.INTERNET"/>
|
||||||
|
<application android:networkSecurityConfig="@xml/network_security_config" />
|
||||||
</manifest>
|
</manifest>
|
||||||
|
|||||||
@ -0,0 +1,9 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!-- Debug builds only: plain HTTP to the PC's Firebase RTDB emulator, which
|
||||||
|
the AVD reaches as 10.0.2.2 (lib/services/sync_emulator.dart). Every
|
||||||
|
other host keeps the platform default (HTTPS only). -->
|
||||||
|
<network-security-config>
|
||||||
|
<domain-config cleartextTrafficPermitted="true">
|
||||||
|
<domain includeSubdomains="false">10.0.2.2</domain>
|
||||||
|
</domain-config>
|
||||||
|
</network-security-config>
|
||||||
@ -94,10 +94,47 @@
|
|||||||
<receiver
|
<receiver
|
||||||
android:name=".PoolSyncReceiver"
|
android:name=".PoolSyncReceiver"
|
||||||
android:exported="false"/>
|
android:exported="false"/>
|
||||||
|
<!-- The 21:00 notifications check (NotifAlarm.kt); not exported,
|
||||||
|
only this app's own PendingIntent reaches it. -->
|
||||||
|
<receiver
|
||||||
|
android:name=".NotifCheckReceiver"
|
||||||
|
android:exported="false"/>
|
||||||
|
<!-- Sent by the system to this app only: its notifications or the
|
||||||
|
ring channel blocked or unblocked in Settings (NotifAlarm.kt). -->
|
||||||
|
<receiver
|
||||||
|
android:name=".NotifBlockReceiver"
|
||||||
|
android:exported="false">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.app.action.APP_BLOCK_STATE_CHANGED"/>
|
||||||
|
<action android:name="android.app.action.NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED"/>
|
||||||
|
</intent-filter>
|
||||||
|
</receiver>
|
||||||
<!-- The silent buzz before a session deadline (SessionWarn.kt). -->
|
<!-- The silent buzz before a session deadline (SessionWarn.kt). -->
|
||||||
<receiver
|
<receiver
|
||||||
android:name=".SessionWarnReceiver"
|
android:name=".SessionWarnReceiver"
|
||||||
android:exported="false"/>
|
android:exported="false"/>
|
||||||
|
<!-- An active device admin cannot be paused from the launcher;
|
||||||
|
removing it is a bypass (Bypass.kt). Activated over adb. -->
|
||||||
|
<receiver
|
||||||
|
android:name=".WakeAdminReceiver"
|
||||||
|
android:exported="true"
|
||||||
|
android:permission="android.permission.BIND_DEVICE_ADMIN">
|
||||||
|
<meta-data
|
||||||
|
android:name="android.app.device_admin"
|
||||||
|
android:resource="@xml/wake_admin"/>
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED"/>
|
||||||
|
</intent-filter>
|
||||||
|
</receiver>
|
||||||
|
<!-- Sent by the system to this app only; a pause is a bypass. -->
|
||||||
|
<receiver
|
||||||
|
android:name=".SuspendReceiver"
|
||||||
|
android:exported="false">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MY_PACKAGE_SUSPENDED"/>
|
||||||
|
<action android:name="android.intent.action.MY_PACKAGE_UNSUSPENDED"/>
|
||||||
|
</intent-filter>
|
||||||
|
</receiver>
|
||||||
<receiver
|
<receiver
|
||||||
android:name=".BootReceiver"
|
android:name=".BootReceiver"
|
||||||
android:exported="true">
|
android:exported="true">
|
||||||
|
|||||||
@ -47,6 +47,8 @@ class AlarmActivity : FlutterActivity() {
|
|||||||
// an unlock first, every leg.
|
// an unlock first, every leg.
|
||||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||||
dismissKeyguard()
|
dismissKeyguard()
|
||||||
|
// A revoke or a killed ring, seen on a relaunch into this screen.
|
||||||
|
Bypass.checkOnLaunch(this)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@ -145,6 +145,8 @@ object AlarmChannel {
|
|||||||
// a deadline that rang while it sat in the background puts the
|
// a deadline that rang while it sat in the background puts the
|
||||||
// dismiss sequence in front the moment it is looked at.
|
// dismiss sequence in front the moment it is looked at.
|
||||||
"isRinging" -> result.success(AlarmService.running)
|
"isRinging" -> result.success(AlarmService.running)
|
||||||
|
"takeBypassReRing" -> result.success(BypassReRing.take(context))
|
||||||
|
"peekBypassReRing" -> result.success(BypassReRing.peek(context))
|
||||||
"beginStepCount" -> {
|
"beginStepCount" -> {
|
||||||
StepCounter.markRingStart(context)
|
StepCounter.markRingStart(context)
|
||||||
result.success(null)
|
result.success(null)
|
||||||
|
|||||||
@ -49,6 +49,9 @@ class AlarmReceiver : BroadcastReceiver() {
|
|||||||
// After the sound is started, never before: tells the PC the phone
|
// After the sound is started, never before: tells the PC the phone
|
||||||
// is ringing even when the ring screen never opens.
|
// is ringing even when the ring screen never opens.
|
||||||
HeadlessRingStart.start(context)
|
HeadlessRingStart.start(context)
|
||||||
|
// Notifications or the full-screen intent switched off: the ring has
|
||||||
|
// no screen, so the morning counts as bypassed.
|
||||||
|
Bypass.checkPermissions(context)
|
||||||
}
|
}
|
||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
|
|||||||
@ -67,6 +67,8 @@ object AlarmScheduler {
|
|||||||
StickAlarm.schedule(context, LocalTime.of(hour, minute))
|
StickAlarm.schedule(context, LocalTime.of(hour, minute))
|
||||||
// Same funnel for the pre-alarm day-pool sync (PoolSyncAlarm.kt).
|
// Same funnel for the pre-alarm day-pool sync (PoolSyncAlarm.kt).
|
||||||
PoolSyncAlarm.schedule(context, LocalTime.of(hour, minute))
|
PoolSyncAlarm.schedule(context, LocalTime.of(hour, minute))
|
||||||
|
// And the 21:00 notifications check (NotifAlarm.kt).
|
||||||
|
NotifAlarm.schedule(context)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Cancels the armed alarm and forgets the stored time. */
|
/** Cancels the armed alarm and forgets the stored time. */
|
||||||
|
|||||||
@ -40,7 +40,7 @@ class AlarmService : Service() {
|
|||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private const val TAG = "AlarmService"
|
private const val TAG = "AlarmService"
|
||||||
private const val CHANNEL_ID = "wake_alarm_ring"
|
private const val CHANNEL_ID = NotifState.RING_CHANNEL_ID
|
||||||
private const val NOTIFICATION_ID = 42
|
private const val NOTIFICATION_ID = 42
|
||||||
|
|
||||||
/** Vibration: 1s buzz, 1s gap, repeating from index 0. */
|
/** Vibration: 1s buzz, 1s gap, repeating from index 0. */
|
||||||
|
|||||||
@ -54,6 +54,8 @@ object AlarmWatchdog {
|
|||||||
fun verify(context: Context) {
|
fun verify(context: Context) {
|
||||||
val rearmed = AlarmScheduler.rearmFromStorage(context)
|
val rearmed = AlarmScheduler.rearmFromStorage(context)
|
||||||
Log.i(TAG, "daily check: rearmed=$rearmed")
|
Log.i(TAG, "daily check: rearmed=$rearmed")
|
||||||
|
// rearmFromStorage arms it too, but only with an alarm stored.
|
||||||
|
NotifAlarm.schedule(context)
|
||||||
// Third net behind the exact check and boot: within a day, whatever
|
// Third net behind the exact check and boot: within a day, whatever
|
||||||
// dropped the other two, today's miss is still caught here.
|
// dropped the other two, today's miss is still caught here.
|
||||||
StickRunner.run(context, "watchdog")
|
StickRunner.run(context, "watchdog")
|
||||||
|
|||||||
@ -25,10 +25,14 @@ class BootReceiver : BroadcastReceiver() {
|
|||||||
// has to be re-established here or it silently stops after the first
|
// has to be re-established here or it silently stops after the first
|
||||||
// restart — exactly when a watchdog is most needed.
|
// restart — exactly when a watchdog is most needed.
|
||||||
AlarmWatchdog.schedule(context)
|
AlarmWatchdog.schedule(context)
|
||||||
|
// The 21:00 notifications check, also with no alarm stored.
|
||||||
|
NotifAlarm.schedule(context)
|
||||||
// A phone switched off before the alarm and back on after A + 15 has
|
// A phone switched off before the alarm and back on after A + 15 has
|
||||||
// missed: this is the path that closes that hole (rearmFromStorage
|
// missed: this is the path that closes that hole (rearmFromStorage
|
||||||
// above has already armed the exact check for a phone back earlier).
|
// above has already armed the exact check for a phone back earlier).
|
||||||
StickRunner.run(context, "boot")
|
StickRunner.run(context, "boot")
|
||||||
|
// Switched off mid-ring and back on the same day: the ring was killed.
|
||||||
|
Bypass.checkRingKilled(context)
|
||||||
}
|
}
|
||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
|
|||||||
@ -0,0 +1,147 @@
|
|||||||
|
package com.kuhy.wake_alarm_sync
|
||||||
|
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.os.Build
|
||||||
|
import android.util.Log
|
||||||
|
import java.time.LocalDate
|
||||||
|
|
||||||
|
/** How the alarm was got around; [wire] is the `bypass` event's `cause`. */
|
||||||
|
enum class BypassCause(val wire: String) {
|
||||||
|
SUSPENDED("suspended"),
|
||||||
|
ADMIN_REMOVED("admin_removed"),
|
||||||
|
FSI_REVOKED("fsi_revoked"),
|
||||||
|
NOTIFICATIONS_OFF("notifications_off"),
|
||||||
|
RING_KILLED("ring_killed"),
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The bypass rules as pure functions; [Bypass] gathers the inputs. */
|
||||||
|
object BypassRules {
|
||||||
|
/** A bypass counts on a ringing day while the ring or the morning session is live. */
|
||||||
|
fun counts(ringingDay: Boolean, ringLive: Boolean, sessionLive: Boolean): Boolean =
|
||||||
|
ringingDay && (ringLive || sessionLive)
|
||||||
|
|
||||||
|
/** The same cause recorded less than [windowMs] ago. */
|
||||||
|
fun isRepeat(last: Pair<String, Long>?, cause: String, now: Long, windowMs: Long): Boolean =
|
||||||
|
last != null && last.first == cause && now - last.second in 0 until windowMs
|
||||||
|
|
||||||
|
/** Today's ring fired, was never dismissed, and nothing is ringing now. */
|
||||||
|
fun ringKilled(firedToday: Boolean, dismissedToday: Boolean, ringing: Boolean): Boolean =
|
||||||
|
firedToday && !dismissedToday && !ringing
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this bypass's ring is a new session re-ring to name for it.
|
||||||
|
* One already sounding (a leg's deadline) stays that re-ring: one sound,
|
||||||
|
* one re-ring, its reason the one that started it.
|
||||||
|
*/
|
||||||
|
fun stampReRing(sessionLive: Boolean, ringing: Boolean): Boolean = sessionLive && !ringing
|
||||||
|
|
||||||
|
fun encodeStamp(cause: String, date: String): String = "$date|$cause"
|
||||||
|
|
||||||
|
/** The cause in [stored] if it was stamped on [today]; a stale one is dropped. */
|
||||||
|
fun takeStamp(stored: String?, today: String): String? {
|
||||||
|
val parts = stored?.split("|", limit = 2) ?: return null
|
||||||
|
return if (parts.size == 2 && parts[0] == today) parts[1] else null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Records a bypass of the alarm: the app paused from the launcher
|
||||||
|
* ("Wstrzymaj aplikację", 2026-11-20 and 11-22), its device admin removed,
|
||||||
|
* notifications or the full-screen intent switched off, or the ring killed.
|
||||||
|
*
|
||||||
|
* A bypass is a miss on any ringing day ([StickCheck]), so it locks the phone
|
||||||
|
* down through the next day and stacks the streak. It is published at once
|
||||||
|
* (the `bypass` phone event), so the PC rings until a fresh dismiss, and the
|
||||||
|
* phone rings again: the morning goes on as if the bypass never happened,
|
||||||
|
* one re-ring richer when a session was live.
|
||||||
|
*/
|
||||||
|
object Bypass {
|
||||||
|
private const val TAG = "WakeAlarmBypass"
|
||||||
|
|
||||||
|
// One launch runs the checks from MainActivity and then AlarmActivity
|
||||||
|
// (emulator, 2026-11-22: two events, two publishes for one revoke).
|
||||||
|
private const val REPEAT_WINDOW_MS = 60_000L
|
||||||
|
private var lastRecorded: Pair<String, Long>? = null
|
||||||
|
|
||||||
|
/** Records [cause] if it counts today; returns whether it did. */
|
||||||
|
@Synchronized
|
||||||
|
fun record(context: Context, cause: BypassCause): Boolean {
|
||||||
|
val today = LocalDate.now()
|
||||||
|
val ringLive = RingWatch.firedToday(context) && !RingWatch.dismissedOn(context, today)
|
||||||
|
val sessionLive = SessionNotice.isLiveToday(context)
|
||||||
|
if (!BypassRules.counts(ringingDay(context, today), ringLive, sessionLive)) {
|
||||||
|
Log.i(TAG, "${cause.wire}: no ring or session live; not a bypass")
|
||||||
|
EventLog.append(context, "bypass_ignored", mapOf("cause" to cause.wire))
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
if (BypassRules.isRepeat(lastRecorded, cause.wire, now, REPEAT_WINDOW_MS)) {
|
||||||
|
Log.i(TAG, "bypass: ${cause.wire} again within a minute; already recorded")
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
lastRecorded = cause.wire to now
|
||||||
|
Log.w(TAG, "bypass: ${cause.wire}")
|
||||||
|
RingWatch.markBypass(context, today)
|
||||||
|
EventLog.append(
|
||||||
|
context,
|
||||||
|
"bypass",
|
||||||
|
mapOf("cause" to cause.wire, "date" to today.toString(), "session" to sessionLive),
|
||||||
|
)
|
||||||
|
if (cause == BypassCause.SUSPENDED) WorkdayStick.sendUnsuspend(context)
|
||||||
|
StickRunner.run(context, "bypass")
|
||||||
|
if (BypassRules.stampReRing(sessionLive, AlarmService.running)) {
|
||||||
|
BypassReRing.stamp(context, cause.wire, today.toString())
|
||||||
|
}
|
||||||
|
ringAgain(context)
|
||||||
|
HeadlessRingStart.start(context, HeadlessRingStart.PUBLISH_ENTRYPOINT)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every launch, from either activity: the launcher restores whichever
|
||||||
|
* one was on top (the ring or the session screen), so checking only in
|
||||||
|
* MainActivity missed a revoke made mid-morning (emulator, 2026-11-22).
|
||||||
|
*/
|
||||||
|
fun checkOnLaunch(context: Context) {
|
||||||
|
checkRingKilled(context)
|
||||||
|
checkPermissions(context)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Checks the permissions the ring needs; a revoked one on a live morning is a bypass. */
|
||||||
|
fun checkPermissions(context: Context) {
|
||||||
|
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||||
|
if (NotifState.off(context)) {
|
||||||
|
record(context, BypassCause.NOTIFICATIONS_OFF)
|
||||||
|
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE &&
|
||||||
|
!manager.canUseFullScreenIntent()
|
||||||
|
) {
|
||||||
|
record(context, BypassCause.FSI_REVOKED)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** On a launch or boot: today's ring fired, undismissed, and is not ringing. */
|
||||||
|
fun checkRingKilled(context: Context) {
|
||||||
|
val killed = BypassRules.ringKilled(
|
||||||
|
firedToday = RingWatch.firedToday(context),
|
||||||
|
dismissedToday = RingWatch.dismissedOn(context, LocalDate.now()),
|
||||||
|
ringing = AlarmService.running,
|
||||||
|
)
|
||||||
|
if (killed) record(context, BypassCause.RING_KILLED)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Starts the ring again; a refused start (still suspended) waits for the unsuspend. */
|
||||||
|
fun ringAgain(context: Context) {
|
||||||
|
try {
|
||||||
|
AlarmService.start(context)
|
||||||
|
} catch (e: RuntimeException) {
|
||||||
|
Log.w(TAG, "ring not restarted yet: $e")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ringingDay(context: Context, day: LocalDate): Boolean =
|
||||||
|
AlarmScheduler.storedAlarm(context) != null &&
|
||||||
|
!FreeDays.isFree(context, day) &&
|
||||||
|
!SickDays.isSick(context, day) &&
|
||||||
|
RingWatch.skippedOn(context, day) == null
|
||||||
|
}
|
||||||
@ -0,0 +1,35 @@
|
|||||||
|
package com.kuhy.wake_alarm_sync
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import java.time.LocalDate
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The cause of a bypass that restarted the ring during a live morning
|
||||||
|
* session, handed to Dart once (`takeBypassReRing`) so the session records
|
||||||
|
* that re-ring as `bypass:<cause>` rather than the leg's deadline.
|
||||||
|
*
|
||||||
|
* Dated, so a session that ends without a dismiss cannot leak it into
|
||||||
|
* tomorrow's first re-ring.
|
||||||
|
*/
|
||||||
|
object BypassReRing {
|
||||||
|
private const val PREFS = "wake_alarm_bypass_rering"
|
||||||
|
private const val KEY = "stamp"
|
||||||
|
|
||||||
|
fun stamp(context: Context, cause: String, date: String) {
|
||||||
|
prefs(context).edit().putString(KEY, BypassRules.encodeStamp(cause, date)).commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The stamped cause, left in place: every screen ticking on this ring sees it. */
|
||||||
|
fun peek(context: Context): String? =
|
||||||
|
BypassRules.takeStamp(prefs(context).getString(KEY, null), LocalDate.now().toString())
|
||||||
|
|
||||||
|
/** The stamped cause, cleared: called once, when the re-ring is recorded. */
|
||||||
|
fun take(context: Context): String? {
|
||||||
|
val stored = prefs(context).getString(KEY, null) ?: return null
|
||||||
|
prefs(context).edit().remove(KEY).commit()
|
||||||
|
return BypassRules.takeStamp(stored, LocalDate.now().toString())
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun prefs(context: Context) =
|
||||||
|
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||||
|
}
|
||||||
@ -0,0 +1,51 @@
|
|||||||
|
package com.kuhy.wake_alarm_sync
|
||||||
|
|
||||||
|
import android.app.admin.DeviceAdminReceiver
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.util.Log
|
||||||
|
import java.time.LocalDate
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The app's own device admin. An active admin cannot be paused
|
||||||
|
* ("Wstrzymaj aplikację"): Android refuses to suspend it. Deactivating it is
|
||||||
|
* possible in Settings and no one can stop that, so it is a bypass instead.
|
||||||
|
* Activated over adb (`dpm set-active-admin`), never by a tap.
|
||||||
|
*/
|
||||||
|
class WakeAdminReceiver : DeviceAdminReceiver() {
|
||||||
|
override fun onDisabled(context: Context, intent: Intent) {
|
||||||
|
Bypass.record(context, BypassCause.ADMIN_REMOVED)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `MY_PACKAGE_SUSPENDED` / `UNSUSPENDED`, sent by the system to this app
|
||||||
|
* itself. Suspended: record the bypass and ask focus-owner to lift it.
|
||||||
|
* Unsuspended: when today's bypass is live, ring again (the start may have
|
||||||
|
* been refused while suspended).
|
||||||
|
*/
|
||||||
|
class SuspendReceiver : BroadcastReceiver() {
|
||||||
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
|
when (intent.action) {
|
||||||
|
Intent.ACTION_MY_PACKAGE_SUSPENDED -> {
|
||||||
|
Log.w(TAG, "suspended")
|
||||||
|
Bypass.record(context, BypassCause.SUSPENDED)
|
||||||
|
}
|
||||||
|
Intent.ACTION_MY_PACKAGE_UNSUSPENDED -> {
|
||||||
|
Log.i(TAG, "unsuspended")
|
||||||
|
EventLog.append(context, "unsuspended")
|
||||||
|
if (RingWatch.bypassOn(context, LocalDate.now())) {
|
||||||
|
if (!AlarmService.running) Bypass.ringAgain(context)
|
||||||
|
// Again now the app runs normally: the push made while
|
||||||
|
// suspended may not have gone out.
|
||||||
|
HeadlessRingStart.start(context, HeadlessRingStart.PUBLISH_ENTRYPOINT)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TAG = "WakeAlarmSuspend"
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -52,12 +52,14 @@ object EnforcementChannel {
|
|||||||
val isFree = { day: LocalDate -> FreeDays.isFree(context, day) }
|
val isFree = { day: LocalDate -> FreeDays.isFree(context, day) }
|
||||||
val isSick = { day: LocalDate -> SickDays.isSick(context, day) }
|
val isSick = { day: LocalDate -> SickDays.isSick(context, day) }
|
||||||
val standsDown = { day: LocalDate -> isFree(day) || isSick(day) }
|
val standsDown = { day: LocalDate -> isFree(day) || isSick(day) }
|
||||||
|
val bypassOn = { day: LocalDate -> RingWatch.bypassOn(context, day) }
|
||||||
return mapOf(
|
return mapOf(
|
||||||
"today" to today.toString(),
|
"today" to today.toString(),
|
||||||
"alarmHour" to alarm?.hour,
|
"alarmHour" to alarm?.hour,
|
||||||
"alarmMinute" to alarm?.minute,
|
"alarmMinute" to alarm?.minute,
|
||||||
"dismissedToday" to RingWatch.dismissedOn(context, today),
|
"dismissedToday" to RingWatch.dismissedOn(context, today),
|
||||||
"escapedToday" to StickStore.escapedOn(context, today),
|
"escapedToday" to StickStore.escapedOn(context, today),
|
||||||
|
"bypassToday" to RingWatch.bypassOn(context, today),
|
||||||
"freeToday" to isFree(today),
|
"freeToday" to isFree(today),
|
||||||
"freeTomorrow" to isFree(tomorrow),
|
"freeTomorrow" to isFree(tomorrow),
|
||||||
"sickToday" to isSick(today),
|
"sickToday" to isSick(today),
|
||||||
@ -67,9 +69,9 @@ object EnforcementChannel {
|
|||||||
"lastMiss" to stick.lastMiss?.toString(),
|
"lastMiss" to stick.lastMiss?.toString(),
|
||||||
"updatedAt" to StickStore.updatedAt(context),
|
"updatedAt" to StickStore.updatedAt(context),
|
||||||
"lockIfMissToday" to
|
"lockIfMissToday" to
|
||||||
StickCheck.afterMiss(today, stick, standsDown).lockedThrough?.toString(),
|
StickCheck.afterMiss(today, stick, standsDown, bypassOn).lockedThrough?.toString(),
|
||||||
"lockIfMissTomorrow" to
|
"lockIfMissTomorrow" to
|
||||||
StickCheck.afterMiss(tomorrow, stick, standsDown).lockedThrough?.toString(),
|
StickCheck.afterMiss(tomorrow, stick, standsDown, bypassOn).lockedThrough?.toString(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -30,15 +30,25 @@ object HeadlessRingStart {
|
|||||||
private const val TAG = "WakeAlarmHeadless"
|
private const val TAG = "WakeAlarmHeadless"
|
||||||
const val CHANNEL = "com.kuhy.wake_alarm_sync/headless"
|
const val CHANNEL = "com.kuhy.wake_alarm_sync/headless"
|
||||||
private const val ENTRYPOINT = "ringStartedMain"
|
private const val ENTRYPOINT = "ringStartedMain"
|
||||||
|
|
||||||
|
/** Publishes the enforcement fields now (a bypass); `publishNowMain` in `main.dart`. */
|
||||||
|
const val PUBLISH_ENTRYPOINT = "publishNowMain"
|
||||||
private const val TIMEOUT_MS = 90_000L
|
private const val TIMEOUT_MS = 90_000L
|
||||||
|
|
||||||
private val handler = Handler(Looper.getMainLooper())
|
private val handler = Handler(Looper.getMainLooper())
|
||||||
private var engine: FlutterEngine? = null
|
private var engine: FlutterEngine? = null
|
||||||
|
|
||||||
/** Starts the engine unless one is already running. Main thread only. */
|
/** A publish asked for while an engine ran; started when that one stops. */
|
||||||
fun start(context: Context) {
|
private var pending: Pair<Context, String>? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts the engine running [entrypoint] unless one is already running,
|
||||||
|
* in which case a publish is queued behind it. Main thread only.
|
||||||
|
*/
|
||||||
|
fun start(context: Context, entrypoint: String = ENTRYPOINT) {
|
||||||
if (engine != null) {
|
if (engine != null) {
|
||||||
Log.w(TAG, "headless ring_started engine already running; start ignored")
|
if (entrypoint == PUBLISH_ENTRYPOINT) pending = context.applicationContext to entrypoint
|
||||||
|
Log.w(TAG, "headless engine already running; $entrypoint ${if (pending != null) "queued" else "ignored"}")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@ -55,7 +65,7 @@ object HeadlessRingStart {
|
|||||||
}
|
}
|
||||||
val bundle = FlutterInjector.instance().flutterLoader().findAppBundlePath()
|
val bundle = FlutterInjector.instance().flutterLoader().findAppBundlePath()
|
||||||
created.dartExecutor.executeDartEntrypoint(
|
created.dartExecutor.executeDartEntrypoint(
|
||||||
DartExecutor.DartEntrypoint(bundle, ENTRYPOINT),
|
DartExecutor.DartEntrypoint(bundle, entrypoint),
|
||||||
)
|
)
|
||||||
handler.postDelayed({ stop("timeout") }, TIMEOUT_MS)
|
handler.postDelayed({ stop("timeout") }, TIMEOUT_MS)
|
||||||
Log.i(TAG, "headless ring_started engine started")
|
Log.i(TAG, "headless ring_started engine started")
|
||||||
@ -70,5 +80,9 @@ object HeadlessRingStart {
|
|||||||
engine?.destroy()
|
engine?.destroy()
|
||||||
engine = null
|
engine = null
|
||||||
Log.i(TAG, "headless engine stopped: $reason")
|
Log.i(TAG, "headless engine stopped: $reason")
|
||||||
|
pending?.let { (context, entrypoint) ->
|
||||||
|
pending = null
|
||||||
|
handler.post { start(context, entrypoint) }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -20,6 +20,9 @@ class MainActivity : FlutterActivity() {
|
|||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
|
// A ring that fired, went undismissed and is not sounding was killed
|
||||||
|
// (force stop, a pause that got through): a bypass, which rings again.
|
||||||
|
Bypass.checkOnLaunch(this)
|
||||||
if (resumeMorning()) return
|
if (resumeMorning()) return
|
||||||
requestAlarmPermissions()
|
requestAlarmPermissions()
|
||||||
}
|
}
|
||||||
|
|||||||
@ -0,0 +1,99 @@
|
|||||||
|
package com.kuhy.wake_alarm_sync
|
||||||
|
|
||||||
|
import android.app.AlarmManager
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.util.Log
|
||||||
|
import java.time.LocalDateTime
|
||||||
|
import java.time.ZoneId
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The exact daily alarm at [NotifRules.EVENING] (21:00) that runs
|
||||||
|
* [NotifState.report] (trigger `evening`), so the PC can ring while the
|
||||||
|
* notifications are still off and there is time to fix them before sleeping.
|
||||||
|
*
|
||||||
|
* Same shape as [PoolSyncAlarm]: setExactAndAllowWhileIdle (never an
|
||||||
|
* alarm-clock entry, which would show as the "next alarm"), inexact when
|
||||||
|
* exact alarms are refused, its own receiver and request code
|
||||||
|
* ([REQUEST_CODE]), never [AlarmReceiver], which would ring.
|
||||||
|
*
|
||||||
|
* Armed from [AlarmScheduler.schedule] (every arm path: launch, dismiss,
|
||||||
|
* skip), from [BootReceiver] and from the watchdog, and re-armed by its own
|
||||||
|
* receiver. Always the next future 21:00 ([NotifRules.nextEvening]), so a
|
||||||
|
* re-arm never restores an instant that has passed.
|
||||||
|
*/
|
||||||
|
object NotifAlarm {
|
||||||
|
private const val REQUEST_CODE = 1007
|
||||||
|
private const val TAG = "WakeAlarmNotifAlarm"
|
||||||
|
|
||||||
|
fun schedule(context: Context) {
|
||||||
|
val at = NotifRules.nextEvening(LocalDateTime.now())
|
||||||
|
val millis = at.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
|
||||||
|
Log.i(TAG, "notifications check armed for $at via ${arm(context, millis)}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Arms [millis], exactly when permitted; returns which API did it. */
|
||||||
|
private fun arm(context: Context, millis: Long): String {
|
||||||
|
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
|
||||||
|
val exactAllowed = Build.VERSION.SDK_INT < Build.VERSION_CODES.S ||
|
||||||
|
manager.canScheduleExactAlarms()
|
||||||
|
if (exactAllowed) {
|
||||||
|
try {
|
||||||
|
manager.setExactAndAllowWhileIdle(
|
||||||
|
AlarmManager.RTC_WAKEUP,
|
||||||
|
millis,
|
||||||
|
pendingIntent(context),
|
||||||
|
)
|
||||||
|
return "setExactAndAllowWhileIdle"
|
||||||
|
} catch (e: SecurityException) {
|
||||||
|
Log.w(TAG, "exact alarm refused; arming inexact", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, millis, pendingIntent(context))
|
||||||
|
return "setAndAllowWhileIdle"
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Holds [receiver]'s broadcast of [intent] open for [NotifRules.holdMs], then lets it go. */
|
||||||
|
fun hold(receiver: BroadcastReceiver, intent: Intent) {
|
||||||
|
val foreground = (intent.flags and Intent.FLAG_RECEIVER_FOREGROUND) != 0
|
||||||
|
val pending = receiver.goAsync()
|
||||||
|
Handler(Looper.getMainLooper())
|
||||||
|
.postDelayed({ pending.finish() }, NotifRules.holdMs(foreground))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun pendingIntent(context: Context): PendingIntent = PendingIntent.getBroadcast(
|
||||||
|
context,
|
||||||
|
REQUEST_CODE,
|
||||||
|
Intent(context, NotifCheckReceiver::class.java),
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Receives [NotifAlarm]: re-arms tomorrow's first, so a crash below cannot end the chain. */
|
||||||
|
class NotifCheckReceiver : BroadcastReceiver() {
|
||||||
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
|
NotifAlarm.schedule(context)
|
||||||
|
NotifAlarm.hold(this, intent)
|
||||||
|
NotifState.report(context, "evening")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The app's notifications, or the ring channel, blocked or unblocked in
|
||||||
|
* Settings. The system sends both to this app alone; switching them back on
|
||||||
|
* publishes `enabled=true` at once, which stops the PC's evening ring.
|
||||||
|
*/
|
||||||
|
class NotifBlockReceiver : BroadcastReceiver() {
|
||||||
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
|
val channel = intent.getStringExtra(NotificationManager.EXTRA_NOTIFICATION_CHANNEL_ID)
|
||||||
|
val trigger = NotifRules.trigger(intent.action, channel) ?: return
|
||||||
|
NotifAlarm.hold(this, intent)
|
||||||
|
NotifState.report(context, trigger)
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,77 @@
|
|||||||
|
package com.kuhy.wake_alarm_sync
|
||||||
|
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.Log
|
||||||
|
import java.time.LocalDateTime
|
||||||
|
import java.time.LocalTime
|
||||||
|
|
||||||
|
/** The notifications check's rules as pure functions; [NotifState] gathers the inputs. */
|
||||||
|
object NotifRules {
|
||||||
|
/** When the evening check runs: early enough to fix it before sleeping. */
|
||||||
|
val EVENING: LocalTime = LocalTime.of(21, 0)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Off when the app's notifications are blocked or the ring channel is set
|
||||||
|
* to none. A channel not created yet ([ringImportance] null) is not a block.
|
||||||
|
*/
|
||||||
|
fun off(appEnabled: Boolean, ringImportance: Int?): Boolean =
|
||||||
|
!appEnabled || ringImportance == NotificationManager.IMPORTANCE_NONE
|
||||||
|
|
||||||
|
/** The next [EVENING] strictly after [now]: never one that has passed. */
|
||||||
|
fun nextEvening(now: LocalDateTime): LocalDateTime {
|
||||||
|
val tonight = now.toLocalDate().atTime(EVENING)
|
||||||
|
return if (tonight.isAfter(now)) tonight else tonight.plusDays(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How long a receiver holds its broadcast open after starting the push:
|
||||||
|
* a receiver that returns lets Android freeze the headless Dart engine
|
||||||
|
* mid-request (see [PoolSyncReceiver]). A foreground broadcast (the
|
||||||
|
* block-state ones are sent that way) has a 10 s budget, a background
|
||||||
|
* one 60 s; overrunning either is an ANR that kills the push.
|
||||||
|
*/
|
||||||
|
fun holdMs(foreground: Boolean): Long = if (foreground) 8_000L else 25_000L
|
||||||
|
|
||||||
|
/** The `notifications` event's data. */
|
||||||
|
fun eventData(enabled: Boolean, trigger: String): Map<String, Any?> =
|
||||||
|
mapOf("enabled" to enabled, "trigger" to trigger)
|
||||||
|
|
||||||
|
/** The event trigger for a block-state broadcast, or null when it is not about the ring. */
|
||||||
|
fun trigger(action: String?, channelId: String?): String? = when (action) {
|
||||||
|
NotificationManager.ACTION_APP_BLOCK_STATE_CHANGED -> "app_block"
|
||||||
|
NotificationManager.ACTION_NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED ->
|
||||||
|
if (channelId == NotifState.RING_CHANNEL_ID) "channel_block" else null
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the ring can show at all: "All WakeAlarm notifications" switched
|
||||||
|
* off, or the ring channel blocked, silences it, and no device policy can
|
||||||
|
* lock that switch (2026-11-22).
|
||||||
|
*
|
||||||
|
* Two readers: [Bypass.checkPermissions] at ring time (a bypass), and
|
||||||
|
* [report] at 21:00 ([NotifAlarm]) and whenever the switch moves
|
||||||
|
* ([NotifBlockReceiver]), which logs a `notifications` event and pushes it
|
||||||
|
* at once so the PC rings in the evening while it is still off.
|
||||||
|
*/
|
||||||
|
object NotifState {
|
||||||
|
const val RING_CHANNEL_ID = "wake_alarm_ring"
|
||||||
|
private const val TAG = "WakeAlarmNotif"
|
||||||
|
|
||||||
|
/** Whether notifications that the ring needs are switched off now. */
|
||||||
|
fun off(context: Context): Boolean {
|
||||||
|
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||||
|
val channel = manager.getNotificationChannel(RING_CHANNEL_ID)
|
||||||
|
return NotifRules.off(manager.areNotificationsEnabled(), channel?.importance)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Logs the state as a `notifications` event and publishes it now. Main thread. */
|
||||||
|
fun report(context: Context, trigger: String) {
|
||||||
|
val enabled = !off(context)
|
||||||
|
Log.i(TAG, "notifications enabled=$enabled ($trigger)")
|
||||||
|
EventLog.append(context, "notifications", NotifRules.eventData(enabled, trigger))
|
||||||
|
HeadlessRingStart.start(context, HeadlessRingStart.PUBLISH_ENTRYPOINT)
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -33,9 +33,18 @@ object RingWatch {
|
|||||||
private const val KEY_DISMISSED_DATE = "dismissed_date"
|
private const val KEY_DISMISSED_DATE = "dismissed_date"
|
||||||
private const val KEY_DISMISSED_DATES = "dismissed_dates"
|
private const val KEY_DISMISSED_DATES = "dismissed_dates"
|
||||||
private const val KEY_SKIPPED_PREFIX = "skipped_dates_"
|
private const val KEY_SKIPPED_PREFIX = "skipped_dates_"
|
||||||
|
private const val KEY_BYPASS_DATES = "bypass_dates"
|
||||||
|
|
||||||
|
// Written only by builds that have [Bypass], next to KEY_FIRED_DATE. A
|
||||||
|
// ring fired by an older build (11-22: paused, never dismissed) must not
|
||||||
|
// read as a killed ring the first time the new build launches.
|
||||||
|
private const val KEY_WATCHED_FIRED_DATE = "watched_fired_date"
|
||||||
|
|
||||||
fun markFired(context: Context) {
|
fun markFired(context: Context) {
|
||||||
prefs(context).edit().putString(KEY_FIRED_DATE, today()).apply()
|
prefs(context).edit()
|
||||||
|
.putString(KEY_FIRED_DATE, today())
|
||||||
|
.putString(KEY_WATCHED_FIRED_DATE, today())
|
||||||
|
.apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun markDismissed(context: Context) {
|
fun markDismissed(context: Context) {
|
||||||
@ -52,6 +61,19 @@ object RingWatch {
|
|||||||
DateHistory.add(prefs(context), KEY_SKIPPED_PREFIX + skip.wire, LocalDate.now())
|
DateHistory.add(prefs(context), KEY_SKIPPED_PREFIX + skip.wire, LocalDate.now())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Whether today's fresh ring fired under a build with [Bypass]; [Bypass] asks it. */
|
||||||
|
fun firedToday(context: Context): Boolean =
|
||||||
|
prefs(context).getString(KEY_WATCHED_FIRED_DATE, null) == today()
|
||||||
|
|
||||||
|
/** Latches a bypass ([Bypass]) on [day]; the stick reads it as a miss. */
|
||||||
|
fun markBypass(context: Context, day: LocalDate) {
|
||||||
|
DateHistory.add(prefs(context), KEY_BYPASS_DATES, day)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether a bypass was recorded on [day]. */
|
||||||
|
fun bypassOn(context: Context, day: LocalDate): Boolean =
|
||||||
|
DateHistory.contains(prefs(context), KEY_BYPASS_DATES, day)
|
||||||
|
|
||||||
/** Why the ring stood down on [day], or null when it was not skipped. */
|
/** Why the ring stood down on [day], or null when it was not skipped. */
|
||||||
fun skippedOn(context: Context, day: LocalDate): RingSkip? =
|
fun skippedOn(context: Context, day: LocalDate): RingSkip? =
|
||||||
RingSkip.entries.firstOrNull {
|
RingSkip.entries.firstOrNull {
|
||||||
|
|||||||
@ -46,6 +46,12 @@ data class StickInputs(
|
|||||||
* (2026-11-11).
|
* (2026-11-11).
|
||||||
*/
|
*/
|
||||||
val ringSkippedOn: (LocalDate) -> RingSkip? = { null },
|
val ringSkippedOn: (LocalDate) -> RingSkip? = { null },
|
||||||
|
/**
|
||||||
|
* Whether a bypass ([Bypass]) was recorded on a day: the app paused,
|
||||||
|
* its admin removed, a permission revoked, the ring killed. A miss on
|
||||||
|
* any ringing day, stick day or not (2026-11-22).
|
||||||
|
*/
|
||||||
|
val bypassOn: (LocalDate) -> Boolean = { false },
|
||||||
)
|
)
|
||||||
|
|
||||||
/** One day's verdict within a run. */
|
/** One day's verdict within a run. */
|
||||||
@ -61,12 +67,17 @@ data class StickRun(
|
|||||||
val state: StickState,
|
val state: StickState,
|
||||||
val checkedThrough: LocalDate,
|
val checkedThrough: LocalDate,
|
||||||
val signalUntil: LocalDate?,
|
val signalUntil: LocalDate?,
|
||||||
|
/** [signalUntil] repeats a lockdown already bought, not a new miss's. */
|
||||||
|
val resend: Boolean = false,
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The stick's decision, as pure functions -- no Context, no clock, no I/O,
|
* The stick's decision, as pure functions -- no Context, no clock, no I/O,
|
||||||
* so every rule here is checkable in isolation.
|
* so every rule here is checkable in isolation.
|
||||||
*
|
*
|
||||||
|
* A **bypass** ([StickInputs.bypassOn]) is a miss on any day that is neither
|
||||||
|
* free nor sick, at once and whatever the dismiss did afterwards.
|
||||||
|
*
|
||||||
* A **miss** is a stick day (Tue/Wed/Thu, [WorkdayStick.STICK_DAYS]) that is
|
* A **miss** is a stick day (Tue/Wed/Thu, [WorkdayStick.STICK_DAYS]) that is
|
||||||
* neither a free day nor a sick day (now, or when its ring stood down), whose alarm passed by at least [Stakes.STICK_GRACE_MINUTES]
|
* neither a free day nor a sick day (now, or when its ring stood down), whose alarm passed by at least [Stakes.STICK_GRACE_MINUTES]
|
||||||
* with no dismiss and no escape, and that has not already been penalised.
|
* with no dismiss and no escape, and that has not already been penalised.
|
||||||
@ -84,6 +95,9 @@ object StickCheck {
|
|||||||
/**
|
/**
|
||||||
* Judges every unchecked day, oldest first, then today.
|
* Judges every unchecked day, oldest first, then today.
|
||||||
*
|
*
|
||||||
|
* A day found [StickVerdict.ALREADY_PENALISED] re-sends the stored
|
||||||
|
* lockdown when it still runs through today ([StickRun.resend]).
|
||||||
|
*
|
||||||
* Past days run from the day after [StickInputs.checkedThrough], at most
|
* Past days run from the day after [StickInputs.checkedThrough], at most
|
||||||
* [BACKLOG_DAYS] back -- in order, so the streak builds exactly as if
|
* [BACKLOG_DAYS] back -- in order, so the streak builds exactly as if
|
||||||
* each day had been checked on time. A first run (no checkedThrough)
|
* each day had been checked on time. A first run (no checkedThrough)
|
||||||
@ -95,6 +109,7 @@ object StickCheck {
|
|||||||
val verdicts = mutableListOf<DayVerdict>()
|
val verdicts = mutableListOf<DayVerdict>()
|
||||||
var state = inputs.state
|
var state = inputs.state
|
||||||
var signal: LocalDate? = null
|
var signal: LocalDate? = null
|
||||||
|
var resend = false
|
||||||
val checked = inputs.checkedThrough
|
val checked = inputs.checkedThrough
|
||||||
var day = if (checked == null) {
|
var day = if (checked == null) {
|
||||||
today
|
today
|
||||||
@ -108,12 +123,22 @@ object StickCheck {
|
|||||||
verdicts += DayVerdict(day, verdict)
|
verdicts += DayVerdict(day, verdict)
|
||||||
if (verdict == StickVerdict.MISS) {
|
if (verdict == StickVerdict.MISS) {
|
||||||
signal = next.lockedThrough?.takeIf { !it.isBefore(today) }
|
signal = next.lockedThrough?.takeIf { !it.isBefore(today) }
|
||||||
|
resend = false
|
||||||
|
} else if (verdict == StickVerdict.ALREADY_PENALISED) {
|
||||||
|
// The one signal may never have landed (focus-owner not
|
||||||
|
// running or not yet Device Owner, C6 2026-11-22), so a day
|
||||||
|
// already penalised sends the stored lockdown again. Same
|
||||||
|
// date, same streak: focus-owner applies it idempotently.
|
||||||
|
state.lockedThrough?.takeIf { !it.isBefore(today) }?.let {
|
||||||
|
signal = it
|
||||||
|
resend = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
state = next
|
state = next
|
||||||
day = day.plusDays(1)
|
day = day.plusDays(1)
|
||||||
}
|
}
|
||||||
val settled = if (verdicts.last().verdict.final) today else today.minusDays(1)
|
val settled = if (verdicts.last().verdict.final) today else today.minusDays(1)
|
||||||
return StickRun(verdicts, state, maxOf(settled, checked ?: settled), signal)
|
return StickRun(verdicts, state, maxOf(settled, checked ?: settled), signal, resend)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One day's verdict and the state after it; [now] is when it is judged. */
|
/** One day's verdict and the state after it; [now] is when it is judged. */
|
||||||
@ -124,7 +149,7 @@ object StickCheck {
|
|||||||
state: StickState,
|
state: StickState,
|
||||||
): Pair<StickVerdict, StickState> {
|
): Pair<StickVerdict, StickState> {
|
||||||
val alarm = inputs.alarm ?: return StickVerdict.NO_ALARM to state
|
val alarm = inputs.alarm ?: return StickVerdict.NO_ALARM to state
|
||||||
if (!isStickDay(day)) return StickVerdict.NOT_STICK_DAY to state
|
if (!isStickDay(day) && !inputs.bypassOn(day)) return StickVerdict.NOT_STICK_DAY to state
|
||||||
if (inputs.isFree(day)) return StickVerdict.FREE_DAY to state
|
if (inputs.isFree(day)) return StickVerdict.FREE_DAY to state
|
||||||
// A sick day stands the stick down like a free day: no miss, no
|
// A sick day stands the stick down like a free day: no miss, no
|
||||||
// streak change, no lockdown -- and nothing carried to tomorrow.
|
// streak change, no lockdown -- and nothing carried to tomorrow.
|
||||||
@ -138,10 +163,14 @@ object StickCheck {
|
|||||||
// shown and synced drops to 0 (a lockdown already sent stays).
|
// shown and synced drops to 0 (a lockdown already sent stays).
|
||||||
if (inputs.escapedOn(day)) return StickVerdict.ESCAPED to state.copy(streak = 0)
|
if (inputs.escapedOn(day)) return StickVerdict.ESCAPED to state.copy(streak = 0)
|
||||||
if (state.lastMiss == day) return StickVerdict.ALREADY_PENALISED to state
|
if (state.lastMiss == day) return StickVerdict.ALREADY_PENALISED to state
|
||||||
|
// A bypass is a miss at once, and a later dismiss does not undo it.
|
||||||
|
if (inputs.bypassOn(day)) {
|
||||||
|
return StickVerdict.MISS to afterMiss(day, state, inputs.standsDown, inputs.bypassOn)
|
||||||
|
}
|
||||||
if (inputs.dismissedOn(day)) return StickVerdict.DISMISSED to state.copy(streak = 0)
|
if (inputs.dismissedOn(day)) return StickVerdict.DISMISSED to state.copy(streak = 0)
|
||||||
val due = day.atTime(alarm).plusMinutes(Stakes.STICK_GRACE_MINUTES)
|
val due = day.atTime(alarm).plusMinutes(Stakes.STICK_GRACE_MINUTES)
|
||||||
if (now.isBefore(due)) return StickVerdict.TOO_EARLY to state
|
if (now.isBefore(due)) return StickVerdict.TOO_EARLY to state
|
||||||
return StickVerdict.MISS to afterMiss(day, state, inputs.standsDown)
|
return StickVerdict.MISS to afterMiss(day, state, inputs.standsDown, inputs.bypassOn)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -151,20 +180,31 @@ object StickCheck {
|
|||||||
* lockdown already in force: a chain restarting at 1 must not report
|
* lockdown already in force: a chain restarting at 1 must not report
|
||||||
* an earlier end than the one focus-owner was already sent.
|
* an earlier end than the one focus-owner was already sent.
|
||||||
*/
|
*/
|
||||||
fun afterMiss(day: LocalDate, state: StickState, standsDown: (LocalDate) -> Boolean): StickState {
|
fun afterMiss(
|
||||||
val streak = streakAfterMiss(day, state, standsDown)
|
day: LocalDate,
|
||||||
|
state: StickState,
|
||||||
|
standsDown: (LocalDate) -> Boolean,
|
||||||
|
bypassOn: (LocalDate) -> Boolean = { false },
|
||||||
|
): StickState {
|
||||||
|
val streak = streakAfterMiss(day, state, standsDown, bypassOn)
|
||||||
val computed = lockedThrough(day, streak)
|
val computed = lockedThrough(day, streak)
|
||||||
val locked = state.lockedThrough?.let { maxOf(it, computed) } ?: computed
|
val locked = state.lockedThrough?.let { maxOf(it, computed) } ?: computed
|
||||||
return StickState(streak = streak, lockedThrough = locked, lastMiss = day)
|
return StickState(streak = streak, lockedThrough = locked, lastMiss = day)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Consecutive stick-day misses including one on [day]: the chain
|
* Consecutive misses including one on [day]: the chain continues only
|
||||||
* continues only when the previous stick day (free and sick days
|
* when the previous penalty day -- a stick day, or any day with a
|
||||||
* skipped, per [standsDown]) is exactly the last miss.
|
* bypass; free and sick days skipped, per [standsDown] -- is exactly
|
||||||
|
* the last miss.
|
||||||
*/
|
*/
|
||||||
fun streakAfterMiss(day: LocalDate, state: StickState, standsDown: (LocalDate) -> Boolean): Int {
|
fun streakAfterMiss(
|
||||||
val previous = previousStickDay(day, standsDown)
|
day: LocalDate,
|
||||||
|
state: StickState,
|
||||||
|
standsDown: (LocalDate) -> Boolean,
|
||||||
|
bypassOn: (LocalDate) -> Boolean = { false },
|
||||||
|
): Int {
|
||||||
|
val previous = previousStickDay(day, standsDown, bypassOn)
|
||||||
return if (previous != null && previous == state.lastMiss) state.streak + 1 else 1
|
return if (previous != null && previous == state.lastMiss) state.streak + 1 else 1
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -172,12 +212,16 @@ object StickCheck {
|
|||||||
fun lockedThrough(day: LocalDate, streak: Int): LocalDate =
|
fun lockedThrough(day: LocalDate, streak: Int): LocalDate =
|
||||||
day.plusDays(minOf(streak, Stakes.STICK_LOCKDOWN_MAX_DAYS - 1).toLong())
|
day.plusDays(minOf(streak, Stakes.STICK_LOCKDOWN_MAX_DAYS - 1).toLong())
|
||||||
|
|
||||||
/** The nearest earlier stick day that does not [standsDown], or null. */
|
/** The nearest earlier penalty day (stick or bypass) that does not [standsDown], or null. */
|
||||||
fun previousStickDay(day: LocalDate, standsDown: (LocalDate) -> Boolean): LocalDate? {
|
fun previousStickDay(
|
||||||
|
day: LocalDate,
|
||||||
|
standsDown: (LocalDate) -> Boolean,
|
||||||
|
bypassOn: (LocalDate) -> Boolean = { false },
|
||||||
|
): LocalDate? {
|
||||||
var step = day.minusDays(1)
|
var step = day.minusDays(1)
|
||||||
val floor = day.minusDays(LOOKBACK_DAYS)
|
val floor = day.minusDays(LOOKBACK_DAYS)
|
||||||
while (step.isAfter(floor)) {
|
while (step.isAfter(floor)) {
|
||||||
if (isStickDay(step) && !standsDown(step)) return step
|
if ((isStickDay(step) || bypassOn(step)) && !standsDown(step)) return step
|
||||||
step = step.minusDays(1)
|
step = step.minusDays(1)
|
||||||
}
|
}
|
||||||
return null
|
return null
|
||||||
|
|||||||
@ -15,8 +15,8 @@ import java.time.LocalDateTime
|
|||||||
* alarm") and `watchdog` (the daily net). Every run also catches up on the
|
* alarm") and `watchdog` (the daily net). Every run also catches up on the
|
||||||
* unchecked days before today ([StickCheck.run]), so a phone off for days
|
* unchecked days before today ([StickCheck.run]), so a phone off for days
|
||||||
* is judged day by day when it comes back. Running twice is harmless --
|
* is judged day by day when it comes back. Running twice is harmless --
|
||||||
* [StickVerdict.ALREADY_PENALISED] makes a second miss on one day a no-op,
|
* [StickVerdict.ALREADY_PENALISED] makes a second miss on one day a no-op
|
||||||
* which matters because Android replays BOOT_COMPLETED to a force-stopped
|
* for the streak (it only re-sends the same lockdown), which matters because Android replays BOOT_COMPLETED to a force-stopped
|
||||||
* app on its next launch.
|
* app on its next launch.
|
||||||
*/
|
*/
|
||||||
object StickRunner {
|
object StickRunner {
|
||||||
@ -36,6 +36,7 @@ object StickRunner {
|
|||||||
state = before,
|
state = before,
|
||||||
checkedThrough = StickStore.checkedThrough(context),
|
checkedThrough = StickStore.checkedThrough(context),
|
||||||
ringSkippedOn = { RingWatch.skippedOn(context, it) },
|
ringSkippedOn = { RingWatch.skippedOn(context, it) },
|
||||||
|
bypassOn = { RingWatch.bypassOn(context, it) },
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
for ((day, verdict) in run.verdicts) {
|
for ((day, verdict) in run.verdicts) {
|
||||||
@ -49,13 +50,18 @@ object StickRunner {
|
|||||||
if (run.state != before) StickStore.save(context, run.state)
|
if (run.state != before) StickStore.save(context, run.state)
|
||||||
StickStore.setCheckedThrough(context, run.checkedThrough)
|
StickStore.setCheckedThrough(context, run.checkedThrough)
|
||||||
// A missed day whose lockdown already ended (caught up days later)
|
// A missed day whose lockdown already ended (caught up days later)
|
||||||
// still counts toward the streak, but nothing is sent for it.
|
// still counts toward the streak, but nothing is sent for it. A day
|
||||||
|
// already penalised sends its lockdown again ([StickRun.resend]).
|
||||||
run.signalUntil?.let { until ->
|
run.signalUntil?.let { until ->
|
||||||
WorkdayStick.sendLockdown(context, until)
|
WorkdayStick.sendLockdown(context, until)
|
||||||
EventLog.append(
|
EventLog.append(
|
||||||
context,
|
context,
|
||||||
"lockdown_sent",
|
"lockdown_sent",
|
||||||
mapOf("until" to until.toString(), "streak" to run.state.streak),
|
mapOf(
|
||||||
|
"until" to until.toString(),
|
||||||
|
"streak" to run.state.streak,
|
||||||
|
"resend" to run.resend,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
return run.verdicts.last().verdict
|
return run.verdicts.last().verdict
|
||||||
|
|||||||
@ -23,6 +23,7 @@ object WorkdayStick {
|
|||||||
|
|
||||||
private const val ACTION_LOCKDOWN = "com.kuhy.focus_owner.action.LOCKDOWN_UNTIL_EOD"
|
private const val ACTION_LOCKDOWN = "com.kuhy.focus_owner.action.LOCKDOWN_UNTIL_EOD"
|
||||||
private const val ACTION_LIFT = "com.kuhy.focus_owner.action.LIFT_LOCKDOWN"
|
private const val ACTION_LIFT = "com.kuhy.focus_owner.action.LIFT_LOCKDOWN"
|
||||||
|
private const val ACTION_UNSUSPEND = "com.kuhy.focus_owner.action.UNSUSPEND"
|
||||||
private const val EXTRA_UNTIL = "until"
|
private const val EXTRA_UNTIL = "until"
|
||||||
private const val PERMISSION_SIGNAL = "com.kuhy.focus_owner.permission.SIGNAL_LOCKDOWN"
|
private const val PERMISSION_SIGNAL = "com.kuhy.focus_owner.permission.SIGNAL_LOCKDOWN"
|
||||||
private const val FOCUS_OWNER_PACKAGE = "com.kuhy.focus_owner"
|
private const val FOCUS_OWNER_PACKAGE = "com.kuhy.focus_owner"
|
||||||
@ -48,4 +49,13 @@ object WorkdayStick {
|
|||||||
PERMISSION_SIGNAL,
|
PERMISSION_SIGNAL,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Asks focus-owner for a pass now, which lifts a suspension of this app. */
|
||||||
|
fun sendUnsuspend(context: Context) {
|
||||||
|
Log.i(TAG, "signalling focus-owner unsuspend")
|
||||||
|
context.sendBroadcast(
|
||||||
|
Intent(ACTION_UNSUSPEND).setPackage(FOCUS_OWNER_PACKAGE),
|
||||||
|
PERMISSION_SIGNAL,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
5
phone_app/android/app/src/main/res/xml/wake_admin.xml
Normal file
5
phone_app/android/app/src/main/res/xml/wake_admin.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!-- No policies: the admin exists only so Android refuses to pause the app. -->
|
||||||
|
<device-admin>
|
||||||
|
<uses-policies />
|
||||||
|
</device-admin>
|
||||||
@ -0,0 +1,37 @@
|
|||||||
|
package com.kuhy.wake_alarm_sync
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A bypass during a live morning session re-rings it, and that re-ring is
|
||||||
|
* recorded as `bypass:<cause>`, not as the leg's deadline (2026-11-22).
|
||||||
|
*/
|
||||||
|
class BypassReRingTest {
|
||||||
|
@Test
|
||||||
|
fun `a bypass with the session live and nothing ringing stamps its re-ring`() {
|
||||||
|
assertTrue(BypassRules.stampReRing(sessionLive = true, ringing = false))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `a bypass while a deadline re-ring sounds keeps that one`() {
|
||||||
|
assertFalse(BypassRules.stampReRing(sessionLive = true, ringing = true))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `a bypass of the first ring is not a session re-ring`() {
|
||||||
|
assertFalse(BypassRules.stampReRing(sessionLive = false, ringing = false))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `a stamp is taken only on its own day`() {
|
||||||
|
val stamp = BypassRules.encodeStamp("fsi_revoked", "2026-11-22")
|
||||||
|
assertEquals("fsi_revoked", BypassRules.takeStamp(stamp, "2026-11-22"))
|
||||||
|
assertNull(BypassRules.takeStamp(stamp, "2026-11-23"))
|
||||||
|
assertNull(BypassRules.takeStamp(null, "2026-11-22"))
|
||||||
|
assertNull(BypassRules.takeStamp("garbage", "2026-11-22"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,63 @@
|
|||||||
|
package com.kuhy.wake_alarm_sync
|
||||||
|
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import java.time.LocalDateTime
|
||||||
|
|
||||||
|
/** The 21:00 notifications check (2026-11-22): when it runs and what it says. */
|
||||||
|
class NotifRulesTest {
|
||||||
|
private fun at(day: Int, hour: Int, minute: Int = 0, second: Int = 0) =
|
||||||
|
LocalDateTime.of(2026, 11, day, hour, minute, second)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun beforeNineTheCheckIsTonight() {
|
||||||
|
assertEquals(at(22, 21), NotifRules.nextEvening(at(22, 3)))
|
||||||
|
assertEquals(at(22, 21), NotifRules.nextEvening(at(22, 20, 59, 59)))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun theInstantThatJustFiredIsNeverReturned() {
|
||||||
|
assertEquals(at(23, 21), NotifRules.nextEvening(at(22, 21)))
|
||||||
|
assertEquals(at(23, 21), NotifRules.nextEvening(at(22, 23, 59)))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun offWhenTheAppIsBlockedOrTheRingChannelIsNone() {
|
||||||
|
assertTrue(NotifRules.off(appEnabled = false, ringImportance = null))
|
||||||
|
assertTrue(
|
||||||
|
NotifRules.off(appEnabled = true, ringImportance = NotificationManager.IMPORTANCE_NONE),
|
||||||
|
)
|
||||||
|
assertFalse(
|
||||||
|
NotifRules.off(appEnabled = true, ringImportance = NotificationManager.IMPORTANCE_HIGH),
|
||||||
|
)
|
||||||
|
// The channel is created at the first ring; none yet is not a block.
|
||||||
|
assertFalse(NotifRules.off(appEnabled = true, ringImportance = null))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun theEventCarriesEnabledAndTheTrigger() {
|
||||||
|
assertEquals(
|
||||||
|
mapOf("enabled" to false, "trigger" to "evening"),
|
||||||
|
NotifRules.eventData(enabled = false, trigger = "evening"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aForegroundBroadcastIsHeldInsideItsTenSeconds() {
|
||||||
|
assertTrue(NotifRules.holdMs(foreground = true) < 10_000L)
|
||||||
|
assertTrue(NotifRules.holdMs(foreground = false) in 10_000L until 60_000L)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun onlyTheAppOrTheRingChannelCounts() {
|
||||||
|
val app = NotificationManager.ACTION_APP_BLOCK_STATE_CHANGED
|
||||||
|
val channel = NotificationManager.ACTION_NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED
|
||||||
|
assertEquals("app_block", NotifRules.trigger(app, null))
|
||||||
|
assertEquals("channel_block", NotifRules.trigger(channel, NotifState.RING_CHANNEL_ID))
|
||||||
|
assertEquals(null, NotifRules.trigger(channel, "wake_alarm_session"))
|
||||||
|
assertEquals(null, NotifRules.trigger("android.intent.action.BOOT_COMPLETED", null))
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,117 @@
|
|||||||
|
package com.kuhy.wake_alarm_sync
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import java.time.LocalDate
|
||||||
|
import java.time.LocalDateTime
|
||||||
|
import java.time.LocalTime
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A bypass (the app paused, its admin removed, a permission revoked, the
|
||||||
|
* ring killed) is a miss on any ringing day, 2026-11-22.
|
||||||
|
*/
|
||||||
|
class StickCheckBypassTest {
|
||||||
|
// 2026-11-20 is a Friday, 22 a Sunday, 24 a Tuesday.
|
||||||
|
private val fri = LocalDate.of(2026, 11, 20)
|
||||||
|
private val sun = LocalDate.of(2026, 11, 22)
|
||||||
|
private val mon = sun.plusDays(1)
|
||||||
|
private val tue = sun.plusDays(2)
|
||||||
|
|
||||||
|
private fun inputs(
|
||||||
|
now: LocalDateTime,
|
||||||
|
bypass: Set<LocalDate> = emptySet(),
|
||||||
|
dismissed: Set<LocalDate> = emptySet(),
|
||||||
|
free: Set<LocalDate> = emptySet(),
|
||||||
|
sick: Set<LocalDate> = emptySet(),
|
||||||
|
state: StickState = StickState(),
|
||||||
|
checkedThrough: LocalDate? = null,
|
||||||
|
) = StickInputs(
|
||||||
|
now = now,
|
||||||
|
alarm = LocalTime.of(7, 30),
|
||||||
|
dismissedOn = { it in dismissed },
|
||||||
|
escapedOn = { false },
|
||||||
|
isFree = { it in free },
|
||||||
|
isSick = { it in sick },
|
||||||
|
state = state,
|
||||||
|
checkedThrough = checkedThrough,
|
||||||
|
bypassOn = { it in bypass },
|
||||||
|
)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aSundayBypassIsAMissLockingThroughMonday() {
|
||||||
|
val run = StickCheck.run(inputs(sun.atTime(7, 40), bypass = setOf(sun)))
|
||||||
|
assertEquals(StickVerdict.MISS, run.verdicts.single().verdict)
|
||||||
|
assertEquals(StickState(streak = 1, lockedThrough = mon, lastMiss = sun), run.state)
|
||||||
|
assertEquals(mon, run.signalUntil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aBypassCountsEvenBeforeTheGraceAndAfterADismiss() {
|
||||||
|
val run = StickCheck.run(
|
||||||
|
inputs(tue.atTime(7, 35), bypass = setOf(tue), dismissed = setOf(tue)),
|
||||||
|
)
|
||||||
|
assertEquals(StickVerdict.MISS, run.verdicts.single().verdict)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aTuesdayMissAfterASundayBypassStacks() {
|
||||||
|
val afterSunday = StickState(streak = 1, lockedThrough = mon, lastMiss = sun)
|
||||||
|
val run = StickCheck.run(
|
||||||
|
inputs(
|
||||||
|
tue.atTime(9, 0),
|
||||||
|
bypass = setOf(sun),
|
||||||
|
state = afterSunday,
|
||||||
|
checkedThrough = mon,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertEquals(StickVerdict.MISS, run.verdicts.last().verdict)
|
||||||
|
assertEquals(2, run.state.streak)
|
||||||
|
assertEquals(tue.plusDays(2), run.state.lockedThrough)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aLateFridayWithNoBypassChangesNothing() {
|
||||||
|
val run = StickCheck.run(inputs(fri.atTime(11, 0)))
|
||||||
|
assertEquals(StickVerdict.NOT_STICK_DAY, run.verdicts.single().verdict)
|
||||||
|
assertEquals(StickState(), run.state)
|
||||||
|
assertNull(run.signalUntil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun freeAndSickDaysStayNeutralEvenWithABypass() {
|
||||||
|
val free = StickCheck.run(inputs(sun.atTime(8, 0), bypass = setOf(sun), free = setOf(sun)))
|
||||||
|
assertEquals(StickVerdict.FREE_DAY, free.verdicts.single().verdict)
|
||||||
|
val sick = StickCheck.run(inputs(tue.atTime(8, 0), bypass = setOf(tue), sick = setOf(tue)))
|
||||||
|
assertEquals(StickVerdict.SICK_DAY, sick.verdicts.single().verdict)
|
||||||
|
assertEquals(StickState(), sick.state)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aBypassCountsOnlyOnARingingDayWithARingOrSessionLive() {
|
||||||
|
assertTrue(BypassRules.counts(ringingDay = true, ringLive = true, sessionLive = false))
|
||||||
|
assertTrue(BypassRules.counts(ringingDay = true, ringLive = false, sessionLive = true))
|
||||||
|
assertFalse(BypassRules.counts(ringingDay = true, ringLive = false, sessionLive = false))
|
||||||
|
assertFalse(BypassRules.counts(ringingDay = false, ringLive = true, sessionLive = true))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aRingIsKilledWhenItFiredUndismissedAndNothingRings() {
|
||||||
|
assertTrue(BypassRules.ringKilled(firedToday = true, dismissedToday = false, ringing = false))
|
||||||
|
assertFalse(BypassRules.ringKilled(firedToday = true, dismissedToday = false, ringing = true))
|
||||||
|
assertFalse(BypassRules.ringKilled(firedToday = true, dismissedToday = true, ringing = false))
|
||||||
|
assertFalse(BypassRules.ringKilled(firedToday = false, dismissedToday = false, ringing = false))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun theSameCauseWithinAMinuteIsARepeat() {
|
||||||
|
val last = "fsi_revoked" to 1_000L
|
||||||
|
assertFalse(BypassRules.isRepeat(null, "fsi_revoked", 1_000L, 60_000L))
|
||||||
|
assertTrue(BypassRules.isRepeat(last, "fsi_revoked", 60_999L, 60_000L))
|
||||||
|
assertFalse(BypassRules.isRepeat(last, "fsi_revoked", 61_000L, 60_000L))
|
||||||
|
assertFalse(BypassRules.isRepeat(last, "suspended", 2_000L, 60_000L))
|
||||||
|
assertFalse(BypassRules.isRepeat(last, "fsi_revoked", 999L, 60_000L))
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -60,7 +60,7 @@ class StickCheckSickTest {
|
|||||||
fun aSickDayIsSkippedWhenTheStreakLooksBack() {
|
fun aSickDayIsSkippedWhenTheStreakLooksBack() {
|
||||||
// Missed Tuesday, sick Wednesday: Thursday's miss continues the chain.
|
// Missed Tuesday, sick Wednesday: Thursday's miss continues the chain.
|
||||||
val before = StickState(streak = 1, lockedThrough = wed, lastMiss = tue)
|
val before = StickState(streak = 1, lockedThrough = wed, lastMiss = tue)
|
||||||
val after = StickCheck.afterMiss(thu, before) { it == wed }
|
val after = StickCheck.afterMiss(thu, before, standsDown = { it == wed })
|
||||||
assertEquals(2, after.streak)
|
assertEquals(2, after.streak)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -0,0 +1,87 @@
|
|||||||
|
package com.kuhy.wake_alarm_sync
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import java.time.LocalDate
|
||||||
|
import java.time.LocalDateTime
|
||||||
|
import java.time.LocalTime
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A day already penalised re-sends the lockdown it bought (2026-11-22, C6):
|
||||||
|
* the one signal went out while focus-owner was neither Device Owner nor
|
||||||
|
* running, and every later bypass that day got `already_penalised` and sent
|
||||||
|
* nothing, so the lockdown never landed.
|
||||||
|
*/
|
||||||
|
class StickResendTest {
|
||||||
|
// 2026-11-22 is a Sunday, 24 a Tuesday.
|
||||||
|
private val sun = LocalDate.of(2026, 11, 22)
|
||||||
|
private val mon = sun.plusDays(1)
|
||||||
|
private val tue = sun.plusDays(2)
|
||||||
|
|
||||||
|
private fun inputs(
|
||||||
|
now: LocalDateTime,
|
||||||
|
state: StickState,
|
||||||
|
escaped: Set<LocalDate> = emptySet(),
|
||||||
|
) = StickInputs(
|
||||||
|
now = now,
|
||||||
|
alarm = LocalTime.of(7, 30),
|
||||||
|
dismissedOn = { false },
|
||||||
|
escapedOn = { it in escaped },
|
||||||
|
isFree = { false },
|
||||||
|
isSick = { false },
|
||||||
|
state = state,
|
||||||
|
checkedThrough = now.toLocalDate(),
|
||||||
|
bypassOn = { it == sun },
|
||||||
|
)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aSecondBypassTheSameDayResendsTheSameLockdown() {
|
||||||
|
val afterSunday = StickState(streak = 1, lockedThrough = mon, lastMiss = sun)
|
||||||
|
val run = StickCheck.run(inputs(sun.atTime(8, 0), afterSunday))
|
||||||
|
assertEquals(StickVerdict.ALREADY_PENALISED, run.verdicts.single().verdict)
|
||||||
|
assertEquals(mon, run.signalUntil)
|
||||||
|
assertTrue(run.resend)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aResendNeverExtendsTheStreakOrTheDate() {
|
||||||
|
val stacked = StickState(streak = 3, lockedThrough = sun.plusDays(3), lastMiss = sun)
|
||||||
|
val run = StickCheck.run(inputs(sun.atTime(9, 0), stacked))
|
||||||
|
assertEquals(stacked, run.state)
|
||||||
|
assertEquals(sun.plusDays(3), run.signalUntil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aLockdownThatAlreadyEndedIsNotResent() {
|
||||||
|
val ended = StickState(streak = 1, lockedThrough = sun.minusDays(1), lastMiss = sun)
|
||||||
|
val run = StickCheck.run(inputs(sun.atTime(8, 0), ended))
|
||||||
|
assertEquals(StickVerdict.ALREADY_PENALISED, run.verdicts.single().verdict)
|
||||||
|
assertNull(run.signalUntil)
|
||||||
|
assertFalse(run.resend)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun noStoredDateMeansNothingToResend() {
|
||||||
|
val undated = StickState(streak = 1, lockedThrough = null, lastMiss = sun)
|
||||||
|
assertNull(StickCheck.run(inputs(sun.atTime(8, 0), undated)).signalUntil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun anEscapedDayIsNotResent() {
|
||||||
|
val afterSunday = StickState(streak = 1, lockedThrough = mon, lastMiss = sun)
|
||||||
|
val run = StickCheck.run(inputs(sun.atTime(8, 0), afterSunday, escaped = setOf(sun)))
|
||||||
|
assertEquals(StickVerdict.ESCAPED, run.verdicts.single().verdict)
|
||||||
|
assertNull(run.signalUntil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aFreshMissIsSentButNotMarkedAResend() {
|
||||||
|
val run = StickCheck.run(inputs(tue.atTime(9, 0), StickState()))
|
||||||
|
assertEquals(StickVerdict.MISS, run.verdicts.single().verdict)
|
||||||
|
assertEquals(tue.plusDays(1), run.signalUntil)
|
||||||
|
assertFalse(run.resend)
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,4 +1,8 @@
|
|||||||
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
|
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
|
||||||
|
# Build cache: a fresh worktree reuses plugin/Kotlin/dex task outputs from ~/.gradle/caches/build-cache-1.
|
||||||
|
# (~/.gradle/gradle.properties wins over this file, so its daemon=false and jvmargs still apply.)
|
||||||
|
org.gradle.caching=true
|
||||||
|
org.gradle.parallel=true
|
||||||
android.useAndroidX=true
|
android.useAndroidX=true
|
||||||
# This newDsl flag was added by the Flutter template
|
# This newDsl flag was added by the Flutter template
|
||||||
android.newDsl=false
|
android.newDsl=false
|
||||||
|
|||||||
@ -11,6 +11,7 @@ import 'package:wake_alarm_sync/screens/session_screen.dart';
|
|||||||
import 'package:wake_alarm_sync/services/alarm_policy.dart';
|
import 'package:wake_alarm_sync/services/alarm_policy.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/day_pool_refresh.dart';
|
import 'package:wake_alarm_sync/services/day_pool_refresh.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/enforcement_publish.dart';
|
||||||
import 'package:wake_alarm_sync/services/headless_ring_start.dart';
|
import 'package:wake_alarm_sync/services/headless_ring_start.dart';
|
||||||
import 'package:wake_alarm_sync/ui/app_name.dart';
|
import 'package:wake_alarm_sync/ui/app_name.dart';
|
||||||
import 'package:wake_alarm_sync/ui/theme.dart';
|
import 'package:wake_alarm_sync/ui/theme.dart';
|
||||||
@ -45,6 +46,10 @@ Future<void> main() async {
|
|||||||
@pragma('vm:entry-point')
|
@pragma('vm:entry-point')
|
||||||
Future<void> ringStartedMain() => runHeadlessRingStart();
|
Future<void> ringStartedMain() => runHeadlessRingStart();
|
||||||
|
|
||||||
|
/// Headless entry point: `Bypass.kt` starts it to push a bypass at once.
|
||||||
|
@pragma('vm:entry-point')
|
||||||
|
Future<void> publishNowMain() => runHeadlessPublish();
|
||||||
|
|
||||||
/// Headless entry point: `PoolSyncReceiver.kt` starts it in the evening and
|
/// Headless entry point: `PoolSyncReceiver.kt` starts it in the evening and
|
||||||
/// shortly before the alarm, so a free or sick day marked on the PC reaches
|
/// shortly before the alarm, so a free or sick day marked on the PC reaches
|
||||||
/// the native ring-path caches with the app closed.
|
/// the native ring-path caches with the app closed.
|
||||||
|
|||||||
@ -1,7 +1,8 @@
|
|||||||
import 'package:material_ui/material_ui.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
import 'package:wake_alarm_sync/main.dart';
|
import 'package:wake_alarm_sync/main.dart' as app;
|
||||||
import 'package:wake_alarm_sync/probe/file_driven_scheduler.dart';
|
import 'package:wake_alarm_sync/probe/file_driven_scheduler.dart';
|
||||||
|
import 'package:wake_alarm_sync/probe/probe_passphrase.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/room_proof_settings.dart';
|
import 'package:wake_alarm_sync/services/room_proof_settings.dart';
|
||||||
import 'package:wake_alarm_sync/services/session_tag_settings.dart';
|
import 'package:wake_alarm_sync/services/session_tag_settings.dart';
|
||||||
@ -24,6 +25,7 @@ import 'package:wake_alarm_sync/services/session_tag_settings.dart';
|
|||||||
/// Not part of the shipped app: `flutter build apk` uses `lib/main.dart`.
|
/// Not part of the shipped app: `flutter build apk` uses `lib/main.dart`.
|
||||||
Future<void> main() async {
|
Future<void> main() async {
|
||||||
WidgetsFlutterBinding.ensureInitialized();
|
WidgetsFlutterBinding.ensureInitialized();
|
||||||
|
await plantProbePassphrase();
|
||||||
await RoomProofSettings.saveNfcTagAt(0, 'ring1');
|
await RoomProofSettings.saveNfcTagAt(0, 'ring1');
|
||||||
await RoomProofSettings.saveNfcTagAt(1, 'ring2');
|
await RoomProofSettings.saveNfcTagAt(1, 'ring2');
|
||||||
await SessionTagSettings.saveTagAt(SessionTagSlot.bathroom, 'bath');
|
await SessionTagSettings.saveTagAt(SessionTagSlot.bathroom, 'bath');
|
||||||
@ -31,5 +33,22 @@ Future<void> main() async {
|
|||||||
await SessionTagSettings.saveTagAt(SessionTagSlot.desk, 'desk');
|
await SessionTagSettings.saveTagAt(SessionTagSlot.desk, 'desk');
|
||||||
final scheduler = AlarmScheduler();
|
final scheduler = AlarmScheduler();
|
||||||
if (!await scheduler.morningLive()) await scheduler.ringNow();
|
if (!await scheduler.morningLive()) await scheduler.ringNow();
|
||||||
runApp(const WakeAlarmSyncApp(newScheduler: FileDrivenScheduler.new));
|
runApp(const app.WakeAlarmSyncApp(newScheduler: FileDrivenScheduler.new));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Kotlin starts the headless engines by entrypoint *name*, resolved in the
|
||||||
|
// root library: the `-t` file. Without these the probe build's bypass,
|
||||||
|
// ring_started and pool-sync engines failed with "Could not resolve main
|
||||||
|
// entrypoint function" and published nothing (C6, emulator 2026-11-22).
|
||||||
|
|
||||||
|
/// See `main.dart`'s [app.ringStartedMain].
|
||||||
|
@pragma('vm:entry-point')
|
||||||
|
Future<void> ringStartedMain() => app.ringStartedMain();
|
||||||
|
|
||||||
|
/// See `main.dart`'s [app.publishNowMain].
|
||||||
|
@pragma('vm:entry-point')
|
||||||
|
Future<void> publishNowMain() => app.publishNowMain();
|
||||||
|
|
||||||
|
/// See `main.dart`'s [app.poolSyncMain].
|
||||||
|
@pragma('vm:entry-point')
|
||||||
|
Future<void> poolSyncMain() => app.poolSyncMain();
|
||||||
|
|||||||
22
phone_app/lib/probe/probe_passphrase.dart
Normal file
22
phone_app/lib/probe/probe_passphrase.dart
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
// phone-slot: not-shared-storage (path is per-package: Android/data/<package>/files)
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart';
|
||||||
|
import 'package:path/path.dart' as p;
|
||||||
|
import 'package:path_provider/path_provider.dart';
|
||||||
|
|
||||||
|
/// Moves an adb-written `files/passphrase` into the keystore, then deletes it.
|
||||||
|
///
|
||||||
|
/// The emulator syncs to the PC's RTDB emulator (`sync_emulator.dart`), and
|
||||||
|
/// every push is end-to-end encrypted: with no passphrase in the keystore it
|
||||||
|
/// throws `SyncLockedException` and nothing is published. The live checks
|
||||||
|
/// give the AVD a dummy test passphrase this way, never the real one, and
|
||||||
|
/// the file does not outlive the first launch. Probe-only.
|
||||||
|
Future<void> plantProbePassphrase() async {
|
||||||
|
final dir = await getExternalStorageDirectory();
|
||||||
|
if (dir == null) return;
|
||||||
|
final file = File(p.join(dir.path, 'passphrase'));
|
||||||
|
if (!file.existsSync()) return;
|
||||||
|
await saveE2ePassphrase((await file.readAsString()).trim());
|
||||||
|
await file.delete();
|
||||||
|
}
|
||||||
@ -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),
|
||||||
|
|||||||
@ -176,7 +176,7 @@ class _SessionScreenState extends State<SessionScreen> {
|
|||||||
// The native deadline already rang (see [AlarmScheduler.isRinging]):
|
// The native deadline already rang (see [AlarmScheduler.isRinging]):
|
||||||
// the dismiss sequence belongs in front now, not after the 20 s grace.
|
// the dismiss sequence belongs in front now, not after the 20 s grace.
|
||||||
if (session.isActive && await _scheduler.isRinging()) {
|
if (session.isActive && await _scheduler.isRinging()) {
|
||||||
await _ring('deadline:${session.currentLeg!.name}', now);
|
await _ring(await nativeRingReason(_scheduler, session), now);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
|
|||||||
@ -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;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -207,6 +207,16 @@ class AlarmScheduler {
|
|||||||
Future<bool> isRinging() async =>
|
Future<bool> isRinging() async =>
|
||||||
await _channel.invokeMethod<bool>('isRinging') ?? false;
|
await _channel.invokeMethod<bool>('isRinging') ?? false;
|
||||||
|
|
||||||
|
/// The cause of a bypass that started today's ring during a live session,
|
||||||
|
/// or null; taking it clears it, so one bypass names one re-ring.
|
||||||
|
Future<String?> takeBypassReRing() =>
|
||||||
|
_channel.invokeMethod<String>('takeBypassReRing');
|
||||||
|
|
||||||
|
/// [takeBypassReRing] without clearing it, for the session screen's tick:
|
||||||
|
/// two screens can tick on one ring, and only the dismiss records it.
|
||||||
|
Future<String?> peekBypassReRing() =>
|
||||||
|
_channel.invokeMethod<String>('peekBypassReRing');
|
||||||
|
|
||||||
/// Raw presence observations: `ssid`, `bssid`, `lat`, `lon`, `accuracy`,
|
/// Raw presence observations: `ssid`, `bssid`, `lat`, `lon`, `accuracy`,
|
||||||
/// `distanceMeters`, `reason`.
|
/// `distanceMeters`, `reason`.
|
||||||
///
|
///
|
||||||
|
|||||||
64
phone_app/lib/services/enforcement_publish.dart
Normal file
64
phone_app/lib/services/enforcement_publish.dart
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
/// Pushes the enforcement fields now, not at the next sync.
|
||||||
|
///
|
||||||
|
/// Two moments need it (2026-11-22): a bypass (the app paused, its admin
|
||||||
|
/// removed, a permission revoked, the ring killed), which the native side
|
||||||
|
/// records and then starts `publishNowMain` for, and a completed dismiss.
|
||||||
|
/// The PC rings for a bypass until it reads a `dismissed` newer than it, so
|
||||||
|
/// both have to reach Firebase within a poll, not minutes later.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:developer' as developer;
|
||||||
|
import 'dart:ui' show DartPluginRegistrant;
|
||||||
|
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter/widgets.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/alarm_sync_service.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/enforcement_sync.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/firebase_backend.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/headless_ring_start.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/sync_settings.dart';
|
||||||
|
|
||||||
|
/// Stages the enforcement fields (the event log included) and pushes.
|
||||||
|
///
|
||||||
|
/// Returns whether the push reached a backend. Never throws: the caller is
|
||||||
|
/// a ring or a dismiss, and neither may wait on a broken network.
|
||||||
|
Future<bool> publishEnforcementNow({
|
||||||
|
Future<AlarmSyncService> Function()? open,
|
||||||
|
Future<void> Function(AlarmSyncService service, String token)? push,
|
||||||
|
}) async {
|
||||||
|
try {
|
||||||
|
final settings = await SyncSettings.load();
|
||||||
|
final hasFirebase = await loadAccount() != null;
|
||||||
|
if (!settings.isConfigured && !hasFirebase) {
|
||||||
|
debugPrint('WakeAlarmPublish: no sync backend');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
final service = await (open ?? AlarmSyncService.open)();
|
||||||
|
await stageEnforcementData(service);
|
||||||
|
await (push ?? ((s, token) => s.push(token)))(service, settings.token);
|
||||||
|
debugPrint('WakeAlarmPublish: pushed');
|
||||||
|
return true;
|
||||||
|
} on Object catch (e) {
|
||||||
|
debugPrint('WakeAlarmPublish: not pushed: $e');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `publishNowMain` engine's whole job: publish, then say done.
|
||||||
|
Future<void> runHeadlessPublish({
|
||||||
|
Future<bool> Function()? publish,
|
||||||
|
MethodChannel? channel,
|
||||||
|
}) async {
|
||||||
|
WidgetsFlutterBinding.ensureInitialized();
|
||||||
|
DartPluginRegistrant.ensureInitialized();
|
||||||
|
try {
|
||||||
|
await (publish ?? publishEnforcementNow)();
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
await (channel ?? const MethodChannel(headlessChannelName))
|
||||||
|
.invokeMethod<void>('done');
|
||||||
|
} on Object catch (e) {
|
||||||
|
developer.log('headless done not delivered: $e', name: 'WakeAlarmRing');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -17,6 +17,7 @@ import 'package:crdt_sync/crdt_sync.dart';
|
|||||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
import 'package:wake_alarm_sync/services/google_sign_in_backend.dart';
|
import 'package:wake_alarm_sync/services/google_sign_in_backend.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/sync_emulator.dart';
|
||||||
|
|
||||||
/// The shared `kuhy-syncs` project.
|
/// The shared `kuhy-syncs` project.
|
||||||
///
|
///
|
||||||
@ -48,6 +49,7 @@ SecureCredentialStore credentialStore() => SecureCredentialStore(
|
|||||||
|
|
||||||
/// Reads the per-device account, or null when sync has not been set up.
|
/// Reads the per-device account, or null when sync has not been set up.
|
||||||
Future<FirebaseAccount?> loadAccount() async {
|
Future<FirebaseAccount?> loadAccount() async {
|
||||||
|
if (syncEmulatorOn) return emulatorAccount;
|
||||||
try {
|
try {
|
||||||
return FirebaseAccount.tryParse(
|
return FirebaseAccount.tryParse(
|
||||||
await _secure.read(key: kFirebaseAccountKey),
|
await _secure.read(key: kFirebaseAccountKey),
|
||||||
@ -82,6 +84,7 @@ Future<void> clearAccount() async {
|
|||||||
/// Signs in with the stored password only when there is no cached refresh
|
/// Signs in with the stored password only when there is no cached refresh
|
||||||
/// token, so the usual path costs no authentication round trip.
|
/// token, so the usual path costs no authentication round trip.
|
||||||
Future<FirebaseRestClient?> openFirebase() async {
|
Future<FirebaseRestClient?> openFirebase() async {
|
||||||
|
if (syncEmulatorOn) return emulatorClient();
|
||||||
final account = await loadAccount();
|
final account = await loadAccount();
|
||||||
if (account == null) {
|
if (account == null) {
|
||||||
// A stored refresh token IS a signed-in device, even with no account
|
// A stored refresh token IS a signed-in device, even with no account
|
||||||
@ -113,6 +116,7 @@ Future<FirebaseRestClient?> openFirebase() async {
|
|||||||
/// a working device "not connected", which is exactly how a phone that was in
|
/// a working device "not connected", which is exactly how a phone that was in
|
||||||
/// fact syncing looked broken.
|
/// fact syncing looked broken.
|
||||||
Future<bool> isFirebaseConfigured() async {
|
Future<bool> isFirebaseConfigured() async {
|
||||||
|
if (syncEmulatorOn) return true;
|
||||||
try {
|
try {
|
||||||
final auth = FirebaseTokenProvider(
|
final auth = FirebaseTokenProvider(
|
||||||
apiKey: kProject.apiKey,
|
apiKey: kProject.apiKey,
|
||||||
@ -214,6 +218,8 @@ Future<FirebaseRestClient?> _clientFromStoredSession() async {
|
|||||||
/// (`_fetch_firebase_alarm() or _fetch_github_alarm()`), so a phone that has
|
/// (`_fetch_firebase_alarm() or _fetch_github_alarm()`), so a phone that has
|
||||||
/// not moved yet still reaches it.
|
/// not moved yet still reaches it.
|
||||||
Future<RemoteStore> syncBackend(RemoteStore github) async {
|
Future<RemoteStore> syncBackend(RemoteStore github) async {
|
||||||
|
// The emulator alone: a mirror beside it would write prod GitHub.
|
||||||
|
if (syncEmulatorOn) return emulatorClient();
|
||||||
final firebase = await openFirebase();
|
final firebase = await openFirebase();
|
||||||
return firebase == null
|
return firebase == null
|
||||||
? github
|
? github
|
||||||
|
|||||||
@ -1,4 +1,7 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/enforcement_publish.dart';
|
||||||
import 'package:wake_alarm_sync/services/morning_session.dart';
|
import 'package:wake_alarm_sync/services/morning_session.dart';
|
||||||
import 'package:wake_alarm_sync/services/session_rules.dart';
|
import 'package:wake_alarm_sync/services/session_rules.dart';
|
||||||
import 'package:wake_alarm_sync/services/session_store.dart';
|
import 'package:wake_alarm_sync/services/session_store.dart';
|
||||||
@ -16,8 +19,10 @@ class SessionHandoff {
|
|||||||
required this.scheduler,
|
required this.scheduler,
|
||||||
SessionStore? store,
|
SessionStore? store,
|
||||||
DateTime Function()? now,
|
DateTime Function()? now,
|
||||||
|
Future<bool> Function()? publishNow,
|
||||||
}) : store = store ?? SessionStore(),
|
}) : store = store ?? SessionStore(),
|
||||||
_now = now ?? DateTime.now;
|
_now = now ?? DateTime.now,
|
||||||
|
_publishNow = publishNow ?? publishEnforcementNow;
|
||||||
|
|
||||||
/// Platform bridge, for the NFC availability check.
|
/// Platform bridge, for the NFC availability check.
|
||||||
final AlarmScheduler scheduler;
|
final AlarmScheduler scheduler;
|
||||||
@ -27,6 +32,10 @@ class SessionHandoff {
|
|||||||
|
|
||||||
final DateTime Function() _now;
|
final DateTime Function() _now;
|
||||||
|
|
||||||
|
/// Pushes the `dismissed` event at once: the PC rings for a bypass until
|
||||||
|
/// it reads one newer than the bypass.
|
||||||
|
final Future<bool> Function() _publishNow;
|
||||||
|
|
||||||
/// Starts or resumes today's session; false when the ring should just end.
|
/// Starts or resumes today's session; false when the ring should just end.
|
||||||
///
|
///
|
||||||
/// [away] is the ring's verdict that the phone is not at home: no scale,
|
/// [away] is the ring's verdict that the phone is not at home: no scale,
|
||||||
@ -38,12 +47,16 @@ class SessionHandoff {
|
|||||||
// recorded before anything else so an interrupted await below still
|
// recorded before anything else so an interrupted await below still
|
||||||
// leaves the native side knowing the ring was answered.
|
// leaves the native side knowing the ring was answered.
|
||||||
await scheduler.markRingDismissed();
|
await scheduler.markRingDismissed();
|
||||||
|
// Not awaited: the session must not wait on the network.
|
||||||
|
unawaited(_publishNow());
|
||||||
final now = _now();
|
final now = _now();
|
||||||
final today = SessionRules.dateKey(now);
|
final today = SessionRules.dateKey(now);
|
||||||
final current = await store.loadCurrent();
|
final current = await store.loadCurrent();
|
||||||
if (current != null && current.date == today) {
|
if (current != null && current.date == today) {
|
||||||
if (!current.isActive) return false;
|
if (!current.isActive) return false;
|
||||||
current.recordReRing(now);
|
current
|
||||||
|
..adoptBypassReRing(await scheduler.takeBypassReRing())
|
||||||
|
..recordReRing(now);
|
||||||
await store.save(current);
|
await store.save(current);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -34,6 +34,13 @@ Future<void> pointNativeAtLeg(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Why the sound the session screen just found is ringing: the bypass
|
||||||
|
/// `Bypass.kt` stamped for it, else the live leg's deadline.
|
||||||
|
Future<String> nativeRingReason(
|
||||||
|
AlarmScheduler scheduler,
|
||||||
|
MorningSession session,
|
||||||
|
) async => session.reRingReasonFor(await scheduler.peekBypassReRing());
|
||||||
|
|
||||||
/// The notification's one line: glyph + position count, with a running-clock
|
/// The notification's one line: glyph + position count, with a running-clock
|
||||||
/// marker when the re-ring was spent.
|
/// marker when the re-ring was spent.
|
||||||
String noticeLabel(MorningSession session) {
|
String noticeLabel(MorningSession session) {
|
||||||
|
|||||||
@ -162,6 +162,18 @@ extension SessionRules on MorningSession {
|
|||||||
updatedAt = now;
|
updatedAt = now;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Names the re-ring a bypass started natively (`Bypass.kt` stamps
|
||||||
|
/// [cause] only when nothing was ringing yet), overriding a deadline mark:
|
||||||
|
/// the screen saw the sound before it saw why. Null leaves the mark.
|
||||||
|
void adoptBypassReRing(String? cause) {
|
||||||
|
if (cause != null) pendingReRingReason = reRingReasonFor(cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `bypass:<cause>` for a bypass's re-ring, else the live leg's deadline.
|
||||||
|
String reRingReasonFor(String? cause) => cause == null
|
||||||
|
? 'deadline:${currentLeg?.name ?? 'none'}'
|
||||||
|
: 'bypass:$cause';
|
||||||
|
|
||||||
/// Records that a re-ring was dismissed; the session resumes here.
|
/// Records that a re-ring was dismissed; the session resumes here.
|
||||||
///
|
///
|
||||||
/// A leg whose deadline has already passed is marked as rung whatever the
|
/// A leg whose deadline has already passed is marked as rung whatever the
|
||||||
@ -170,7 +182,7 @@ extension SessionRules on MorningSession {
|
|||||||
void recordReRing(DateTime now) {
|
void recordReRing(DateTime now) {
|
||||||
final leg = currentLeg;
|
final leg = currentLeg;
|
||||||
reRings++;
|
reRings++;
|
||||||
reRingReasons.add(pendingReRingReason ?? 'deadline:${leg?.name ?? 'none'}');
|
reRingReasons.add(pendingReRingReason ?? reRingReasonFor(null));
|
||||||
pendingReRingReason = null;
|
pendingReRingReason = null;
|
||||||
if (leg != null && !now.isBefore(deadline(leg))) deadlineRung.add(leg);
|
if (leg != null && !now.isBefore(deadline(leg))) deadlineRung.add(leg);
|
||||||
updatedAt = now;
|
updatedAt = now;
|
||||||
|
|||||||
51
phone_app/lib/services/sync_emulator.dart
Normal file
51
phone_app/lib/services/sync_emulator.dart
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
/// A debug-only sync backend: the Firebase RTDB emulator on the PC.
|
||||||
|
///
|
||||||
|
/// The emulator checks (a bypass reaching "the test backend") need a
|
||||||
|
/// backend, and the AVD must never sign in to prod: a probe's per-date
|
||||||
|
/// merge would overwrite the phone's real morning. So the probe build
|
||||||
|
/// passes `--dart-define=WAKE_SYNC_EMULATOR=http://10.0.2.2:9000` (the AVD's
|
||||||
|
/// name for the PC's loopback), and every sync open then returns this client
|
||||||
|
/// *instead of* prod Firebase and the GitHub mirror, never beside them.
|
||||||
|
///
|
||||||
|
/// The define is a compile-time constant: release and `deploy.sh` builds
|
||||||
|
/// never set it, so there the branch is dead code. The emulator answers
|
||||||
|
/// `auth=owner` as admin, so no Google sign-in is involved.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
|
||||||
|
/// The emulator's origin, or empty (every release build).
|
||||||
|
const String kSyncEmulatorUrl = String.fromEnvironment('WAKE_SYNC_EMULATOR');
|
||||||
|
|
||||||
|
/// Whether this build syncs to the emulator only.
|
||||||
|
bool get syncEmulatorOn => kSyncEmulatorUrl.isNotEmpty;
|
||||||
|
|
||||||
|
/// The account marker the sync gates look for; carries no credential.
|
||||||
|
const FirebaseAccount emulatorAccount = FirebaseAccount(
|
||||||
|
email: 'emulator',
|
||||||
|
password: '',
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Signs every request `auth=owner`, the emulator's admin token.
|
||||||
|
class EmulatorTokenProvider extends FirebaseTokenProvider {
|
||||||
|
/// Creates a provider that never talks to Google.
|
||||||
|
EmulatorTokenProvider()
|
||||||
|
: super(apiKey: 'emulator', store: InMemoryCredentialStore());
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String> idToken() async => 'owner';
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> hasSession() async => true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A client for the emulator at [url].
|
||||||
|
FirebaseRestClient emulatorClient({
|
||||||
|
String url = kSyncEmulatorUrl,
|
||||||
|
http.Client? httpClient,
|
||||||
|
}) => FirebaseRestClient(
|
||||||
|
databaseUrl: url,
|
||||||
|
auth: EmulatorTokenProvider(),
|
||||||
|
httpClient: httpClient,
|
||||||
|
);
|
||||||
@ -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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -101,20 +101,20 @@ packages:
|
|||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
path: crdt_sync_dart
|
path: crdt_sync_dart
|
||||||
ref: "crdt_sync_dart-v0.14.1"
|
ref: "crdt_sync_dart-v0.14.2"
|
||||||
resolved-ref: edd0f7a7882cb1d3904932ba94faa282d08165df
|
resolved-ref: "171a7f8ae34cec78df17a680e42878ca0b97c137"
|
||||||
url: "https://github.com/kuhyx/utils"
|
url: "https://github.com/kuhyx/utils"
|
||||||
source: git
|
source: git
|
||||||
version: "0.14.1"
|
version: "0.14.2"
|
||||||
crdt_sync_flutter:
|
crdt_sync_flutter:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
path: crdt_sync_flutter
|
path: crdt_sync_flutter
|
||||||
ref: "crdt_sync_flutter-v0.9.1"
|
ref: "crdt_sync_flutter-v0.9.2"
|
||||||
resolved-ref: "48dc28ad97b97c787aba4479c3ce51aade6e86b5"
|
resolved-ref: "41af57870207f80a5bf571f15544a08fddcbe7bf"
|
||||||
url: "https://github.com/kuhyx/utils"
|
url: "https://github.com/kuhyx/utils"
|
||||||
source: git
|
source: git
|
||||||
version: "0.9.1"
|
version: "0.9.2"
|
||||||
cross_file:
|
cross_file:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -159,11 +159,11 @@ packages:
|
|||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
path: data_transfer_flutter
|
path: data_transfer_flutter
|
||||||
ref: "data_transfer_flutter-v0.2.3"
|
ref: "data_transfer_flutter-v0.2.4"
|
||||||
resolved-ref: bb2f92f459283a29ad4864cf37704cc5f749cc6d
|
resolved-ref: "5c2effe7d1148830c9e273e47a272791dc17509e"
|
||||||
url: "https://github.com/kuhyx/utils"
|
url: "https://github.com/kuhyx/utils"
|
||||||
source: git
|
source: git
|
||||||
version: "0.2.3"
|
version: "0.2.4"
|
||||||
dbus:
|
dbus:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -208,10 +208,10 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: file_picker
|
name: file_picker
|
||||||
sha256: c3780977700b8962c3b9b6a9aa4e2c988956893d70d4a4fa2d7adf4ec9b9eaee
|
sha256: "5b99250437a4d34ee2cdc0686924452103540eaa1c248094b63f07f9d7216f6c"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "13.4.0"
|
version: "13.4.1"
|
||||||
file_picker_darwin:
|
file_picker_darwin:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -224,10 +224,10 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: file_picker_linux
|
name: file_picker_linux
|
||||||
sha256: "9215ee8c672508cdd9a325202669f849e1baac883658626b3abed5d7777e6a4b"
|
sha256: cf3889644e8e54551f5c3a4f98b6b6ef5f0ef85c07d2a0c1a969538983be2f9b
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.0.4"
|
version: "2.0.5"
|
||||||
file_picker_platform_interface:
|
file_picker_platform_interface:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -478,11 +478,11 @@ packages:
|
|||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
path: "kuhy_credit/flutter"
|
path: "kuhy_credit/flutter"
|
||||||
ref: "kuhy-credit-v0.3.1"
|
ref: "kuhy-credit-v0.3.2"
|
||||||
resolved-ref: "2352c177232a4b4594573a3b1126697ef32851f7"
|
resolved-ref: adeb40f68e1d6c701da43e396fc46bffa3ef10c7
|
||||||
url: "https://github.com/kuhyx/utils"
|
url: "https://github.com/kuhyx/utils"
|
||||||
source: git
|
source: git
|
||||||
version: "0.3.1"
|
version: "0.3.2"
|
||||||
leak_tracker:
|
leak_tracker:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -812,11 +812,11 @@ packages:
|
|||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
path: sync_settings_ui
|
path: sync_settings_ui
|
||||||
ref: "sync_settings_ui-v0.8.4"
|
ref: "sync_settings_ui-v0.8.6"
|
||||||
resolved-ref: "15ef5b44f186cea0ab163cc88cb8743c51d58247"
|
resolved-ref: "41af57870207f80a5bf571f15544a08fddcbe7bf"
|
||||||
url: "https://github.com/kuhyx/utils"
|
url: "https://github.com/kuhyx/utils"
|
||||||
source: git
|
source: git
|
||||||
version: "0.8.4"
|
version: "0.8.6"
|
||||||
term_glyph:
|
term_glyph:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
|||||||
@ -12,13 +12,13 @@ dependencies:
|
|||||||
crdt_sync:
|
crdt_sync:
|
||||||
git:
|
git:
|
||||||
url: https://github.com/kuhyx/utils
|
url: https://github.com/kuhyx/utils
|
||||||
ref: crdt_sync_dart-v0.14.1
|
ref: crdt_sync_dart-v0.14.2
|
||||||
path: crdt_sync_dart
|
path: crdt_sync_dart
|
||||||
# Keystore-backed end-to-end encryption open + the passphrase lock button.
|
# Keystore-backed end-to-end encryption open + the passphrase lock button.
|
||||||
crdt_sync_flutter:
|
crdt_sync_flutter:
|
||||||
git:
|
git:
|
||||||
url: https://github.com/kuhyx/utils
|
url: https://github.com/kuhyx/utils
|
||||||
ref: crdt_sync_flutter-v0.9.1
|
ref: crdt_sync_flutter-v0.9.2
|
||||||
path: crdt_sync_flutter
|
path: crdt_sync_flutter
|
||||||
cupertino_icons: 2.0.0
|
cupertino_icons: 2.0.0
|
||||||
|
|
||||||
@ -26,7 +26,7 @@ dependencies:
|
|||||||
data_transfer_flutter:
|
data_transfer_flutter:
|
||||||
git:
|
git:
|
||||||
url: https://github.com/kuhyx/utils
|
url: https://github.com/kuhyx/utils
|
||||||
ref: data_transfer_flutter-v0.2.3
|
ref: data_transfer_flutter-v0.2.4
|
||||||
path: data_transfer_flutter
|
path: data_transfer_flutter
|
||||||
flutter:
|
flutter:
|
||||||
sdk: flutter
|
sdk: flutter
|
||||||
@ -48,7 +48,7 @@ dependencies:
|
|||||||
kuhy_credit:
|
kuhy_credit:
|
||||||
git:
|
git:
|
||||||
url: https://github.com/kuhyx/utils
|
url: https://github.com/kuhyx/utils
|
||||||
ref: kuhy-credit-v0.3.1
|
ref: kuhy-credit-v0.3.2
|
||||||
path: kuhy_credit/flutter
|
path: kuhy_credit/flutter
|
||||||
material_ui: 1.11.1
|
material_ui: 1.11.1
|
||||||
path: 1.9.1
|
path: 1.9.1
|
||||||
@ -61,7 +61,7 @@ dependencies:
|
|||||||
sync_settings_ui:
|
sync_settings_ui:
|
||||||
git:
|
git:
|
||||||
url: https://github.com/kuhyx/utils
|
url: https://github.com/kuhyx/utils
|
||||||
ref: sync_settings_ui-v0.8.4
|
ref: sync_settings_ui-v0.8.6
|
||||||
path: sync_settings_ui
|
path: sync_settings_ui
|
||||||
url_launcher: 6.3.3
|
url_launcher: 6.3.3
|
||||||
uuid: 4.6.0
|
uuid: 4.6.0
|
||||||
|
|||||||
@ -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', () {
|
||||||
|
|||||||
67
phone_app/test/services/enforcement_publish_test.dart
Normal file
67
phone_app/test/services/enforcement_publish_test.dart
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/enforcement_publish.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/headless_ring_start.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/session_handoff.dart';
|
||||||
|
|
||||||
|
/// A bypass and a dismiss reach the PC at once, not at the next sync
|
||||||
|
/// (2026-11-22): the PC rings for a bypass until it sees a newer dismiss.
|
||||||
|
void main() {
|
||||||
|
TestWidgetsFlutterBinding.ensureInitialized();
|
||||||
|
|
||||||
|
late List<String> calls;
|
||||||
|
|
||||||
|
setUp(() {
|
||||||
|
calls = <String>[];
|
||||||
|
SharedPreferences.setMockInitialValues(<String, Object>{});
|
||||||
|
for (final name in [headlessChannelName, AlarmScheduler.channelName]) {
|
||||||
|
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||||
|
.setMockMethodCallHandler(MethodChannel(name), (call) async {
|
||||||
|
calls.add(call.method);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the headless publish pushes once, then says done', () async {
|
||||||
|
var published = 0;
|
||||||
|
await runHeadlessPublish(
|
||||||
|
publish: () async {
|
||||||
|
published++;
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
expect(published, 1);
|
||||||
|
expect(calls, ['done']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('done is sent even when the publish blows up', () async {
|
||||||
|
await expectLater(
|
||||||
|
runHeadlessPublish(publish: () async => throw StateError('boom')),
|
||||||
|
throwsStateError,
|
||||||
|
);
|
||||||
|
expect(calls, ['done']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('with no sync backend nothing is pushed', () async {
|
||||||
|
expect(await publishEnforcementNow(), isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a dismiss publishes at once, after telling native', () async {
|
||||||
|
final order = <String>[];
|
||||||
|
final handoff = SessionHandoff(
|
||||||
|
scheduler: AlarmScheduler(),
|
||||||
|
now: () => DateTime(2026, 11, 22, 7, 40),
|
||||||
|
publishNow: () async {
|
||||||
|
order
|
||||||
|
..addAll(calls)
|
||||||
|
..add('publish');
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
await handoff.afterDismiss(away: true);
|
||||||
|
expect(order, ['markRingDismissed', 'publish']);
|
||||||
|
});
|
||||||
|
}
|
||||||
31
phone_app/test/services/session_bypass_rering_test.dart
Normal file
31
phone_app/test/services/session_bypass_rering_test.dart
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/morning_session.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/session_rules.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/session_tag_settings.dart';
|
||||||
|
|
||||||
|
final DateTime t0 = DateTime(2026, 9, 17, 8, 5);
|
||||||
|
|
||||||
|
MorningSession fresh() => SessionRules.start(
|
||||||
|
now: t0,
|
||||||
|
tags: const SessionTagSettings(tagIds: <String>['bath', 'ward', 'desk']),
|
||||||
|
nfcAvailable: true,
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('a bypass re-ring is named for its cause and counted once', () {
|
||||||
|
final s = fresh()
|
||||||
|
..markReRing('deadline:bathroomIn', t0)
|
||||||
|
..adoptBypassReRing('fsi_revoked')
|
||||||
|
..recordReRing(t0.add(const Duration(minutes: 3)));
|
||||||
|
expect(s.reRings, 1);
|
||||||
|
expect(s.reRingReasons, <String>['bypass:fsi_revoked']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no bypass stamped keeps the deadline reason', () {
|
||||||
|
final s = fresh()
|
||||||
|
..markReRing('deadline:bathroomIn', t0)
|
||||||
|
..adoptBypassReRing(null)
|
||||||
|
..recordReRing(t0.add(const Duration(minutes: 3)));
|
||||||
|
expect(s.reRingReasons, <String>['deadline:bathroomIn']);
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -13,10 +13,12 @@ void main() {
|
|||||||
|
|
||||||
final now = DateTime(2026, 9, 17, 8, 4);
|
final now = DateTime(2026, 9, 17, 8, 4);
|
||||||
var hasNfc = true;
|
var hasNfc = true;
|
||||||
|
String? bypassCause;
|
||||||
late List<String> calls;
|
late List<String> calls;
|
||||||
|
|
||||||
setUp(() {
|
setUp(() {
|
||||||
hasNfc = true;
|
hasNfc = true;
|
||||||
|
bypassCause = null;
|
||||||
calls = <String>[];
|
calls = <String>[];
|
||||||
SharedPreferences.setMockInitialValues(<String, Object>{});
|
SharedPreferences.setMockInitialValues(<String, Object>{});
|
||||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||||
@ -24,6 +26,7 @@ void main() {
|
|||||||
const MethodChannel(AlarmScheduler.channelName),
|
const MethodChannel(AlarmScheduler.channelName),
|
||||||
(call) async {
|
(call) async {
|
||||||
calls.add(call.method);
|
calls.add(call.method);
|
||||||
|
if (call.method == 'takeBypassReRing') return bypassCause;
|
||||||
return call.method == 'hasNfc' ? hasNfc : null;
|
return call.method == 'hasNfc' ? hasNfc : null;
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@ -63,6 +66,23 @@ void main() {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
test('a bypass that rang during a live session names the re-ring', () async {
|
||||||
|
final store = SessionStore();
|
||||||
|
await store.save(
|
||||||
|
SessionRules.start(
|
||||||
|
now: now.subtract(const Duration(minutes: 2)),
|
||||||
|
tags: const SessionTagSettings(tagIds: <String>['b', 'w', 'd']),
|
||||||
|
nfcAvailable: true,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
bypassCause = 'fsi_revoked';
|
||||||
|
expect(await handoff().afterDismiss(away: false), isTrue);
|
||||||
|
final session = (await store.loadCurrent())!;
|
||||||
|
expect(session.reRings, 1);
|
||||||
|
expect(session.reRingReasons, <String>['bypass:fsi_revoked']);
|
||||||
|
expect(calls, contains('takeBypassReRing'));
|
||||||
|
});
|
||||||
|
|
||||||
test('a dismiss during a live session is a re-ring', () async {
|
test('a dismiss during a live session is a re-ring', () async {
|
||||||
final store = SessionStore();
|
final store = SessionStore();
|
||||||
await store.save(
|
await store.save(
|
||||||
|
|||||||
39
phone_app/test/services/sync_emulator_test.dart
Normal file
39
phone_app/test/services/sync_emulator_test.dart
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/firebase_backend.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/sync_emulator.dart';
|
||||||
|
|
||||||
|
/// A [RemoteStore] that is only ever compared by identity.
|
||||||
|
class _Github extends Fake implements RemoteStore {}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test(
|
||||||
|
'a build without the define syncs to prod, never the emulator',
|
||||||
|
() async {
|
||||||
|
expect(kSyncEmulatorUrl, isEmpty);
|
||||||
|
expect(syncEmulatorOn, isFalse);
|
||||||
|
expect(kProject.databaseUrl, contains('kuhy-syncs'));
|
||||||
|
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 {
|
||||||
|
final seen = <Uri>[];
|
||||||
|
final client = emulatorClient(
|
||||||
|
url: 'http://10.0.2.2:9000',
|
||||||
|
httpClient: MockClient((request) async {
|
||||||
|
seen.add(request.url);
|
||||||
|
return http.Response('null', 200);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await client.listDirectory('wake-alarm-sync/devices-e2e');
|
||||||
|
expect(seen.single.origin, 'http://10.0.2.2:9000');
|
||||||
|
expect(seen.single.queryParameters['auth'], 'owner');
|
||||||
|
expect(await EmulatorTokenProvider().hasSession(), isTrue);
|
||||||
|
expect(emulatorAccount.email, 'emulator');
|
||||||
|
});
|
||||||
|
}
|
||||||
70
phone_app/test/session_screen_bypass_test.dart
Normal file
70
phone_app/test/session_screen_bypass_test.dart
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:wake_alarm_sync/screens/session_screen.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/session_store.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/session_tag_settings.dart';
|
||||||
|
|
||||||
|
/// A bypass during a live session restarts the ring natively; the session
|
||||||
|
/// screen finds it sounding and must name the re-ring for the bypass, not
|
||||||
|
/// for the leg's deadline (C7's emulator run recorded `deadline:bathroomIn`).
|
||||||
|
void main() {
|
||||||
|
TestWidgetsFlutterBinding.ensureInitialized();
|
||||||
|
|
||||||
|
final now = DateTime(2026, 9, 17, 8, 4);
|
||||||
|
String? bypassCause;
|
||||||
|
late List<String> calls;
|
||||||
|
|
||||||
|
setUp(() async {
|
||||||
|
calls = <String>[];
|
||||||
|
bypassCause = null;
|
||||||
|
SharedPreferences.setMockInitialValues(<String, Object>{});
|
||||||
|
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||||
|
.setMockMethodCallHandler(
|
||||||
|
const MethodChannel(AlarmScheduler.channelName),
|
||||||
|
(call) async {
|
||||||
|
calls.add(call.method);
|
||||||
|
if (call.method == 'hasNfc') return true;
|
||||||
|
if (call.method == 'isRinging') return true;
|
||||||
|
if (call.method == 'peekBypassReRing') return bypassCause;
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
await SessionTagSettings.replaceAll(<String>['bath', 'ward', 'desk'], '');
|
||||||
|
});
|
||||||
|
|
||||||
|
Future<String?> ringReasonAfterOneTick(WidgetTester tester) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
routes: <String, WidgetBuilder>{
|
||||||
|
'/': (_) =>
|
||||||
|
SessionScreen(clock: () => now, publish: () async => 'pushed'),
|
||||||
|
'/ring': (_) => const Scaffold(body: Text('RING')),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(kSessionTick);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('RING'), findsOneWidget);
|
||||||
|
return (await SessionStore().loadCurrent())!.pendingReRingReason;
|
||||||
|
}
|
||||||
|
|
||||||
|
testWidgets('a ring a bypass started is named for the bypass', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
bypassCause = 'suspended';
|
||||||
|
expect(await ringReasonAfterOneTick(tester), 'bypass:suspended');
|
||||||
|
// Only the dismiss takes the stamp: two screens can tick on one ring
|
||||||
|
// (emulator 2026-11-23), and the second must not see it gone.
|
||||||
|
expect(calls, contains('peekBypassReRing'));
|
||||||
|
expect(calls, isNot(contains('takeBypassReRing')));
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a ring nothing stamped is the deadline', (tester) async {
|
||||||
|
expect(await ringReasonAfterOneTick(tester), 'deadline:bathroomIn');
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -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,16 +8,16 @@ 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.0#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.
|
||||||
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync",
|
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync",
|
||||||
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays",
|
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays",
|
||||||
# Sick days stand the PC's enforcement down (_sick.py). Imported behind
|
# Sick days stand the PC's enforcement down (_sick.py). Imported behind
|
||||||
# a guard: missing means "not sick", never a crashed tick.
|
# a guard: missing means "not sick", never a crashed tick.
|
||||||
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.6#subdirectory=sickdays",
|
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays",
|
||||||
"kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.1#subdirectory=kuhy_credit",
|
"kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit",
|
||||||
]
|
]
|
||||||
|
|
||||||
# Package discovery must be explicit: phone_app/ is a Flutter app, not a Python
|
# Package discovery must be explicit: phone_app/ is a Flutter app, not a Python
|
||||||
@ -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,11 +4,11 @@
|
|||||||
# 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.3#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.0#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.1#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
|
||||||
pylint==4.1.4
|
pylint==4.1.4
|
||||||
@ -18,4 +18,4 @@ pytest-randomly==5.1.0
|
|||||||
pytest-sugar==1.1.1
|
pytest-sugar==1.1.1
|
||||||
pytest-xdist==3.8.0
|
pytest-xdist==3.8.0
|
||||||
ruff==0.17.6
|
ruff==0.17.6
|
||||||
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.6#subdirectory=sickdays
|
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays
|
||||||
|
|||||||
71
scripts/emu_published.py
Executable file
71
scripts/emu_published.py
Executable file
@ -0,0 +1,71 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
r"""Export what the emulator phone published to the Firebase RTDB emulator.
|
||||||
|
|
||||||
|
The emulator live checks (a ``bypass`` reaching "the test backend") use a
|
||||||
|
probe build that syncs to the PC's RTDB emulator instead of prod
|
||||||
|
(``phone_app/lib/services/sync_emulator.dart``). This reads it back exactly
|
||||||
|
the way the PC reads prod -- ``_sync_transport._read_published``: device
|
||||||
|
discovery plus the E2E unlock -- and writes the ``[[device_id, alarm], ...]``
|
||||||
|
list that ``python -m wake_alarm._fallback --dry-run --published`` takes.
|
||||||
|
|
||||||
|
Run it with ``HOME`` set to a scratch directory whose
|
||||||
|
``.config/crdt-sync/password`` holds the dummy test passphrase the AVD was
|
||||||
|
given, so the real passphrase is never read, and with
|
||||||
|
``PYTHONUSERBASE=/home/kuhy/.local`` so ``crdt_sync`` still imports::
|
||||||
|
|
||||||
|
HOME=$SCRATCH PYTHONUSERBASE=$HOME/.local \\
|
||||||
|
/usr/bin/python3 scripts/emu_published.py http://127.0.0.1:9000 out.json
|
||||||
|
|
||||||
|
``crdt_sync`` is imported unguarded on purpose: the transport degrades a
|
||||||
|
missing module to "nothing published", which here would read as a failed
|
||||||
|
check instead of a broken setup.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from crdt_sync import (
|
||||||
|
FirebaseSyncClient,
|
||||||
|
FirebaseTokenProvider,
|
||||||
|
MemoryCredentialStore,
|
||||||
|
)
|
||||||
|
|
||||||
|
from wake_alarm._sync_transport import _read_published
|
||||||
|
|
||||||
|
|
||||||
|
class _OwnerToken(FirebaseTokenProvider):
|
||||||
|
"""The emulator's admin token; the RTDB emulator accepts ``auth=owner``.
|
||||||
|
|
||||||
|
Never signs in: no API key, an empty store, and ``id_token`` overridden.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
"""A provider with nothing to refresh."""
|
||||||
|
super().__init__("", MemoryCredentialStore())
|
||||||
|
|
||||||
|
def id_token(self) -> str:
|
||||||
|
"""Every request's ``auth`` parameter."""
|
||||||
|
return "owner"
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str] | None = None) -> int:
|
||||||
|
"""Write the emulator's published logs to the output file; 1 when empty."""
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||||
|
parser.add_argument("url", help="the RTDB emulator's origin")
|
||||||
|
parser.add_argument("out", type=Path, help="where to write the JSON list")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
client = FirebaseSyncClient(args.url, _OwnerToken())
|
||||||
|
published = _read_published(client)
|
||||||
|
pairs = [[device, json.loads(raw)] for device, raw in published]
|
||||||
|
args.out.write_text(json.dumps(pairs, indent=1), encoding="utf-8")
|
||||||
|
devices = " ".join(device for device, _ in pairs)
|
||||||
|
sys.stdout.write(f"{len(pairs)} device(s): {devices}\n")
|
||||||
|
return 0 if pairs else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@ -17,7 +17,19 @@
|
|||||||
# non-zero. Needs WAKE_ALARM_USER (set by the unit; install.sh fills it in)
|
# non-zero. Needs WAKE_ALARM_USER (set by the unit; install.sh fills it in)
|
||||||
# and psmisc's fuser.
|
# and psmisc's fuser.
|
||||||
#
|
#
|
||||||
# Usage: ring_alsa.sh <rise.wav> <loop.wav>
|
# The monitors ring too (2026-11-22): kuhy switches the speakers off at the
|
||||||
|
# knob for the night, so the 07:51 ring of 11-22 played 30 min into silence.
|
||||||
|
# Every HDMI/DP output whose ELD names a connected monitor gets its own
|
||||||
|
# aplay loop, IEC958 unmuted; each output logs one `ring_sink` line.
|
||||||
|
#
|
||||||
|
# --probe proves the monitors without a sound: two seconds of digital
|
||||||
|
# silence to each, IEC958 muted, one `ring_probe` line per sink, exit 1 when
|
||||||
|
# any fails or none is connected (wake-alarm-ring-probe.service).
|
||||||
|
#
|
||||||
|
# --monitors <rise> <loop> rings only the monitors, until SIGTERM: the
|
||||||
|
# PipeWire path runs it as the user beside pw-play (wake_alarm/_ring_monitors).
|
||||||
|
#
|
||||||
|
# Usage: ring_alsa.sh <rise.wav> <loop.wav> | --monitors <rise> <loop> | --probe
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
|
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@ -35,9 +47,15 @@ readonly RING_USER="${WAKE_ALARM_USER:-}"
|
|||||||
readonly PY="${WAKE_ALARM_PYTHON:-/usr/bin/python3}"
|
readonly PY="${WAKE_ALARM_PYTHON:-/usr/bin/python3}"
|
||||||
# A failed aplay (device briefly held elsewhere) must not spin the CPU.
|
# A failed aplay (device briefly held elsewhere) must not spin the CPU.
|
||||||
readonly RETRY_SECONDS=1
|
readonly RETRY_SECONDS=1
|
||||||
|
# How long a monitor's aplay must survive to count as opened.
|
||||||
|
readonly OPEN_CHECK_SECONDS=1
|
||||||
|
# The monitors as card:dev:name:hdmi-index lines; unset = read `aplay -l`.
|
||||||
|
# Set (even empty) only by the vmbox gate.
|
||||||
|
MONITORS_OVERRIDE="${WAKE_ALARM_MONITORS-__unset__}"
|
||||||
|
readonly MONITORS_OVERRIDE
|
||||||
|
|
||||||
usage() {
|
usage() {
|
||||||
echo "Usage: $(basename "$0") <rise.wav> <loop.wav>" >&2
|
echo "Usage: $(basename "$0") <rise.wav> <loop.wav> | --monitors <rise> <loop> | --probe" >&2
|
||||||
exit 2
|
exit 2
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -70,6 +88,88 @@ play() {
|
|||||||
sleep "$RETRY_SECONDS"
|
sleep "$RETRY_SECONDS"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# One line per connected monitor: card:dev:name:hdmi-index. `aplay -l` names
|
||||||
|
# an HDMI/DP device after its ELD ("HDMI 0 [G27Q]"); an empty port keeps
|
||||||
|
# "HDMI n [HDMI n]".
|
||||||
|
monitor_sinks() {
|
||||||
|
if [[ "$MONITORS_OVERRIDE" != "__unset__" ]]; then
|
||||||
|
tr ' ' '\n' <<<"$MONITORS_OVERRIDE" | grep -v '^$' || true
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
aplay -l 2>/dev/null |
|
||||||
|
sed -nE 's/^card [0-9]+: ([^ ]+) \[[^]]*\], device ([0-9]+): HDMI ([0-9]+) \[(.+)\]$/\1:\2:\4:\3/p' |
|
||||||
|
grep -vE ':HDMI [0-9]+:[0-9]+$' || true
|
||||||
|
}
|
||||||
|
|
||||||
|
# One sink's ring: the rise, a `ring_sink` line saying whether it opened,
|
||||||
|
# then the loop until SIGTERM. The rise lasts a minute, so "opened" means
|
||||||
|
# aplay is still playing after OPEN_CHECK_SECONDS. A sink that cannot open
|
||||||
|
# logs and gives up, so one dead monitor never stops the others.
|
||||||
|
ring_sink() {
|
||||||
|
local card="$1" dev="$2" name="$3" rise="$4" loop="$5" device err pid rc=0
|
||||||
|
device="plughw:CARD=${card},DEV=${dev}"
|
||||||
|
err="$(mktemp)"
|
||||||
|
aplay -q -D "$device" "$rise" 2>"$err" &
|
||||||
|
pid=$!
|
||||||
|
sleep "$OPEN_CHECK_SECONDS"
|
||||||
|
if ! kill -0 "$pid" 2>/dev/null; then
|
||||||
|
wait "$pid" || rc=$?
|
||||||
|
fi
|
||||||
|
if [[ $rc -ne 0 ]]; then
|
||||||
|
echo "ring_sink sink=$name device=$card,$dev result=error $(tr '\n' ' ' <"$err")"
|
||||||
|
rm -f "$err"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
echo "ring_sink sink=$name device=$card,$dev result=ok"
|
||||||
|
rm -f "$err"
|
||||||
|
wait "$pid" 2>/dev/null || true
|
||||||
|
while true; do
|
||||||
|
aplay -q -D "$device" "$loop" 2>/dev/null || sleep "$RETRY_SECONDS"
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
# Every monitor in the background, IEC958 unmuted first.
|
||||||
|
start_monitors() {
|
||||||
|
local rise="$1" loop="$2" card dev name index
|
||||||
|
while IFS=: read -r card dev name index; do
|
||||||
|
[[ -n "$card" ]] || continue
|
||||||
|
amixer -q -c "$card" sset "IEC958,${index}" unmute >/dev/null 2>&1 || true
|
||||||
|
ring_sink "$card" "$dev" "$name" "$rise" "$loop" &
|
||||||
|
done < <(monitor_sinks)
|
||||||
|
}
|
||||||
|
|
||||||
|
# Silence into every monitor; 0 only when each opened and took >= 1.5 s.
|
||||||
|
# IEC958 is muted for the check and put back the way it was found.
|
||||||
|
probe() {
|
||||||
|
local card dev name index start ms rc err was failed=0 found=0
|
||||||
|
while IFS=: read -r card dev name index; do
|
||||||
|
[[ -n "$card" ]] || continue
|
||||||
|
found=1
|
||||||
|
was=unmute
|
||||||
|
if amixer -c "$card" sget "IEC958,${index}" 2>/dev/null | grep -q '\[off\]'; then
|
||||||
|
was=mute
|
||||||
|
fi
|
||||||
|
amixer -q -c "$card" sset "IEC958,${index}" mute >/dev/null 2>&1 || true
|
||||||
|
start="$(date +%s%N)"
|
||||||
|
rc=0
|
||||||
|
err="$(aplay -q -D "plughw:CARD=${card},DEV=${dev}" -t raw -f S16_LE -r 48000 \
|
||||||
|
-c 2 -d 2 /dev/zero 2>&1)" || rc=$?
|
||||||
|
ms=$((($(date +%s%N) - start) / 1000000))
|
||||||
|
amixer -q -c "$card" sset "IEC958,${index}" "$was" >/dev/null 2>&1 || true
|
||||||
|
if [[ $rc -eq 0 && $ms -ge 1500 ]]; then
|
||||||
|
echo "ring_probe sink=$name device=$card,$dev result=ok ms=$ms"
|
||||||
|
else
|
||||||
|
echo "ring_probe sink=$name device=$card,$dev result=error rc=$rc ms=$ms ${err//$'\n'/ }"
|
||||||
|
failed=1
|
||||||
|
fi
|
||||||
|
done < <(monitor_sinks)
|
||||||
|
if [[ $found -eq 0 ]]; then
|
||||||
|
echo "ring_probe result=error no connected monitor"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
return "$failed"
|
||||||
|
}
|
||||||
|
|
||||||
# Ring through the user's PipeWire until systemd's SIGTERM; non-zero if it
|
# Ring through the user's PipeWire until systemd's SIGTERM; non-zero if it
|
||||||
# cannot play (the fallback itself reports ring_backend FAILED).
|
# cannot play (the fallback itself reports ring_backend FAILED).
|
||||||
user_fallback() {
|
user_fallback() {
|
||||||
@ -109,16 +209,32 @@ handle_busy() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
|
if [[ "${1:-}" == "--probe" ]]; then
|
||||||
|
probe
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
if [[ "${1:-}" == "--monitors" ]]; then
|
||||||
|
[[ $# -eq 3 ]] || usage
|
||||||
|
# SIGTERM from the PipeWire path: end every loop, then exit.
|
||||||
|
trap 'kill $(jobs -p) 2>/dev/null || true; exit 0' TERM INT
|
||||||
|
start_monitors "$2" "$3"
|
||||||
|
wait
|
||||||
|
return
|
||||||
|
fi
|
||||||
[[ $# -eq 2 ]] || usage
|
[[ $# -eq 2 ]] || usage
|
||||||
local rise="$1" loop="$2"
|
local rise="$1" loop="$2"
|
||||||
[[ -r "$rise" && -r "$loop" ]] || {
|
[[ -r "$rise" && -r "$loop" ]] || {
|
||||||
echo "Error: cannot read $rise / $loop" >&2
|
echo "Error: cannot read $rise / $loop" >&2
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
# The monitor loops die with this script, whatever ends it.
|
||||||
|
trap 'kill $(jobs -p) 2>/dev/null || true' EXIT
|
||||||
|
start_monitors "$rise" "$loop"
|
||||||
unmute_all
|
unmute_all
|
||||||
local rc=0
|
local rc=0
|
||||||
play "$rise" || rc=$?
|
play "$rise" || rc=$?
|
||||||
[[ $rc -ne 3 ]] || handle_busy "$rise" "$loop"
|
[[ $rc -ne 3 ]] || handle_busy "$rise" "$loop"
|
||||||
|
[[ $rc -ne 0 ]] || echo "ring_sink sink=speakers device=$CARD,0 result=ok"
|
||||||
while true; do
|
while true; do
|
||||||
play "$loop" || sleep "$RETRY_SECONDS"
|
play "$loop" || sleep "$RETRY_SECONDS"
|
||||||
done
|
done
|
||||||
|
|||||||
13
scripts/pc/wake-alarm-ring-probe.service
Normal file
13
scripts/pc/wake-alarm-ring-probe.service
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Wake Alarm silent check that the monitors can ring (ALSA, root)
|
||||||
|
Documentation=https://github.com/kuhyx/wake-alarm
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
# Started once by the user's wake-alarm-fallback.service at A - 5 on a
|
||||||
|
# morning with no graphical session (the state the fallback rings in),
|
||||||
|
# through `sudo -n systemctl start` (see /etc/sudoers.d/wake-alarm).
|
||||||
|
# Plays digital silence only: `journalctl -u wake-alarm-ring-probe` shows
|
||||||
|
# one ring_probe line per monitor.
|
||||||
|
Type=oneshot
|
||||||
|
ExecStart=/usr/local/lib/wake-alarm/ring_alsa.sh --probe
|
||||||
|
TimeoutStartSec=60
|
||||||
48
scripts/vmbox/guest_cases_monitors.sh
Executable file
48
scripts/vmbox/guest_cases_monitors.sh
Executable file
@ -0,0 +1,48 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# wake_alarm vmbox harness — the monitors ring too (2026-11-22). Two fake
|
||||||
|
# monitors on snd-dummy's extra PCM devices (WAKE_ALARM_MONITORS stands in
|
||||||
|
# for the ELD names `aplay -l` reads on the PC): each must log its own
|
||||||
|
# `ring_sink ... result=ok`, a dead one must log an error without stopping
|
||||||
|
# the others, and --probe must pass on silence. Sourced by guest_cases_v2.sh.
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
# snd-dummy with three PCM devices: 0 = speakers, 1 and 2 = the monitors.
|
||||||
|
monitors_card() {
|
||||||
|
sudo modprobe -r snd-dummy >/dev/null 2>&1 || true
|
||||||
|
sudo modprobe snd-dummy pcm_devs=3
|
||||||
|
sudo udevadm settle
|
||||||
|
}
|
||||||
|
|
||||||
|
case_ring_monitor_sinks() {
|
||||||
|
local name="ring-alsa-monitor-sinks" out
|
||||||
|
monitors_card
|
||||||
|
out="$(sudo WAKE_ALARM_CARD=Dummy WAKE_ALARM_USER="$USER" \
|
||||||
|
WAKE_ALARM_MONITORS="Dummy:1:MonA:0 Dummy:2:MonB:1 Nope:0:Dead:2" \
|
||||||
|
timeout 5 "$RING_SCRIPT" "$RING_WAV_DIR/ring.wav" "$RING_WAV_DIR/ring_loop.wav" 2>&1)" || true
|
||||||
|
if grep -q "ring_sink sink=MonA device=Dummy,1 result=ok" <<<"$out" &&
|
||||||
|
grep -q "ring_sink sink=MonB device=Dummy,2 result=ok" <<<"$out" &&
|
||||||
|
grep -q "ring_sink sink=Dead device=Nope,0 result=error" <<<"$out"; then
|
||||||
|
pass "$name"
|
||||||
|
else
|
||||||
|
fail "$name" "ring_sink lines: $(grep ring_sink <<<"$out" | tr '\n' '|')"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
case_ring_monitor_probe() {
|
||||||
|
local name="ring-alsa-monitor-probe" out rc=0
|
||||||
|
monitors_card
|
||||||
|
out="$(sudo WAKE_ALARM_MONITORS="Dummy:1:MonA:0 Dummy:2:MonB:1" \
|
||||||
|
"$RING_SCRIPT" --probe 2>&1)" || rc=$?
|
||||||
|
if [[ $rc -eq 0 ]] && [[ "$(grep -c 'ring_probe .*result=ok' <<<"$out")" -eq 2 ]]; then
|
||||||
|
pass "$name"
|
||||||
|
else
|
||||||
|
fail "$name" "rc=$rc: $(tr '\n' '|' <<<"$out")"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
run_monitor_cases() {
|
||||||
|
case_ring_monitor_sinks
|
||||||
|
case_ring_monitor_probe
|
||||||
|
}
|
||||||
@ -18,6 +18,8 @@ readonly WAKEALARM=/sys/class/rtc/rtc0/wakealarm
|
|||||||
# (~/wake-alarm, or ~/wt from a worktree), so derive it, never hard-code it.
|
# (~/wake-alarm, or ~/wt from a worktree), so derive it, never hard-code it.
|
||||||
GUEST_REPO="$(readlink -f "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../..")"
|
GUEST_REPO="$(readlink -f "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../..")"
|
||||||
readonly GUEST_REPO
|
readonly GUEST_REPO
|
||||||
|
# shellcheck source=guest_cases_monitors.sh source-path=SCRIPTDIR
|
||||||
|
source "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/guest_cases_monitors.sh"
|
||||||
|
|
||||||
# A timer present but disabled fails silently every morning.
|
# A timer present but disabled fails silently every morning.
|
||||||
case_v2_timers() {
|
case_v2_timers() {
|
||||||
@ -236,6 +238,7 @@ run_v2_cases() {
|
|||||||
case_ring_script_plays
|
case_ring_script_plays
|
||||||
case_ring_busy_fallback
|
case_ring_busy_fallback
|
||||||
case_ring_busy_fails_loudly
|
case_ring_busy_fails_loudly
|
||||||
|
run_monitor_cases
|
||||||
case_sudoers
|
case_sudoers
|
||||||
case_powerkey_dropin
|
case_powerkey_dropin
|
||||||
case_rtc_arm
|
case_rtc_arm
|
||||||
|
|||||||
@ -24,8 +24,10 @@ readonly SYSTEMD_USER_DIR="$HOME/.config/systemd/user"
|
|||||||
# Enforcement v2 (DOCS-wake-enforcement.md): user units, then root pieces.
|
# Enforcement v2 (DOCS-wake-enforcement.md): user units, then root pieces.
|
||||||
readonly V2_UNITS=(wake-alarm-fallback wake-alarm-rtc wake-alarm-audit)
|
readonly V2_UNITS=(wake-alarm-fallback wake-alarm-rtc wake-alarm-audit)
|
||||||
readonly ALSA_UNIT="wake-alarm-ring-alsa.service"
|
readonly ALSA_UNIT="wake-alarm-ring-alsa.service"
|
||||||
|
readonly PROBE_UNIT="wake-alarm-ring-probe.service"
|
||||||
readonly ROOT_FILES=(
|
readonly ROOT_FILES=(
|
||||||
"/etc/systemd/system/$ALSA_UNIT"
|
"/etc/systemd/system/$ALSA_UNIT"
|
||||||
|
"/etc/systemd/system/$PROBE_UNIT"
|
||||||
"/usr/local/lib/wake-alarm/ring_alsa.sh"
|
"/usr/local/lib/wake-alarm/ring_alsa.sh"
|
||||||
"/usr/local/share/wake-alarm/ring.wav"
|
"/usr/local/share/wake-alarm/ring.wav"
|
||||||
"/usr/local/share/wake-alarm/ring_loop.wav"
|
"/usr/local/share/wake-alarm/ring_loop.wav"
|
||||||
@ -105,7 +107,7 @@ remove_enforcement() {
|
|||||||
done
|
done
|
||||||
echo " Fallback, RTC and audit timers removed"
|
echo " Fallback, RTC and audit timers removed"
|
||||||
|
|
||||||
sudo systemctl stop "$ALSA_UNIT" >/dev/null 2>&1 || true
|
sudo systemctl stop "$ALSA_UNIT" "$PROBE_UNIT" >/dev/null 2>&1 || true
|
||||||
for path in "${ROOT_FILES[@]}"; do
|
for path in "${ROOT_FILES[@]}"; do
|
||||||
sudo rm -f "$path"
|
sudo rm -f "$path"
|
||||||
done
|
done
|
||||||
|
|||||||
@ -1,11 +1,14 @@
|
|||||||
[Unit]
|
[Unit]
|
||||||
Description=Wake Alarm PC fallback alarm, once a minute through the morning
|
Description=Wake Alarm PC fallback alarm, once a minute mornings and 21:00-21:59
|
||||||
Documentation=https://github.com/kuhyx/wake-alarm
|
Documentation=https://github.com/kuhyx/wake-alarm
|
||||||
|
|
||||||
[Timer]
|
[Timer]
|
||||||
# 04:00-09:59 covers A-5min..A+45min for any alarm the phone can set (A is
|
# 04:00-09:59 covers A-5min..A+45min for any alarm the phone can set (A is
|
||||||
# clamped to <= 08:00). Outside that window a tick reads only local files.
|
# clamped to <= 08:00). Outside that window a tick reads only local files.
|
||||||
OnCalendar=*-*-* 04..09:*:00
|
# Through 11:59: a phone bypass rings the PC up to A + 4 h (A <= 08:00).
|
||||||
|
OnCalendar=*-*-* 04..11:*:00
|
||||||
|
# 21:00-21:59: the notifications check (DOCS-bypass.md); fetches only then.
|
||||||
|
OnCalendar=*-*-* 21:*:00
|
||||||
AccuracySec=1s
|
AccuracySec=1s
|
||||||
# Catch up at once after the RTC resume or a boot.
|
# Catch up at once after the RTC resume or a boot.
|
||||||
Persistent=true
|
Persistent=true
|
||||||
|
|||||||
@ -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"
|
||||||
|
|
||||||
@ -201,6 +210,8 @@ ESCAPE_REASON_MIN_CHARS: int = 40
|
|||||||
# Today's fallback-ring latch: {"date", "started_at", "stopped_at", "reason",
|
# Today's fallback-ring latch: {"date", "started_at", "stopped_at", "reason",
|
||||||
# "stop_reason"}.
|
# "stop_reason"}.
|
||||||
FALLBACK_RING_FILE: Path = LOG_STATE_DIR / "fallback_ring.json"
|
FALLBACK_RING_FILE: Path = LOG_STATE_DIR / "fallback_ring.json"
|
||||||
|
# The 21:00 notifications ring's own latch, same shape; never the morning's.
|
||||||
|
EVENING_RING_FILE: Path = LOG_STATE_DIR / "evening_ring.json"
|
||||||
|
|
||||||
# {"mode": "hibernate" | "poweroff"}; how the PC goes down for the night.
|
# {"mode": "hibernate" | "poweroff"}; how the PC goes down for the night.
|
||||||
PC_WAKE_CONFIG: Path = Path.home() / ".config" / "wake_alarm" / "pc_wake.json"
|
PC_WAKE_CONFIG: Path = Path.home() / ".config" / "wake_alarm" / "pc_wake.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,
|
||||||
@ -35,6 +36,7 @@ from wake_alarm._enforcement_records import (
|
|||||||
RingStarted,
|
RingStarted,
|
||||||
StickState,
|
StickState,
|
||||||
escape_from,
|
escape_from,
|
||||||
|
parse_instant,
|
||||||
phone_event_from,
|
phone_event_from,
|
||||||
ring_started_from,
|
ring_started_from,
|
||||||
stick_state_from,
|
stick_state_from,
|
||||||
@ -42,6 +44,7 @@ from wake_alarm._enforcement_records import (
|
|||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@ -69,6 +72,49 @@ class EnforcementView:
|
|||||||
"""The first honoured escape excusing ``day``, or None."""
|
"""The first honoured escape excusing ``day``, or None."""
|
||||||
return next((e for e in self.honoured_escapes() if e.date == day), None)
|
return next((e for e in self.honoured_escapes() if e.date == day), None)
|
||||||
|
|
||||||
|
def bypass_on(self, day: str) -> datetime | None:
|
||||||
|
"""The newest ``bypass`` of ``day``, unless a ``dismissed`` came after it.
|
||||||
|
|
||||||
|
The PC rings for a bypass until the phone proves the full dismiss
|
||||||
|
sequence again, which logs ``dismissed``.
|
||||||
|
"""
|
||||||
|
bypasses = [
|
||||||
|
at
|
||||||
|
for event in self.phone_events
|
||||||
|
if event.kind == "bypass" and event.data.get("date") == day
|
||||||
|
if (at := parse_instant(event.at)) is not None
|
||||||
|
]
|
||||||
|
if not bypasses:
|
||||||
|
return None
|
||||||
|
newest = max(bypasses)
|
||||||
|
dismissed = any(
|
||||||
|
event.kind == "dismissed"
|
||||||
|
and (at := parse_instant(event.at)) is not None
|
||||||
|
and at > newest
|
||||||
|
for event in self.phone_events
|
||||||
|
)
|
||||||
|
return None if dismissed else newest
|
||||||
|
|
||||||
|
def notifications_off_since(self, day: str) -> datetime | None:
|
||||||
|
"""The newest ``notifications`` event of local ``day``, if it says off.
|
||||||
|
|
||||||
|
None when ``day`` has none or the newest says on. An entry whose
|
||||||
|
``enabled`` is not a real bool is skipped, so a malformed event can
|
||||||
|
neither start the 21:00 ring nor silence it.
|
||||||
|
"""
|
||||||
|
seen = [
|
||||||
|
(at, enabled)
|
||||||
|
for event in self.phone_events
|
||||||
|
if event.kind == "notifications"
|
||||||
|
if isinstance(enabled := event.data.get("enabled"), bool)
|
||||||
|
if (at := parse_instant(event.at)) is not None
|
||||||
|
if at.date().isoformat() == day
|
||||||
|
]
|
||||||
|
if not seen:
|
||||||
|
return None
|
||||||
|
at, enabled = max(seen)
|
||||||
|
return None if enabled else at
|
||||||
|
|
||||||
def escaped_dates(self) -> frozenset[str]:
|
def escaped_dates(self) -> frozenset[str]:
|
||||||
"""Every morning an honoured escape excuses."""
|
"""Every morning an honoured escape excuses."""
|
||||||
return frozenset(e.date for e in self.honoured_escapes())
|
return frozenset(e.date for e in self.honoured_escapes())
|
||||||
@ -159,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 ():
|
||||||
|
|||||||
93
wake_alarm/_evening_policy.py
Normal file
93
wake_alarm/_evening_policy.py
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
"""The 21:00 notifications check's rule, as pure functions (``DOCS-bypass.md``).
|
||||||
|
|
||||||
|
Switching off "All WakeAlarm notifications" silences the ring and no device
|
||||||
|
policy can lock that switch, so the phone reports the state as a
|
||||||
|
``notifications`` phone event (at 21:00 and whenever the switch moves) and
|
||||||
|
the PC rings in the evening, while there is still time to fix it:
|
||||||
|
|
||||||
|
============================================= ===================
|
||||||
|
outside 21:00-21:59 start nothing
|
||||||
|
tomorrow is a free or sick day never ring
|
||||||
|
the evening ring used its 30 minutes never again tonight
|
||||||
|
today's newest event says on, or none today quiet
|
||||||
|
otherwise ring: notifications_off
|
||||||
|
============================================= ===================
|
||||||
|
|
||||||
|
Tomorrow, not today: the point is tomorrow's alarm. The hour gates
|
||||||
|
*starting* only; a ring in progress is judged by :func:`stop_reason`, so one
|
||||||
|
started at 21:50 runs its full 30 minutes. The cap is measured from the
|
||||||
|
evening latch's first start, never the morning's or a bypass's.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from wake_alarm._fallback_policy import CAP, Decision, latch_capped
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from wake_alarm._fallback_latch import Latch
|
||||||
|
|
||||||
|
EVENING_HOUR: int = 21
|
||||||
|
|
||||||
|
# Reasons, as they appear in events.jsonl and evening_ring.json.
|
||||||
|
NOTIFICATIONS_OFF = "notifications_off"
|
||||||
|
NOTIFICATIONS_ON = "notifications_on"
|
||||||
|
OUTSIDE_EVENING = "outside_evening"
|
||||||
|
FREE_TOMORROW = "free_tomorrow"
|
||||||
|
SICK_TOMORROW = "sick_tomorrow"
|
||||||
|
UNREACHABLE = "firebase_unreachable"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class EveningFacts:
|
||||||
|
"""Everything one evening decision needs; the caller gathers it.
|
||||||
|
|
||||||
|
``off_since`` is today's newest ``notifications`` event when it says
|
||||||
|
off; ``tomorrow_off`` is :data:`FREE_TOMORROW` / :data:`SICK_TOMORROW`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
now: datetime
|
||||||
|
tomorrow_off: str | None = None
|
||||||
|
off_since: datetime | None = None
|
||||||
|
latch: Latch | None = None
|
||||||
|
reachable: bool = True
|
||||||
|
|
||||||
|
|
||||||
|
def in_evening(now: datetime) -> bool:
|
||||||
|
"""Whether ``now`` is in the hour that may start an evening ring."""
|
||||||
|
return now.hour == EVENING_HOUR
|
||||||
|
|
||||||
|
|
||||||
|
def is_capped(facts: EveningFacts) -> bool:
|
||||||
|
"""Whether tonight's ring has used its 30 minutes."""
|
||||||
|
return latch_capped(facts.latch, facts.now)
|
||||||
|
|
||||||
|
|
||||||
|
def needs_fetch(facts: EveningFacts) -> bool:
|
||||||
|
"""Whether the phone's events can still change the answer."""
|
||||||
|
return facts.tomorrow_off is None and not is_capped(facts)
|
||||||
|
|
||||||
|
|
||||||
|
def stop_reason(facts: EveningFacts) -> str | None:
|
||||||
|
"""Why an evening ring must stop (or not start), or None to ring."""
|
||||||
|
if facts.tomorrow_off is not None:
|
||||||
|
return facts.tomorrow_off
|
||||||
|
if is_capped(facts):
|
||||||
|
return CAP
|
||||||
|
if facts.off_since is None:
|
||||||
|
return NOTIFICATIONS_ON if facts.reachable else UNREACHABLE
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def decide(facts: EveningFacts) -> Decision:
|
||||||
|
"""Ring or not at an evening tick; the table above, first match wins."""
|
||||||
|
if not in_evening(facts.now):
|
||||||
|
return Decision(ring=False, reason=OUTSIDE_EVENING)
|
||||||
|
stop = stop_reason(facts)
|
||||||
|
if stop is not None:
|
||||||
|
return Decision(ring=False, reason=stop)
|
||||||
|
return Decision(ring=True, reason=NOTIFICATIONS_OFF)
|
||||||
@ -1,4 +1,7 @@
|
|||||||
"""The PC fallback alarm: one per-minute tick, 04:00-09:59.
|
"""The PC fallback alarm: one per-minute tick, 04:00-11:59 and 21:00-21:59.
|
||||||
|
|
||||||
|
The 21:xx ticks are the notifications check (``_fallback_evening``),
|
||||||
|
dispatched before any morning code runs.
|
||||||
|
|
||||||
``wake-alarm-fallback.timer`` runs ``--tick`` every minute. Outside
|
``wake-alarm-fallback.timer`` runs ``--tick`` every minute. Outside
|
||||||
``A - 5 min .. A + 45 min`` (or on a free or sick day) a tick decides from local
|
``A - 5 min .. A + 45 min`` (or on a free or sick day) a tick decides from local
|
||||||
@ -12,6 +15,7 @@ no session, no escape": fail toward ringing.
|
|||||||
python -m wake_alarm._fallback --tick # what the timer runs
|
python -m wake_alarm._fallback --tick # what the timer runs
|
||||||
python -m wake_alarm._fallback --dry-run # decide now, change nothing
|
python -m wake_alarm._fallback --dry-run # decide now, change nothing
|
||||||
python -m wake_alarm._fallback --show # latch + last decision, offline
|
python -m wake_alarm._fallback --show # latch + last decision, offline
|
||||||
|
python -m wake_alarm._fallback --dry-run --published F # F replaces Firebase
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@ -25,7 +29,9 @@ from typing import TYPE_CHECKING
|
|||||||
import freedays
|
import freedays
|
||||||
|
|
||||||
from wake_alarm._cli_modes import mode_parser, parse_with_now
|
from wake_alarm._cli_modes import mode_parser, parse_with_now
|
||||||
|
from wake_alarm._evening_policy import in_evening
|
||||||
from wake_alarm._events import emit, emit_on_change, last_value
|
from wake_alarm._events import emit, emit_on_change, last_value
|
||||||
|
from wake_alarm._fallback_evening import evening_dry_run, evening_tick
|
||||||
from wake_alarm._fallback_latch import Latch, mark_started, mark_stopped, read_latch
|
from wake_alarm._fallback_latch import Latch, mark_started, mark_stopped, read_latch
|
||||||
from wake_alarm._fallback_observe import (
|
from wake_alarm._fallback_observe import (
|
||||||
Observation,
|
Observation,
|
||||||
@ -35,14 +41,18 @@ from wake_alarm._fallback_observe import (
|
|||||||
settled_reason,
|
settled_reason,
|
||||||
)
|
)
|
||||||
from wake_alarm._fallback_policy import (
|
from wake_alarm._fallback_policy import (
|
||||||
|
BYPASS,
|
||||||
Decision,
|
Decision,
|
||||||
Facts,
|
Facts,
|
||||||
alarm_instant,
|
alarm_instant,
|
||||||
|
bypass_stop_reason,
|
||||||
decide,
|
decide,
|
||||||
stop_reason,
|
stop_reason,
|
||||||
)
|
)
|
||||||
from wake_alarm._fallback_ring import ring
|
from wake_alarm._fallback_ring import ring
|
||||||
from wake_alarm._logging_setup import configure_logging
|
from wake_alarm._logging_setup import configure_logging
|
||||||
|
from wake_alarm._published_file import load_published
|
||||||
|
from wake_alarm._ring_probe import maybe_probe
|
||||||
from wake_alarm._ring_wav import SYSTEM_WAV_DIR, USER_WAV_DIR, ensure_pair
|
from wake_alarm._ring_wav import SYSTEM_WAV_DIR, USER_WAV_DIR, ensure_pair
|
||||||
from wake_alarm._sick import alarm_stands_down
|
from wake_alarm._sick import alarm_stands_down
|
||||||
from wake_alarm._sync import get_alarm
|
from wake_alarm._sync import get_alarm
|
||||||
@ -80,6 +90,41 @@ def _poll(day: str) -> str | None:
|
|||||||
return reason
|
return reason
|
||||||
|
|
||||||
|
|
||||||
|
def _poll_bypass(bypass_at: datetime | None) -> str | None:
|
||||||
|
"""Re-observe while ringing for a bypass; the reason to stop, or None.
|
||||||
|
|
||||||
|
An unreachable Firebase keeps the bypass it started with: fail toward
|
||||||
|
ringing, never toward silence.
|
||||||
|
"""
|
||||||
|
seen = observe(_now(), sync=True)
|
||||||
|
record(seen)
|
||||||
|
facts = seen.facts if seen.reachable else replace(seen.facts, bypass_at=bypass_at)
|
||||||
|
return bypass_stop_reason(facts)
|
||||||
|
|
||||||
|
|
||||||
|
def ring_bypass(facts: Facts) -> str:
|
||||||
|
"""Ring for a bypass until it is cleared or capped; returns the stop reason.
|
||||||
|
|
||||||
|
Never touches the daily latch: a bypass has its own 30 minutes, measured
|
||||||
|
from the phone's event, whatever the day's own ring already used.
|
||||||
|
"""
|
||||||
|
bypass_at = facts.bypass_at
|
||||||
|
emit(
|
||||||
|
"fallback_ring_start",
|
||||||
|
BYPASS,
|
||||||
|
reason=BYPASS,
|
||||||
|
bypass_at=bypass_at.isoformat() if bypass_at else None,
|
||||||
|
alarm=facts.alarm_at.isoformat(),
|
||||||
|
)
|
||||||
|
stopped = TERMINATED
|
||||||
|
try:
|
||||||
|
rise, loop = ensure_pair(SYSTEM_WAV_DIR, USER_WAV_DIR)
|
||||||
|
stopped = ring(lambda: _poll_bypass(bypass_at), rise=rise, loop=loop)
|
||||||
|
finally:
|
||||||
|
emit("fallback_ring_stop", stopped, stop_reason=stopped, reason=BYPASS)
|
||||||
|
return stopped
|
||||||
|
|
||||||
|
|
||||||
def ring_now(facts: Facts, reason: str) -> str:
|
def ring_now(facts: Facts, reason: str) -> str:
|
||||||
"""Latch, ring until a stop condition, unlatch; returns the stop reason."""
|
"""Latch, ring until a stop condition, unlatch; returns the stop reason."""
|
||||||
day = facts.now.date().isoformat()
|
day = facts.now.date().isoformat()
|
||||||
@ -106,9 +151,13 @@ def ring_now(facts: Facts, reason: str) -> str:
|
|||||||
|
|
||||||
def tick(now: datetime) -> Decision:
|
def tick(now: datetime) -> Decision:
|
||||||
"""One timer tick: observe, log a changed decision, ring if due."""
|
"""One timer tick: observe, log a changed decision, ring if due."""
|
||||||
|
if in_evening(now):
|
||||||
|
return evening_tick(now)
|
||||||
seen = observe(now, sync=True)
|
seen = observe(now, sync=True)
|
||||||
record(seen)
|
record(seen)
|
||||||
facts, day = seen.facts, now.date().isoformat()
|
facts, day = seen.facts, now.date().isoformat()
|
||||||
|
# Before any ring can start: the probe needs the monitors free.
|
||||||
|
maybe_probe(now, facts.alarm_at)
|
||||||
decision = decide(facts)
|
decision = decide(facts)
|
||||||
emit_on_change(
|
emit_on_change(
|
||||||
"fallback_tick",
|
"fallback_tick",
|
||||||
@ -121,7 +170,9 @@ def tick(now: datetime) -> Decision:
|
|||||||
)
|
)
|
||||||
remember_final(day, decision.reason)
|
remember_final(day, decision.reason)
|
||||||
latch = facts.latch
|
latch = facts.latch
|
||||||
if decision.ring:
|
if decision.ring and decision.reason == BYPASS:
|
||||||
|
ring_bypass(facts)
|
||||||
|
elif decision.ring:
|
||||||
ring_now(facts, decision.reason)
|
ring_now(facts, decision.reason)
|
||||||
elif latch is not None and latch.started_at and not latch.stopped_at:
|
elif latch is not None and latch.started_at and not latch.stopped_at:
|
||||||
_close(latch, decision.reason)
|
_close(latch, decision.reason)
|
||||||
@ -138,7 +189,8 @@ def describe(seen: Observation, decision: Decision) -> str:
|
|||||||
f"sick_day={facts.sick_day} "
|
f"sick_day={facts.sick_day} "
|
||||||
f"firebase={'ok' if seen.reachable else 'UNREACHABLE'}\n"
|
f"firebase={'ok' if seen.reachable else 'UNREACHABLE'}\n"
|
||||||
f" escaped={facts.escaped} session_started={facts.session_started} "
|
f" escaped={facts.escaped} session_started={facts.session_started} "
|
||||||
f"ring_started={facts.ring_started} settled={facts.settled}\n"
|
f"ring_started={facts.ring_started} settled={facts.settled} "
|
||||||
|
f"bypass_at={facts.bypass_at}\n"
|
||||||
f" latch={facts.latch}\n"
|
f" latch={facts.latch}\n"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -165,11 +217,22 @@ def _terminate(signum: int, _frame: FrameType | None) -> None:
|
|||||||
def main(argv: list[str] | None = None) -> int:
|
def main(argv: list[str] | None = None) -> int:
|
||||||
"""Entry point."""
|
"""Entry point."""
|
||||||
parser = mode_parser("PC fallback alarm tick", "tick", "decide and act")
|
parser = mode_parser("PC fallback alarm tick", "tick", "decide and act")
|
||||||
|
parser.add_argument("--published", help="with --dry-run: phone logs file")
|
||||||
args, now = parse_with_now(parser, argv, _now)
|
args, now = parse_with_now(parser, argv, _now)
|
||||||
|
planted = None
|
||||||
|
if args.published is not None:
|
||||||
|
if not args.dry_run:
|
||||||
|
parser.error("--published only goes with --dry-run")
|
||||||
|
try:
|
||||||
|
planted = load_published(args.published)
|
||||||
|
except (OSError, TypeError, ValueError) as exc:
|
||||||
|
parser.error(f"--published {args.published}: {exc}")
|
||||||
if args.show:
|
if args.show:
|
||||||
sys.stdout.write(show(now))
|
sys.stdout.write(show(now))
|
||||||
|
elif args.dry_run and in_evening(now):
|
||||||
|
sys.stdout.write(evening_dry_run(now, planted))
|
||||||
elif args.dry_run:
|
elif args.dry_run:
|
||||||
seen = observe(now, sync=False)
|
seen = observe(now, sync=False, planted=planted)
|
||||||
sys.stdout.write(describe(seen, decide(seen.facts)))
|
sys.stdout.write(describe(seen, decide(seen.facts)))
|
||||||
else:
|
else:
|
||||||
configure_logging(component="fallback")
|
configure_logging(component="fallback")
|
||||||
|
|||||||
168
wake_alarm/_fallback_evening.py
Normal file
168
wake_alarm/_fallback_evening.py
Normal file
@ -0,0 +1,168 @@
|
|||||||
|
"""The fallback timer's 21:00 hour: ring when the phone's notifications are off.
|
||||||
|
|
||||||
|
``_fallback.tick`` hands every 21:xx tick here before any morning code runs,
|
||||||
|
so the morning rules (today free or sick, the window, the morning latch) never
|
||||||
|
see the evening and the evening never sees them. The rule itself is
|
||||||
|
``_evening_policy``; this module gathers its facts, rings and logs.
|
||||||
|
|
||||||
|
Events use their own names (``evening_tick``, ``evening_ring_start``,
|
||||||
|
``evening_ring_stop``) so the morning audit never counts an evening ring as
|
||||||
|
the morning's. An unreachable Firebase at a tick rings nothing (no event is
|
||||||
|
known); one during a ring keeps ringing, bounded by the cap.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import replace
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
import freedays
|
||||||
|
|
||||||
|
from wake_alarm._constants import EVENING_RING_FILE
|
||||||
|
from wake_alarm._enforcement_payload import enforcement_view
|
||||||
|
from wake_alarm._evening_policy import (
|
||||||
|
FREE_TOMORROW,
|
||||||
|
NOTIFICATIONS_OFF,
|
||||||
|
SICK_TOMORROW,
|
||||||
|
EveningFacts,
|
||||||
|
decide,
|
||||||
|
needs_fetch,
|
||||||
|
stop_reason,
|
||||||
|
)
|
||||||
|
from wake_alarm._events import emit, emit_on_change
|
||||||
|
from wake_alarm._fallback_latch import Latch, mark_started, mark_stopped, read_latch
|
||||||
|
from wake_alarm._fallback_ring import ring
|
||||||
|
from wake_alarm._ring_wav import SYSTEM_WAV_DIR, USER_WAV_DIR, ensure_pair
|
||||||
|
from wake_alarm._sick import alarm_stands_down, alarm_stands_down_synced
|
||||||
|
from wake_alarm._sync_transport import fetch_firebase_logs
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from wake_alarm._fallback_policy import Decision
|
||||||
|
|
||||||
|
TERMINATED = "terminated"
|
||||||
|
|
||||||
|
|
||||||
|
def _now() -> datetime:
|
||||||
|
"""Aware local now; the seam tests patch."""
|
||||||
|
return datetime.now(tz=UTC).astimezone()
|
||||||
|
|
||||||
|
|
||||||
|
def _tomorrow_off(now: datetime, *, sync: bool) -> str | None:
|
||||||
|
"""Why tomorrow rings nothing, or None; pulls the sick pool when acting."""
|
||||||
|
tomorrow = now.date() + timedelta(days=1)
|
||||||
|
if freedays.is_free_day(tomorrow):
|
||||||
|
return FREE_TOMORROW
|
||||||
|
sick = alarm_stands_down_synced if sync else alarm_stands_down
|
||||||
|
return SICK_TOMORROW if sick(tomorrow) else None
|
||||||
|
|
||||||
|
|
||||||
|
def observe_evening(
|
||||||
|
now: datetime, *, sync: bool, planted: list[tuple[str, str]] | None = None
|
||||||
|
) -> EveningFacts:
|
||||||
|
"""Gather the evening's facts; Firebase (or ``planted``) only when needed."""
|
||||||
|
day = now.date().isoformat()
|
||||||
|
facts = EveningFacts(
|
||||||
|
now=now,
|
||||||
|
tomorrow_off=_tomorrow_off(now, sync=sync),
|
||||||
|
latch=read_latch(day, EVENING_RING_FILE),
|
||||||
|
)
|
||||||
|
if not needs_fetch(facts):
|
||||||
|
return facts
|
||||||
|
published = fetch_firebase_logs() if planted is None else planted
|
||||||
|
if published is None:
|
||||||
|
return replace(facts, reachable=False)
|
||||||
|
return replace(
|
||||||
|
facts, off_since=enforcement_view(published).notifications_off_since(day)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _poll(off_since: datetime | None) -> str | None:
|
||||||
|
"""Re-observe while ringing; the reason to stop, or None.
|
||||||
|
|
||||||
|
An unreachable Firebase keeps the off state the ring started with: fail
|
||||||
|
toward ringing, never toward silence. The cap still ends it.
|
||||||
|
"""
|
||||||
|
facts = observe_evening(_now(), sync=True)
|
||||||
|
if not facts.reachable:
|
||||||
|
facts = replace(facts, off_since=off_since, reachable=True)
|
||||||
|
return stop_reason(facts)
|
||||||
|
|
||||||
|
|
||||||
|
def _close(latch: Latch, reason: str) -> None:
|
||||||
|
"""Stop an open evening latch and log it."""
|
||||||
|
stopped = mark_stopped(
|
||||||
|
latch, now=_now(), stop_reason=reason, file=EVENING_RING_FILE
|
||||||
|
)
|
||||||
|
emit(
|
||||||
|
"evening_ring_stop",
|
||||||
|
reason,
|
||||||
|
stop_reason=reason,
|
||||||
|
started_at=stopped.started_at,
|
||||||
|
stopped_at=stopped.stopped_at,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def ring_evening(facts: EveningFacts) -> str:
|
||||||
|
"""Latch, ring until a stop condition, unlatch; returns the stop reason."""
|
||||||
|
day = facts.now.date().isoformat()
|
||||||
|
resumed = facts.latch is not None and facts.latch.started_at is not None
|
||||||
|
latch = mark_started(
|
||||||
|
facts.latch,
|
||||||
|
day=day,
|
||||||
|
now=facts.now,
|
||||||
|
reason=NOTIFICATIONS_OFF,
|
||||||
|
file=EVENING_RING_FILE,
|
||||||
|
)
|
||||||
|
off_since = facts.off_since
|
||||||
|
emit(
|
||||||
|
"evening_ring_start",
|
||||||
|
NOTIFICATIONS_OFF,
|
||||||
|
reason=NOTIFICATIONS_OFF,
|
||||||
|
resumed=resumed,
|
||||||
|
off_since=off_since.isoformat() if off_since else None,
|
||||||
|
started_at=latch.started_at,
|
||||||
|
)
|
||||||
|
stopped = TERMINATED
|
||||||
|
try:
|
||||||
|
# Inside the try, as in the morning: a WAV that cannot be generated
|
||||||
|
# must still close the latch.
|
||||||
|
rise, loop = ensure_pair(SYSTEM_WAV_DIR, USER_WAV_DIR)
|
||||||
|
stopped = ring(lambda: _poll(off_since), rise=rise, loop=loop)
|
||||||
|
finally:
|
||||||
|
_close(latch, stopped)
|
||||||
|
return stopped
|
||||||
|
|
||||||
|
|
||||||
|
def evening_tick(now: datetime) -> Decision:
|
||||||
|
"""One 21:xx timer tick: observe, log a changed decision, ring if due."""
|
||||||
|
facts, day = observe_evening(now, sync=True), now.date().isoformat()
|
||||||
|
decision = decide(facts)
|
||||||
|
emit_on_change(
|
||||||
|
"evening_tick",
|
||||||
|
f"{day}|{decision.ring}|{decision.reason}",
|
||||||
|
f"{'ring' if decision.ring else 'quiet'}: {decision.reason}",
|
||||||
|
ring=decision.ring,
|
||||||
|
reason=decision.reason,
|
||||||
|
reachable=facts.reachable,
|
||||||
|
)
|
||||||
|
latch = facts.latch
|
||||||
|
if decision.ring:
|
||||||
|
ring_evening(facts)
|
||||||
|
elif latch is not None and latch.started_at and not latch.stopped_at:
|
||||||
|
_close(latch, decision.reason)
|
||||||
|
return decision
|
||||||
|
|
||||||
|
|
||||||
|
def evening_dry_run(now: datetime, planted: list[tuple[str, str]] | None = None) -> str:
|
||||||
|
"""The ``--dry-run`` report for a 21:xx instant; writes nothing."""
|
||||||
|
facts = observe_evening(now, sync=False, planted=planted)
|
||||||
|
decision = decide(facts)
|
||||||
|
verdict = "WOULD RING" if decision.ring else "quiet"
|
||||||
|
return (
|
||||||
|
f"{now:%Y-%m-%d %H:%M} — {verdict}: {decision.reason}\n"
|
||||||
|
f" evening check: tomorrow_off={facts.tomorrow_off} "
|
||||||
|
f"firebase={'ok' if facts.reachable else 'UNREACHABLE'}\n"
|
||||||
|
f" off_since={facts.off_since}\n"
|
||||||
|
f" latch={facts.latch}\n"
|
||||||
|
)
|
||||||
@ -5,6 +5,9 @@ contract's shape. It is what makes the 30-minute cap survive the ringing
|
|||||||
process dying (a hibernate, a reboot): the cap is measured from the
|
process dying (a hibernate, a reboot): the cap is measured from the
|
||||||
wall-clock ``started_at``, never a monotonic clock, which does not advance
|
wall-clock ``started_at``, never a monotonic clock, which does not advance
|
||||||
through S4. An unreadable latch is no latch -- fail toward ringing.
|
through S4. An unreadable latch is no latch -- fail toward ringing.
|
||||||
|
|
||||||
|
``file`` (default ``FALLBACK_RING_FILE``, resolved per call so the test
|
||||||
|
redirect holds) lets the 21:00 notifications ring keep its own latch.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@ -19,6 +22,7 @@ from wake_alarm._enforcement_records import optional_text, parse_instant
|
|||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@ -38,14 +42,15 @@ class Latch:
|
|||||||
return parse_instant(self.started_at) if self.started_at else None
|
return parse_instant(self.started_at) if self.started_at else None
|
||||||
|
|
||||||
|
|
||||||
def read_latch(day: str) -> Latch | None:
|
def read_latch(day: str, file: Path | None = None) -> Latch | None:
|
||||||
"""The latch for ``day``; None when absent, unreadable or another day's."""
|
"""The latch for ``day``; None when absent, unreadable or another day's."""
|
||||||
|
path = file or FALLBACK_RING_FILE
|
||||||
try:
|
try:
|
||||||
raw = json.loads(FALLBACK_RING_FILE.read_text(encoding="utf-8"))
|
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
return None
|
return None
|
||||||
except (OSError, ValueError) as exc:
|
except (OSError, ValueError) as exc:
|
||||||
_logger.info("Ignoring unreadable %s: %s", FALLBACK_RING_FILE, exc)
|
_logger.info("Ignoring unreadable %s: %s", path, exc)
|
||||||
return None
|
return None
|
||||||
if not isinstance(raw, dict) or raw.get("date") != day:
|
if not isinstance(raw, dict) or raw.get("date") != day:
|
||||||
return None
|
return None
|
||||||
@ -58,31 +63,39 @@ def read_latch(day: str) -> Latch | None:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def write_latch(latch: Latch) -> bool:
|
def write_latch(latch: Latch, file: Path | None = None) -> bool:
|
||||||
"""Persist ``latch``; False when the disk refused."""
|
"""Persist ``latch``; False when the disk refused."""
|
||||||
|
path = file or FALLBACK_RING_FILE
|
||||||
try:
|
try:
|
||||||
FALLBACK_RING_FILE.parent.mkdir(parents=True, exist_ok=True)
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
FALLBACK_RING_FILE.write_text(json.dumps(asdict(latch), indent=2))
|
path.write_text(json.dumps(asdict(latch), indent=2))
|
||||||
except OSError as exc:
|
except OSError as exc:
|
||||||
_logger.warning("Could not write %s: %s", FALLBACK_RING_FILE, exc)
|
_logger.warning("Could not write %s: %s", path, exc)
|
||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def mark_started(
|
def mark_started(
|
||||||
previous: Latch | None, *, day: str, now: datetime, reason: str
|
previous: Latch | None,
|
||||||
|
*,
|
||||||
|
day: str,
|
||||||
|
now: datetime,
|
||||||
|
reason: str,
|
||||||
|
file: Path | None = None,
|
||||||
) -> Latch:
|
) -> Latch:
|
||||||
"""Record a ring (re)starting; a resumed ring keeps its first start."""
|
"""Record a ring (re)starting; a resumed ring keeps its first start."""
|
||||||
if previous is not None and previous.started_at:
|
if previous is not None and previous.started_at:
|
||||||
latch = replace(previous, stopped_at=None, stop_reason=None)
|
latch = replace(previous, stopped_at=None, stop_reason=None)
|
||||||
else:
|
else:
|
||||||
latch = Latch(date=day, started_at=now.isoformat(), reason=reason)
|
latch = Latch(date=day, started_at=now.isoformat(), reason=reason)
|
||||||
write_latch(latch)
|
write_latch(latch, file)
|
||||||
return latch
|
return latch
|
||||||
|
|
||||||
|
|
||||||
def mark_stopped(latch: Latch, *, now: datetime, stop_reason: str) -> Latch:
|
def mark_stopped(
|
||||||
|
latch: Latch, *, now: datetime, stop_reason: str, file: Path | None = None
|
||||||
|
) -> Latch:
|
||||||
"""Record why and when the ring stopped."""
|
"""Record why and when the ring stopped."""
|
||||||
stopped = replace(latch, stopped_at=now.isoformat(), stop_reason=stop_reason)
|
stopped = replace(latch, stopped_at=now.isoformat(), stop_reason=stop_reason)
|
||||||
write_latch(stopped)
|
write_latch(stopped, file)
|
||||||
return stopped
|
return stopped
|
||||||
|
|||||||
@ -62,11 +62,14 @@ def _sick_today(now: datetime, *, online: bool, sync: bool) -> bool:
|
|||||||
return alarm_stands_down(now.date())
|
return alarm_stands_down(now.date())
|
||||||
|
|
||||||
|
|
||||||
def observe(now: datetime, *, sync: bool) -> Observation:
|
def observe(
|
||||||
|
now: datetime, *, sync: bool, planted: list[tuple[str, str]] | None = None
|
||||||
|
) -> Observation:
|
||||||
"""Gather the facts; the network only when the decision needs it.
|
"""Gather the facts; the network only when the decision needs it.
|
||||||
|
|
||||||
``sync`` is False for ``--dry-run``: pulling the sick-day pool rewrites
|
``sync`` is False for ``--dry-run``: pulling the sick-day pool rewrites
|
||||||
its local file, and a dry run writes nothing.
|
its local file, and a dry run writes nothing. ``planted`` (``--dry-run
|
||||||
|
--published``) stands in for the Firebase fetch.
|
||||||
"""
|
"""
|
||||||
day = now.date().isoformat()
|
day = now.date().isoformat()
|
||||||
latch = read_latch(day)
|
latch = read_latch(day)
|
||||||
@ -82,7 +85,7 @@ def observe(now: datetime, *, sync: bool) -> Observation:
|
|||||||
)
|
)
|
||||||
if facts.free_day or facts.sick_day or not online:
|
if facts.free_day or facts.sick_day or not online:
|
||||||
return Observation(facts)
|
return Observation(facts)
|
||||||
published = fetch_firebase_logs()
|
published = fetch_firebase_logs() if planted is None else planted
|
||||||
if published is None:
|
if published is None:
|
||||||
return Observation(facts, reachable=False)
|
return Observation(facts, reachable=False)
|
||||||
view = enforcement_view(published)
|
view = enforcement_view(published)
|
||||||
@ -93,6 +96,7 @@ def observe(now: datetime, *, sync: bool) -> Observation:
|
|||||||
escaped=view.escape_for(day) is not None,
|
escaped=view.escape_for(day) is not None,
|
||||||
session_started=session is not None and session.date == day,
|
session_started=session is not None and session.date == day,
|
||||||
ring_started=view.ring_started_on(day),
|
ring_started=view.ring_started_on(day),
|
||||||
|
bypass_at=view.bypass_on(day),
|
||||||
),
|
),
|
||||||
view=view,
|
view=view,
|
||||||
)
|
)
|
||||||
|
|||||||
@ -10,6 +10,12 @@ ring already ran 30 min today (``FALLBACK_RING_CAP``) never again today
|
|||||||
``now >= A + 15 min`` (``SESSION_NONE_GRACE``) ring: no_session
|
``now >= A + 15 min`` (``SESSION_NONE_GRACE``) ring: no_session
|
||||||
========================================================= ==================
|
========================================================= ==================
|
||||||
|
|
||||||
|
A **bypass** comes before the table (2026-11-22): a ``bypass`` phone event
|
||||||
|
today (the app paused, its admin removed, a permission revoked, the ring
|
||||||
|
killed) with no newer ``dismissed`` rings ``bypass`` for 30 minutes from the
|
||||||
|
event, ignoring the window, a started session, a final reason and the
|
||||||
|
day's own cap. Only a free or sick day, or an escape, stands it down.
|
||||||
|
|
||||||
The window gates *starting* a ring only. A ring that already started today
|
The window gates *starting* a ring only. A ring that already started today
|
||||||
and has not hit its cap is judged by the table alone, so a ringing process
|
and has not hit its cap is judged by the table alone, so a ringing process
|
||||||
killed by a hibernate resumes after the resume instead of going quiet
|
killed by a hibernate resumes after the resume instead of going quiet
|
||||||
@ -53,6 +59,13 @@ CAP = "cap"
|
|||||||
PHONE_SILENT = "phone_silent"
|
PHONE_SILENT = "phone_silent"
|
||||||
NO_SESSION = "no_session"
|
NO_SESSION = "no_session"
|
||||||
WAITING = "waiting"
|
WAITING = "waiting"
|
||||||
|
BYPASS = "bypass"
|
||||||
|
BYPASS_CLEARED = "bypass_cleared"
|
||||||
|
|
||||||
|
# How long after A the tick keeps reading the phone for a bypass. The morning
|
||||||
|
# session's last cutoff is 11:00 and A is never later than 08:00 (07:00 at
|
||||||
|
# the end of the ramp), so A + 4 h covers every live ring and session.
|
||||||
|
BYPASS_WATCH: timedelta = timedelta(hours=4)
|
||||||
|
|
||||||
# Once seen, these hold for the rest of the day even if Firebase later stops
|
# Once seen, these hold for the rest of the day even if Firebase later stops
|
||||||
# answering: an unreachable backend fails toward ringing, but never toward
|
# answering: an unreachable backend fails toward ringing, but never toward
|
||||||
@ -76,6 +89,8 @@ class Facts:
|
|||||||
ring_started: bool = False
|
ring_started: bool = False
|
||||||
latch: Latch | None = None
|
latch: Latch | None = None
|
||||||
settled: str | None = None
|
settled: str | None = None
|
||||||
|
# The newest bypass today not followed by a dismiss; None = none live.
|
||||||
|
bypass_at: datetime | None = None
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@ -101,26 +116,38 @@ def _ring_started_today(latch: Latch | None) -> bool:
|
|||||||
return latch is not None and latch.started() is not None
|
return latch is not None and latch.started() is not None
|
||||||
|
|
||||||
|
|
||||||
def needs_facts(now: datetime, alarm_at: datetime, latch: Latch | None) -> bool:
|
def in_window(now: datetime, alarm_at: datetime, latch: Latch | None) -> bool:
|
||||||
"""Whether this tick must fetch the phone's state at all.
|
"""Whether the table's rows may start (or resume) a ring now."""
|
||||||
|
|
||||||
Outside the window with nothing rung today the answer is already
|
|
||||||
``outside_window``, so the per-minute tick stays off the network.
|
|
||||||
"""
|
|
||||||
if _ring_started_today(latch):
|
if _ring_started_today(latch):
|
||||||
return True
|
return True
|
||||||
return alarm_at - FALLBACK_WINDOW_START <= now < alarm_at + FALLBACK_WINDOW_END
|
return alarm_at - FALLBACK_WINDOW_START <= now < alarm_at + FALLBACK_WINDOW_END
|
||||||
|
|
||||||
|
|
||||||
def is_capped(facts: Facts) -> bool:
|
def needs_facts(now: datetime, alarm_at: datetime, latch: Latch | None) -> bool:
|
||||||
"""Whether today's ring has used its 30 minutes."""
|
"""Whether this tick must fetch the phone's state at all.
|
||||||
latch = facts.latch
|
|
||||||
|
The window, or the bypass watch after it (``BYPASS_WATCH``). Outside
|
||||||
|
both the answer is already ``outside_window``, so the per-minute tick
|
||||||
|
stays off the network.
|
||||||
|
"""
|
||||||
|
if in_window(now, alarm_at, latch):
|
||||||
|
return True
|
||||||
|
return alarm_at - FALLBACK_WINDOW_START <= now < alarm_at + BYPASS_WATCH
|
||||||
|
|
||||||
|
|
||||||
|
def latch_capped(latch: Latch | None, now: datetime) -> bool:
|
||||||
|
"""Whether the ring this latch records has used its 30 minutes."""
|
||||||
if latch is None:
|
if latch is None:
|
||||||
return False
|
return False
|
||||||
if latch.stop_reason == CAP:
|
if latch.stop_reason == CAP:
|
||||||
return True
|
return True
|
||||||
started = latch.started()
|
started = latch.started()
|
||||||
return started is not None and facts.now >= started + FALLBACK_RING_CAP
|
return started is not None and now >= started + FALLBACK_RING_CAP
|
||||||
|
|
||||||
|
|
||||||
|
def is_capped(facts: Facts) -> bool:
|
||||||
|
"""Whether today's ring has used its 30 minutes."""
|
||||||
|
return latch_capped(facts.latch, facts.now)
|
||||||
|
|
||||||
|
|
||||||
def day_off(facts: Facts) -> str | None:
|
def day_off(facts: Facts) -> str | None:
|
||||||
@ -154,12 +181,33 @@ def stop_reason(facts: Facts) -> str | None:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def bypass_stop_reason(facts: Facts) -> str | None:
|
||||||
|
"""Why a bypass ring must stop now, or None while the bypass stands."""
|
||||||
|
off = day_off(facts)
|
||||||
|
if off is not None:
|
||||||
|
return off
|
||||||
|
if facts.escaped:
|
||||||
|
return ESCAPE
|
||||||
|
if facts.bypass_at is None:
|
||||||
|
return BYPASS_CLEARED
|
||||||
|
if facts.now >= facts.bypass_at + FALLBACK_RING_CAP:
|
||||||
|
return CAP
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def decide(facts: Facts) -> Decision:
|
def decide(facts: Facts) -> Decision:
|
||||||
"""The table above; first match wins."""
|
"""A live bypass first, then the table above; first match wins."""
|
||||||
off = day_off(facts)
|
off = day_off(facts)
|
||||||
if off is not None:
|
if off is not None:
|
||||||
return Decision(ring=False, reason=off)
|
return Decision(ring=False, reason=off)
|
||||||
if not needs_facts(facts.now, facts.alarm_at, facts.latch):
|
if facts.bypass_at is not None and bypass_stop_reason(facts) is None:
|
||||||
|
return Decision(ring=True, reason=BYPASS)
|
||||||
|
return _decide_table(facts)
|
||||||
|
|
||||||
|
|
||||||
|
def _decide_table(facts: Facts) -> Decision:
|
||||||
|
"""The table's rows, on a day that is neither off nor bypassed."""
|
||||||
|
if not in_window(facts.now, facts.alarm_at, facts.latch):
|
||||||
return Decision(ring=False, reason=OUTSIDE_WINDOW)
|
return Decision(ring=False, reason=OUTSIDE_WINDOW)
|
||||||
stop = stop_reason(facts)
|
stop = stop_reason(facts)
|
||||||
if stop is not None:
|
if stop is not None:
|
||||||
|
|||||||
@ -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)
|
||||||
|
|||||||
42
wake_alarm/_published_file.py
Normal file
42
wake_alarm/_published_file.py
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
"""A planted stand-in for ``fetch_firebase_logs()``: ``--published FILE``.
|
||||||
|
|
||||||
|
Only for ``_fallback --dry-run``: the live check of the bypass ring needs
|
||||||
|
``bypass`` / ``dismissed`` events the PC can read, and there is no test
|
||||||
|
backend to put them in. The file is a JSON list of ``[device_id, alarm]``
|
||||||
|
pairs, the shape ``fetch_firebase_logs()`` returns. ``alarm`` is the
|
||||||
|
decrypted ``alarm.json`` -- an object (re-serialised here) or its raw text,
|
||||||
|
passed through as-is.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
_PAIR_LEN = 2
|
||||||
|
|
||||||
|
|
||||||
|
def _pair(entry: object) -> tuple[str, str]:
|
||||||
|
"""One ``[device_id, alarm]`` entry as ``(device_id, raw_json)``."""
|
||||||
|
if not isinstance(entry, list) or len(entry) != _PAIR_LEN:
|
||||||
|
msg = f"expected [device_id, alarm], got {entry!r}"
|
||||||
|
raise TypeError(msg)
|
||||||
|
device, alarm = entry
|
||||||
|
if not isinstance(device, str):
|
||||||
|
msg = f"device id must be a string, got {device!r}"
|
||||||
|
raise TypeError(msg)
|
||||||
|
if isinstance(alarm, str):
|
||||||
|
return device, alarm
|
||||||
|
if isinstance(alarm, dict):
|
||||||
|
return device, json.dumps(alarm)
|
||||||
|
msg = f"alarm for {device!r} must be an object or its JSON text"
|
||||||
|
raise TypeError(msg)
|
||||||
|
|
||||||
|
|
||||||
|
def load_published(path: str) -> list[tuple[str, str]]:
|
||||||
|
"""The planted logs; OSError/ValueError/TypeError when the file is unusable."""
|
||||||
|
raw = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||||
|
if not isinstance(raw, list):
|
||||||
|
msg = "expected a JSON list of [device_id, alarm] pairs"
|
||||||
|
raise TypeError(msg)
|
||||||
|
return [_pair(entry) for entry in raw]
|
||||||
59
wake_alarm/_ring_monitors.py
Normal file
59
wake_alarm/_ring_monitors.py
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
"""The monitors' share of a PipeWire ring.
|
||||||
|
|
||||||
|
The night's speakers are switched off at the knob (2026-11-22), so a ring
|
||||||
|
must reach the two monitors too. PipeWire does not expose them (the NVidia
|
||||||
|
card's profile is off), but the active session's ACL lets this user open
|
||||||
|
their ALSA devices, so ``ring_alsa.sh --monitors`` plays to each one
|
||||||
|
directly, logging one ``ring_sink`` line per monitor to this unit's journal.
|
||||||
|
The script runs in its own session so :meth:`MonitorLoops.stop` can end
|
||||||
|
every ``aplay`` it started at once.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import signal
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Where install.sh puts scripts/pc/ring_alsa.sh.
|
||||||
|
RING_SCRIPT = Path("/usr/local/lib/wake-alarm/ring_alsa.sh")
|
||||||
|
|
||||||
|
|
||||||
|
def _spawn(cmd: list[str]) -> subprocess.Popen[bytes]:
|
||||||
|
"""Start ``cmd`` as its own process group; the seam tests replace."""
|
||||||
|
return subprocess.Popen(cmd, start_new_session=True)
|
||||||
|
|
||||||
|
|
||||||
|
class MonitorLoops:
|
||||||
|
"""One ``ring_alsa.sh --monitors`` process group."""
|
||||||
|
|
||||||
|
def __init__(self, proc: subprocess.Popen[bytes]) -> None:
|
||||||
|
"""Wrap a started group."""
|
||||||
|
self._proc: subprocess.Popen[bytes] | None = proc
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def start(cls, rise: Path, loop: Path) -> MonitorLoops | None:
|
||||||
|
"""Start the loops; None (logged) when they cannot start.
|
||||||
|
|
||||||
|
Never fatal: the speakers' ring must not depend on the monitors.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
proc = _spawn([str(RING_SCRIPT), "--monitors", str(rise), str(loop)])
|
||||||
|
except OSError as exc:
|
||||||
|
_logger.warning("Monitor ring not started: %s", exc)
|
||||||
|
return None
|
||||||
|
return cls(proc)
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
"""SIGTERM the whole group. Safe to call twice."""
|
||||||
|
proc, self._proc = self._proc, None
|
||||||
|
if proc is None or proc.poll() is not None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
os.killpg(proc.pid, signal.SIGTERM)
|
||||||
|
except ProcessLookupError:
|
||||||
|
return
|
||||||
@ -4,7 +4,8 @@ Two backends, chosen per ring by :func:`select_backend`:
|
|||||||
|
|
||||||
* **PipeWire** -- an active graphical session on seat0 belongs to this user,
|
* **PipeWire** -- an active graphical session on seat0 belongs to this user,
|
||||||
so its PipeWire is reachable: unmute and max the default sink with
|
so its PipeWire is reachable: unmute and max the default sink with
|
||||||
``wpctl`` and play with ``pw-play``.
|
``wpctl`` and play with ``pw-play``; the monitors ring beside it
|
||||||
|
(:mod:`wake_alarm._ring_monitors`).
|
||||||
* **ALSA unit** -- anything else (the night lockdown: lightdm masked, nobody
|
* **ALSA unit** -- anything else (the night lockdown: lightdm masked, nobody
|
||||||
logged in, and the user is not in ``audio``): start the root system unit
|
logged in, and the user is not in ``audio``): start the root system unit
|
||||||
``wake-alarm-ring-alsa.service`` through its NOPASSWD sudoers entry. The
|
``wake-alarm-ring-alsa.service`` through its NOPASSWD sudoers entry. The
|
||||||
@ -21,6 +22,8 @@ import os
|
|||||||
import subprocess
|
import subprocess
|
||||||
from typing import TYPE_CHECKING, Protocol
|
from typing import TYPE_CHECKING, Protocol
|
||||||
|
|
||||||
|
from wake_alarm._ring_monitors import MonitorLoops
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@ -111,6 +114,7 @@ class PipeWireBackend:
|
|||||||
"""Play ``rise`` once, then ``loop`` forever."""
|
"""Play ``rise`` once, then ``loop`` forever."""
|
||||||
self._rise, self._loop = rise, loop
|
self._rise, self._loop = rise, loop
|
||||||
self._proc: subprocess.Popen[bytes] | None = None
|
self._proc: subprocess.Popen[bytes] | None = None
|
||||||
|
self._monitors: MonitorLoops | None = None
|
||||||
|
|
||||||
def _play(self, path: Path) -> None:
|
def _play(self, path: Path) -> None:
|
||||||
"""Start ``pw-play`` on ``path`` at full stream volume."""
|
"""Start ``pw-play`` on ``path`` at full stream volume."""
|
||||||
@ -129,6 +133,7 @@ class PipeWireBackend:
|
|||||||
self._play(self._rise)
|
self._play(self._rise)
|
||||||
except OSError as exc:
|
except OSError as exc:
|
||||||
return False, f"pw-play failed: {exc}"
|
return False, f"pw-play failed: {exc}"
|
||||||
|
self._monitors = MonitorLoops.start(self._rise, self._loop)
|
||||||
return True, "pw-play started"
|
return True, "pw-play started"
|
||||||
|
|
||||||
def pump(self) -> bool:
|
def pump(self) -> bool:
|
||||||
@ -148,7 +153,10 @@ class PipeWireBackend:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
def stop(self) -> None:
|
def stop(self) -> None:
|
||||||
"""Terminate the current ``pw-play``."""
|
"""Terminate the current ``pw-play`` and the monitor loops."""
|
||||||
|
monitors, self._monitors = self._monitors, None
|
||||||
|
if monitors is not None:
|
||||||
|
monitors.stop()
|
||||||
proc, self._proc = self._proc, None
|
proc, self._proc = self._proc, None
|
||||||
if proc is None or proc.poll() is not None:
|
if proc is None or proc.poll() is not None:
|
||||||
return
|
return
|
||||||
|
|||||||
48
wake_alarm/_ring_probe.py
Normal file
48
wake_alarm/_ring_probe.py
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
"""The silent monitor probe: once, at A - 5, on a morning with no session.
|
||||||
|
|
||||||
|
On 2026-11-22 the fallback rang 30 minutes into the analog speakers, which
|
||||||
|
kuhy switches off at the knob for the night, so nothing was heard. The ring
|
||||||
|
now plays to every connected monitor too (``scripts/pc/ring_alsa.sh``).
|
||||||
|
Whether a monitor really takes the stream with no graphical session can be
|
||||||
|
known only in that state, and kuhy asked for no test sound, so this starts
|
||||||
|
``wake-alarm-ring-probe.service`` once: digital silence into each monitor,
|
||||||
|
one ``ring_probe`` journal line per sink. The first real fallback morning's
|
||||||
|
``ring_sink`` lines are the follow-up check.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import timedelta
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from wake_alarm._constants import LOG_STATE_DIR
|
||||||
|
from wake_alarm._events import emit, emit_on_change
|
||||||
|
from wake_alarm._ring_player import _ok, graphical_session
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
PROBE_UNIT = "wake-alarm-ring-probe.service"
|
||||||
|
PROBE_DONE_FILE = LOG_STATE_DIR / "ring_probe_done"
|
||||||
|
PROBE_LEAD = timedelta(minutes=5)
|
||||||
|
|
||||||
|
|
||||||
|
def maybe_probe(now: datetime, alarm_at: datetime) -> str | None:
|
||||||
|
"""Start the probe if it is due; what happened, or None when not due."""
|
||||||
|
if PROBE_DONE_FILE.exists() or not alarm_at - PROBE_LEAD <= now < alarm_at:
|
||||||
|
return None
|
||||||
|
graphical, why = graphical_session()
|
||||||
|
if graphical:
|
||||||
|
# Not the state a fallback ring meets; try again tomorrow. Logged
|
||||||
|
# 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])
|
||||||
|
emit("ring_probe", "started" if started else "failed", session=why, output=out)
|
||||||
|
if not started:
|
||||||
|
return "failed"
|
||||||
|
PROBE_DONE_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
PROBE_DONE_FILE.write_text(now.isoformat(), encoding="utf-8")
|
||||||
|
return "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
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -52,6 +52,13 @@ def _no_process(cmd: list[str]) -> object:
|
|||||||
raise AssertionError(msg)
|
raise AssertionError(msg)
|
||||||
|
|
||||||
|
|
||||||
|
def _probe_done(tmp_path: Path) -> Path:
|
||||||
|
"""An already-run probe, so a tick at A - 5 never reaches loginctl."""
|
||||||
|
path = tmp_path / "ring_probe_done"
|
||||||
|
path.write_text("test", encoding="utf-8")
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
class FakeClock:
|
class FakeClock:
|
||||||
"""A monotonic clock that only moves when ``sleep`` is called.
|
"""A monotonic clock that only moves when ``sleep`` is called.
|
||||||
|
|
||||||
@ -166,6 +173,10 @@ def _hermetic(tmp_path: Path) -> Generator[None]:
|
|||||||
tmp_path / "morning_session.json",
|
tmp_path / "morning_session.json",
|
||||||
),
|
),
|
||||||
patch("wake_alarm._session_strip._popen", _no_process),
|
patch("wake_alarm._session_strip._popen", _no_process),
|
||||||
|
# The silent monitor probe sudo-starts a root unit: never from a test
|
||||||
|
# unless that test patches its own done file and process seam.
|
||||||
|
patch("wake_alarm._ring_probe._ok", _no_process),
|
||||||
|
patch("wake_alarm._ring_probe.PROBE_DONE_FILE", _probe_done(tmp_path)),
|
||||||
patch("wake_alarm._session_strip._once", _session_strip._Once()),
|
patch("wake_alarm._session_strip._once", _session_strip._Once()),
|
||||||
patch(
|
patch(
|
||||||
"wake_alarm._workday_penalty.WORKDAY_PENALTY_FILE",
|
"wake_alarm._workday_penalty.WORKDAY_PENALTY_FILE",
|
||||||
@ -175,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",
|
||||||
@ -190,6 +207,12 @@ def _hermetic(tmp_path: Path) -> Generator[None]:
|
|||||||
"wake_alarm._fallback_latch.FALLBACK_RING_FILE",
|
"wake_alarm._fallback_latch.FALLBACK_RING_FILE",
|
||||||
tmp_path / "fallback_ring.json",
|
tmp_path / "fallback_ring.json",
|
||||||
),
|
),
|
||||||
|
patch(
|
||||||
|
"wake_alarm._fallback_evening.EVENING_RING_FILE",
|
||||||
|
tmp_path / "evening_ring.json",
|
||||||
|
),
|
||||||
|
patch("wake_alarm._fallback_evening.SYSTEM_WAV_DIR", tmp_path / "wav-system"),
|
||||||
|
patch("wake_alarm._fallback_evening.USER_WAV_DIR", tmp_path / "wav-user"),
|
||||||
patch("wake_alarm._pc_wake_mode.PC_WAKE_CONFIG", tmp_path / "pc_wake.json"),
|
patch("wake_alarm._pc_wake_mode.PC_WAKE_CONFIG", tmp_path / "pc_wake.json"),
|
||||||
patch("wake_alarm._audit.INCIDENTS_DIR", tmp_path / "incidents"),
|
patch("wake_alarm._audit.INCIDENTS_DIR", tmp_path / "incidents"),
|
||||||
patch("wake_alarm._audit_sources.LOG_JSONL_FILE", tmp_path / "audit.jsonl"),
|
patch("wake_alarm._audit_sources.LOG_JSONL_FILE", tmp_path / "audit.jsonl"),
|
||||||
@ -199,6 +222,7 @@ def _hermetic(tmp_path: Path) -> Generator[None]:
|
|||||||
patch("wake_alarm._rtc_hw.RTC_ARMED_FILE", tmp_path / "rtc_armed.json"),
|
patch("wake_alarm._rtc_hw.RTC_ARMED_FILE", tmp_path / "rtc_armed.json"),
|
||||||
patch("wake_alarm._ring_player._run", _no_process),
|
patch("wake_alarm._ring_player._run", _no_process),
|
||||||
patch("wake_alarm._ring_player._popen", _no_process),
|
patch("wake_alarm._ring_player._popen", _no_process),
|
||||||
|
patch("wake_alarm._ring_monitors._spawn", _no_process),
|
||||||
patch("wake_alarm._rtc_hw._run", _no_process),
|
patch("wake_alarm._rtc_hw._run", _no_process),
|
||||||
patch("wake_alarm._audit_sources._run", _no_process),
|
patch("wake_alarm._audit_sources._run", _no_process),
|
||||||
# The shared free-day pool lives under ~/.local/share, outside every
|
# The shared free-day pool lives under ~/.local/share, outside every
|
||||||
|
|||||||
@ -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"]
|
||||||
|
|||||||
64
wake_alarm/tests/test_enforcement_notifications.py
Normal file
64
wake_alarm/tests/test_enforcement_notifications.py
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
"""``EnforcementView.notifications_off_since``: the 21:00 check's input."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from wake_alarm._enforcement_payload import EnforcementView
|
||||||
|
from wake_alarm._enforcement_records import PhoneEvent
|
||||||
|
|
||||||
|
DAY = "2026-11-22"
|
||||||
|
|
||||||
|
|
||||||
|
def _notif(hour: int, minute: int, enabled: object, day: int = 22) -> PhoneEvent:
|
||||||
|
at = datetime(2026, 11, day, hour, minute).astimezone().isoformat()
|
||||||
|
return PhoneEvent(at=at, kind="notifications", data={"enabled": enabled})
|
||||||
|
|
||||||
|
|
||||||
|
def _view(*events: PhoneEvent) -> EnforcementView:
|
||||||
|
return EnforcementView(phone_events=events)
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_event_today_is_none() -> None:
|
||||||
|
assert _view().notifications_off_since(DAY) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_newest_event_saying_off_is_returned() -> None:
|
||||||
|
view = _view(_notif(15, 0, enabled=True), _notif(21, 0, enabled=False))
|
||||||
|
assert (
|
||||||
|
view.notifications_off_since(DAY) == datetime(2026, 11, 22, 21, 0).astimezone()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_newer_event_saying_on_clears_it() -> None:
|
||||||
|
view = _view(_notif(21, 5, enabled=True), _notif(21, 0, enabled=False))
|
||||||
|
assert view.notifications_off_since(DAY) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_yesterdays_off_does_not_count_today() -> None:
|
||||||
|
view = _view(_notif(21, 0, enabled=False, day=21))
|
||||||
|
assert view.notifications_off_since(DAY) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_malformed_newer_event_neither_starts_nor_silences() -> None:
|
||||||
|
view = _view(
|
||||||
|
_notif(21, 0, enabled=False),
|
||||||
|
_notif(21, 5, enabled="true"),
|
||||||
|
_notif(21, 6, enabled=None),
|
||||||
|
)
|
||||||
|
assert (
|
||||||
|
view.notifications_off_since(DAY) == datetime(2026, 11, 22, 21, 0).astimezone()
|
||||||
|
)
|
||||||
|
assert _view(_notif(21, 6, enabled=0)).notifications_off_since(DAY) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_other_kinds_and_undatable_events_are_ignored() -> None:
|
||||||
|
view = _view(
|
||||||
|
PhoneEvent(at="nope", kind="notifications", data={"enabled": False}),
|
||||||
|
PhoneEvent(
|
||||||
|
at=datetime(2026, 11, 22, 21, 0).astimezone().isoformat(),
|
||||||
|
kind="bypass",
|
||||||
|
data={"enabled": False},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assert view.notifications_off_since(DAY) is None
|
||||||
@ -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()
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user