mirror of
https://github.com/kuhyx/wake-alarm.git
synced 2026-11-24 21:26:20 +01:00
Compare commits
67 Commits
v1.0.0-bui
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| af503f465f | |||
| 10625bd29f | |||
| 4e946483f5 | |||
| 0059d44571 | |||
| be45e5969a | |||
| 0432a9968f | |||
| 00cc8ca223 | |||
| 6be954afd4 | |||
| 032358cc03 | |||
| 9d98a57909 | |||
| 96e4388297 | |||
| 65df7f6682 | |||
| 1df4f64393 | |||
| 8253836612 | |||
| 83e1e158fd | |||
| 0d66b64fb5 | |||
| df314d5dbe | |||
| 69cfc6270b | |||
| 8c511c148c | |||
| 35d6d07d8e | |||
| 0781c42222 | |||
| 7a2340bbf8 | |||
| cf0d243ffd | |||
| 863b94a7d5 | |||
| e398f47740 | |||
| 2e0111724b | |||
| 01a6b7e5e7 | |||
| 1793009449 | |||
| ddc076ee51 | |||
| a12fae9666 | |||
| a36c4e596c | |||
| 209da92c5e | |||
| 8efaa518ad | |||
| b603cbf342 | |||
| 899a2c5581 | |||
| 224015cc2e | |||
| 5937e22131 | |||
| 59a853839c | |||
| 677a9f0f00 | |||
| 7a3b767075 | |||
| dec4ecc0cb | |||
| f0de01f9aa | |||
| 7aae649d44 | |||
| a353977afd | |||
| 38fb4f3763 | |||
| 78c41bd167 | |||
| 9250db4cc1 | |||
| 9dbc4547ee | |||
| 3b7f561452 | |||
| 8e6fa90c80 | |||
| 6cb51ad0f2 | |||
| 4dbde2b525 | |||
| 28327d322a | |||
| 6c248e712e | |||
| 52c3ff5f1e | |||
| 89e6eed105 | |||
| 06b70ab312 | |||
| 10938ed012 | |||
| f182453567 | |||
| 537a3a79e4 | |||
| 672eaf8aba | |||
| 13f6e3f5d2 | |||
| 5525ca6f95 | |||
| 58c4260b6e | |||
| 6033e3815f | |||
| 18a304de55 | |||
| a51a67e2fe |
2
.dep-freshness-no-workflow
Normal file
2
.dep-freshness-no-workflow
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
# Dependency freshness runs locally only (pre-commit hook); no GitHub Actions
|
||||||
|
# workflow. This marker stops the fleet installer from re-adding it.
|
||||||
62
.github/workflows/dependency-freshness.yml
vendored
62
.github/workflows/dependency-freshness.yml
vendored
@ -1,62 +0,0 @@
|
|||||||
name: dependency freshness
|
|
||||||
|
|
||||||
# Every dependency on its ecosystem's newest STABLE release, enforced on push
|
|
||||||
# as well as at commit time. The local pre-commit hook only sees the manifests
|
|
||||||
# in a commit and can be skipped entirely by a fresh clone that never ran
|
|
||||||
# `pre-commit install`; this runs `--all` over the whole repo.
|
|
||||||
#
|
|
||||||
# `--strict` is CI-only. Offline the gate degrades to its cached answer and
|
|
||||||
# passes, because `--no-verify` is banned locally and a hook that hard-failed
|
|
||||||
# on a flaky connection would leave no way to commit. A runner is always
|
|
||||||
# online, so here an undeterminable answer is a real failure.
|
|
||||||
#
|
|
||||||
# Expect this to go red for reasons this repo's commit did not cause: an
|
|
||||||
# upstream release overnight is enough. That is the chosen behaviour -- the
|
|
||||||
# alternative is a gate that only notices staleness when someone remembers to
|
|
||||||
# look.
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [main]
|
|
||||||
pull_request:
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
dependency-freshness:
|
|
||||||
name: dependencies on newest stable
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
# The gate lives in the shared utils repo so every repo resolves the
|
|
||||||
# same "latest stable" the same way. Checking it out beats vendoring a
|
|
||||||
# copy, which is exactly how a gate and its survey start disagreeing.
|
|
||||||
- name: Check out the shared gate
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
repository: kuhyx/utils
|
|
||||||
path: .utils
|
|
||||||
|
|
||||||
# "3.x", never a pinned minor: the Python target IS the interpreter the
|
|
||||||
# gate runs under (registries/toolchain.python_installed), so a runner
|
|
||||||
# held a release behind this machine reports a repo's `requires-python`
|
|
||||||
# as excluding "latest" while the same check passes locally. flax-docs-mcp
|
|
||||||
# hit exactly that -- `>=3.14` green here, red on a 3.13 runner.
|
|
||||||
- name: Set up Python
|
|
||||||
uses: actions/setup-python@v5
|
|
||||||
with:
|
|
||||||
python-version: "3.x"
|
|
||||||
|
|
||||||
- name: Install the gate's two runtime dependencies
|
|
||||||
run: python -m pip install --upgrade pyyaml packaging
|
|
||||||
|
|
||||||
- name: Cache registry lookups
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: ~/.cache/dep-freshness
|
|
||||||
key: dep-freshness-${{ hashFiles('**/pubspec.yaml', '**/pyproject.toml',
|
|
||||||
'**/requirements*.txt', '**/package.json', '**/Cargo.toml', '**/go.mod') }}
|
|
||||||
restore-keys: dep-freshness-
|
|
||||||
|
|
||||||
- name: Every dependency is on newest stable
|
|
||||||
run: bash .utils/scripts/check_dependency_freshness.sh --all --strict
|
|
||||||
2
.github/workflows/pre-commit.yml
vendored
2
.github/workflows/pre-commit.yml
vendored
@ -27,7 +27,7 @@ jobs:
|
|||||||
# fail-open.
|
# fail-open.
|
||||||
- group: rest
|
- group: rest
|
||||||
hooks: ""
|
hooks: ""
|
||||||
skip: mypy,pylint,free-days-interop
|
skip: mypy,pylint,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
|
||||||
|
|||||||
2
.github/workflows/python-tests.yml
vendored
2
.github/workflows/python-tests.yml
vendored
@ -71,7 +71,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: kuhyx/utils/flutter-setup@flutter-setup-v1
|
- uses: kuhyx/utils/flutter-setup@flutter-setup-v1
|
||||||
with:
|
with:
|
||||||
flutter-version: 3.47.9
|
flutter-version: 3.50.1
|
||||||
working-directory: phone_app
|
working-directory: phone_app
|
||||||
|
|
||||||
- name: Dart writes, Python replays, both must agree
|
- name: Dart writes, Python replays, both must agree
|
||||||
|
|||||||
2
.github/workflows/release-apk.yml
vendored
2
.github/workflows/release-apk.yml
vendored
@ -87,7 +87,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: subosito/flutter-action@v2
|
- uses: subosito/flutter-action@v2
|
||||||
with:
|
with:
|
||||||
flutter-version: 3.47.9
|
flutter-version: 3.50.1
|
||||||
channel: stable
|
channel: stable
|
||||||
cache: true
|
cache: true
|
||||||
|
|
||||||
|
|||||||
@ -8,6 +8,7 @@ default_language_version:
|
|||||||
default_stages: [pre-commit]
|
default_stages: [pre-commit]
|
||||||
fail_fast: false
|
fail_fast: false
|
||||||
|
|
||||||
|
default_install_hook_types: [pre-commit, pre-push, post-commit, post-merge, post-rewrite]
|
||||||
repos:
|
repos:
|
||||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||||
rev: v4.6.0
|
rev: v4.6.0
|
||||||
@ -95,6 +96,8 @@ repos:
|
|||||||
rev: v3.3.2
|
rev: v3.3.2
|
||||||
hooks:
|
hooks:
|
||||||
- id: pylint
|
- id: pylint
|
||||||
|
# dill (pylint --jobs) crashes on 3.15 (co_lnotab gone); 3.14 until it catches up.
|
||||||
|
language_version: python3.14
|
||||||
args:
|
args:
|
||||||
- --rcfile=pyproject.toml
|
- --rcfile=pyproject.toml
|
||||||
- --fail-under=10
|
- --fail-under=10
|
||||||
@ -105,10 +108,11 @@ repos:
|
|||||||
# direct URLs for one distribution, so any pin that drifts from
|
# direct URLs for one distribution, so any pin that drifts from
|
||||||
# the manifest becomes an unresolvable hook environment rather
|
# the manifest becomes an unresolvable hook environment rather
|
||||||
# than merely an old one.
|
# than merely an old one.
|
||||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.10.0#subdirectory=gatelock
|
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock
|
||||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#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.0#subdirectory=freedays
|
- kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
|
||||||
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.3.0#subdirectory=sickdays
|
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
|
||||||
|
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays
|
||||||
# Test suites intentionally use patterns (protected-access, magic-value
|
# Test suites intentionally use patterns (protected-access, magic-value
|
||||||
# comparisons) that don't belong in the source-code 10/10 gate.
|
# comparisons) that don't belong in the source-code 10/10 gate.
|
||||||
exclude: ^(\.venv/)|(^|/)(tests/|conftest\.py)
|
exclude: ^(\.venv/)|(^|/)(tests/|conftest\.py)
|
||||||
@ -186,6 +190,30 @@ repos:
|
|||||||
language: system
|
language: system
|
||||||
files: \.(md|markdown)$
|
files: \.(md|markdown)$
|
||||||
|
|
||||||
|
- id: todo-closer
|
||||||
|
name: close Todo trailer tasks
|
||||||
|
entry: scripts/todo_hooks.sh closer
|
||||||
|
language: system
|
||||||
|
stages: [post-commit]
|
||||||
|
always_run: true
|
||||||
|
pass_filenames: false
|
||||||
|
|
||||||
|
- id: todo-import-pr-merge
|
||||||
|
name: import PR Todo sections (pull)
|
||||||
|
entry: scripts/todo_hooks.sh import-pr post-merge
|
||||||
|
language: system
|
||||||
|
stages: [post-merge]
|
||||||
|
always_run: true
|
||||||
|
pass_filenames: false
|
||||||
|
|
||||||
|
- id: todo-import-pr-rewrite
|
||||||
|
name: import PR Todo sections (pull --rebase)
|
||||||
|
entry: scripts/todo_hooks.sh import-pr post-rewrite
|
||||||
|
language: system
|
||||||
|
stages: [post-rewrite]
|
||||||
|
always_run: true
|
||||||
|
pass_filenames: false
|
||||||
|
|
||||||
# Every dependency on its ecosystem's newest STABLE release, exact-pinned
|
# Every dependency on its ecosystem's newest STABLE release, exact-pinned
|
||||||
# so the question is mechanically answerable at all.
|
# so the question is mechanically answerable at all.
|
||||||
#
|
#
|
||||||
|
|||||||
162
AGENTS.md
162
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)
|
||||||
|
|
||||||
@ -39,8 +43,8 @@ passing sent the user back to the start.
|
|||||||
re-baselined at tag 1, so walking to tag 1 already banks them and the stage
|
re-baselined at tag 1, so walking to tag 1 already banks them and the stage
|
||||||
passes on its first poll. The 2-minute elapsed floor (`requiredElapsed`)
|
passes on its first poll. The 2-minute elapsed floor (`requiredElapsed`)
|
||||||
applies **only under bypass/away**, where no tag proved the walk and a
|
applies **only under bypass/away**, where no tag proved the walk and a
|
||||||
shaken phone would count; on the normal path it was two minutes of ringing
|
shaken phone would count; on the normal path it only added two minutes of
|
||||||
nothing could shorten (dropped 2026-09-16).
|
ringing (dropped 2026-09-16).
|
||||||
- **Answers are cumulative, not consecutive.** A wrong one costs the attempt
|
- **Answers are cumulative, not consecutive.** A wrong one costs the attempt
|
||||||
and nothing else.
|
and nothing else.
|
||||||
- **The bypass skips the tags, never the walk.** After
|
- **The bypass skips the tags, never the walk.** After
|
||||||
@ -50,8 +54,7 @@ passing sent the user back to the start.
|
|||||||
bed for five minutes and answer questions without standing up — weaker than
|
bed for five minutes and answer questions without standing up — weaker than
|
||||||
the gate this replaced. Do not "simplify" it into that.
|
the gate this replaced. Do not "simplify" it into that.
|
||||||
- **No challenge may hide its prompt.** The memorise-then-hide kind was
|
- **No challenge may hide its prompt.** The memorise-then-hide kind was
|
||||||
deleted, not merely unrouted: the ring screen is reached by walking in from
|
deleted, not merely unrouted: the ring screen is reached by walking in.
|
||||||
another room.
|
|
||||||
|
|
||||||
**The dismiss does not end the morning.** Since 2026-09-16 it hands over, in
|
**The dismiss does not end the morning.** Since 2026-09-16 it hands over, in
|
||||||
the same activity, to the silent **morning session**: weigh in → bathroom tag
|
the same activity, to the silent **morning session**: weigh in → bathroom tag
|
||||||
@ -69,10 +72,10 @@ clock, and everything that is a hard crash or a silent no-ring:
|
|||||||
**`DOCS-phone-alarm.md`**.
|
**`DOCS-phone-alarm.md`**.
|
||||||
|
|
||||||
**Free days.** On a day in the shared pool (`~/src/utils/freedays`) the phone
|
**Free days.** On a day in the shared pool (`~/src/utils/freedays`) the phone
|
||||||
does not ring at all: `AlarmReceiver` checks a native cache Dart rewrites
|
does not ring: `AlarmReceiver` checks a native cache Dart rewrites after every
|
||||||
after every mark/release/sync. Picker, cache and its fail-closed contract:
|
mark/release/sync. Picker, cache, fail-closed contract: **`DOCS-free-days.md`**.
|
||||||
**`DOCS-free-days.md`**. Sick days (`~/src/utils/sickdays`, never a free day):
|
Sick days (`~/src/utils/sickdays`, never a free day): phone + pre-alarm sync
|
||||||
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
|
||||||
|
|
||||||
@ -88,66 +91,69 @@ today's fire instant in **local** time, and fires iff `now` is in
|
|||||||
`was_trigger_fired_today()`. Without it the routine restarts on every tick for
|
`was_trigger_fired_today()`. Without it the routine restarts on every tick for
|
||||||
the rest of the 60-minute window: the unit is `Type=simple`, so a start while
|
the rest of the 60-minute window: the unit is `Type=simple`, so a start while
|
||||||
it runs is a no-op, but the moment the workout lock finishes the next tick
|
it runs is a no-op, but the moment the workout lock finishes the next tick
|
||||||
relaunches it on top of the user. This latch replaced the alarm's own
|
relaunches it on top of the user. The latch replaced the alarm's own dismissal
|
||||||
dismissal record when `_alarm.py` was deleted — deleting one without adding the
|
record when `_alarm.py` was deleted; deleting one without adding the other is
|
||||||
other is a silent regression, and that is exactly the trap.
|
a silent regression.
|
||||||
|
|
||||||
`Persistent=true` plus the 60-minute window is also what replaced the deleted
|
`Persistent=true` plus the 60-minute window also replaced the deleted
|
||||||
systemd-sleep hook: a suspended or just-booted machine still fires.
|
systemd-sleep hook: a suspended or just-booted machine still fires.
|
||||||
|
|
||||||
## Reading the phone's alarm
|
## Reading the phone's alarm
|
||||||
|
|
||||||
`_sync.py` is the only reader.
|
`_sync.py` is the only reader; `_sync_transport.py` fetches, `_sync_token.py`
|
||||||
|
holds the GitHub-token lookup (stdlib-only).
|
||||||
|
|
||||||
- Source of truth: a `crdt_sync` log written by `phone_app/` under
|
- Source of truth: a `crdt_sync` log written by `phone_app/` under
|
||||||
`wake-alarm-sync/devices/<device-id>/alarm.json`, at
|
`wake-alarm-sync/devices-e2e/<device-id>/alarm.json`, at
|
||||||
`.alarm.fields.alarm_hour[0]` / `.alarm_minute[0]`. Same logical path on both
|
`.alarm.fields.alarm_hour[0]` / `.alarm_minute[0]`. Same logical path on both
|
||||||
backends, so only the transport differs, never the parse.
|
backends, so only the transport differs, never the parse.
|
||||||
|
- **End-to-end encrypted** (since 2026-11-12): fields are sealed with a key
|
||||||
|
derived from the shared passphrase (`~/.config/crdt-sync/password` on the
|
||||||
|
PC, the keystore + lock icon in Settings on the phone). Both readers go
|
||||||
|
through `open_encrypted_client`, which copies the old plaintext
|
||||||
|
`wake-alarm-sync/devices` over once per process and never deletes it. No
|
||||||
|
or wrong passphrase reads as "nothing published" (cache, then 08:00) —
|
||||||
|
never plaintext. diet_guard reads the same prefix for weigh-ins.
|
||||||
- **The Firebase reader discovers device directories; it is not pinned to
|
- **The Firebase reader discovers device directories; it is not pinned to
|
||||||
`devices/phone/`.** The phone's device id is migrating from the fixed
|
`devices/phone/`.** The phone's device id is migrating from the constant
|
||||||
constant `phone` to a per-install uuid, and a pinned reader would silently
|
`phone` to a per-install uuid; a pinned reader would silently stop seeing
|
||||||
stop seeing the alarm and fall back to 08:00 — i.e. the wrong
|
the alarm and fall back to 08:00, the wrong time. `_fetch_firebase_alarm()`
|
||||||
time. `_fetch_firebase_alarm()` lists `SYNC_DEVICES_PREFIX`, reads every
|
lists `SYNC_DEVICES_PREFIX`, reads every device's `alarm.json`, and picks the
|
||||||
device's `alarm.json`, and picks the newest by the hour field's **HLC**, with
|
newest by the hour field's **HLC** (`device_id` breaks exact ties). A payload
|
||||||
`device_id` breaking exact ties. A payload that does not parse is skipped
|
that does not parse is skipped, never allowed to win. `SYNC_ALARM_PATH`
|
||||||
rather than allowed to win. `SYNC_ALARM_PATH` remains as a last-resort read
|
stays as a last-resort read for a backend that lists nothing.
|
||||||
for a backend that lists nothing.
|
- Payload parsing/ranking lives in `_alarm_payload.py` ("what did the phone
|
||||||
- Payload parsing/ranking lives in `_alarm_payload.py`: `_sync.py` owns
|
say"); `_sync.py` owns fetching, caching and fallback.
|
||||||
fetching, caching and fallback; `_alarm_payload.py` owns "what did the phone
|
|
||||||
actually say".
|
|
||||||
- **Firebase first, GitHub as the cutover mirror.** Retiring the mirror is
|
- **Firebase first, GitHub as the cutover mirror.** Retiring the mirror is
|
||||||
deleting the GitHub branch plus `SYNC_API_BASE`/`SYNC_REPO_*`.
|
deleting the GitHub branch plus `SYNC_API_BASE`/`SYNC_REPO_*`.
|
||||||
- Firebase config: shared `~/.config/crdt-sync/firebase.json`; the refresh
|
- Firebase config: shared `~/.config/crdt-sync/firebase.json`; the refresh
|
||||||
token is cached per app under `SYNC_APP_NAME` (`wake_alarm`). The config file
|
token is cached per app under `SYNC_APP_NAME` (`wake_alarm`). The config is
|
||||||
is checked **before** anything is constructed, so an unconfigured machine
|
checked **before** anything is constructed, so an unconfigured machine never
|
||||||
never touches the network.
|
touches the network.
|
||||||
- GitHub token (fallback only): `~/.config/wake_alarm/sync.json` key `token`,
|
- GitHub token (fallback only): `~/.config/wake_alarm/sync.json` key `token`,
|
||||||
else diet_guard's raw `~/.config/diet_guard/sync_token` (screen-locker is
|
else diet_guard's raw `~/.config/diet_guard/sync_token` (screen-locker's is no
|
||||||
Firebase-only since 2026-10-09; its `sync_token` is no longer read).
|
longer read: Firebase-only since 2026-10-09). Needs `repo` scope; the repo is
|
||||||
Needs `repo` scope — the repo is private, so a token without access returns
|
private, so a token without access returns **404, not 403**.
|
||||||
**404, not 403**.
|
|
||||||
- `crdt_sync` is imported at module scope but **guarded by
|
- `crdt_sync` is imported at module scope but **guarded by
|
||||||
`try/except ImportError`**: the service runs `/usr/bin/python`, not a venv, so
|
`try/except ImportError`**: the service runs `/usr/bin/python`, not a venv, so
|
||||||
a dependency that failed to install must degrade the read to the GitHub path
|
a dependency that failed to install must degrade the read to the cache
|
||||||
rather than crash the per-minute trigger. The GitHub path stays stdlib-only
|
rather than crash the per-minute trigger. Both backends need it (the GitHub
|
||||||
for that reason. Verify with `/usr/bin/python3 -c "import crdt_sync"`, not the
|
mirror is read through `GitHubSyncClient`, encrypted too). Verify with
|
||||||
dev venv.
|
`/usr/bin/python3 -c "import crdt_sync"`, not the dev venv.
|
||||||
- Resolution chain in `get_alarm()`: fresh cache (< 5 min) → live fetch → stale
|
- Resolution chain in `get_alarm()`: fresh cache (< 5 min) → live fetch → stale
|
||||||
cache → 08:00. The cache bounds remote reads to ~288/day
|
cache → 08:00. The cache bounds remote reads to ~288/day.
|
||||||
despite the per-minute tick.
|
|
||||||
- **A record older than `PUBLISHED_ALARM_MAX_AGE_SECONDS` (14 days) is skipped
|
- **A record older than `PUBLISHED_ALARM_MAX_AGE_SECONDS` (14 days) is skipped
|
||||||
at every step, including the cache.** The check is on when the *phone
|
at every step, including the cache.** The check is on when the *phone
|
||||||
stamped it*, never on when we fetched — checking the fetch is trivially
|
stamped it*, never on when we fetched: the cache is rewritten from the same
|
||||||
defeated, because the cache is rewritten from the same stale record every few
|
stale record every few minutes, so `fetched_at` is always fresh. That is why
|
||||||
minutes, so `fetched_at` is always fresh however old the record behind it is.
|
the winning HLC's instant is carried through `_alarm_payload` →
|
||||||
That is why the winning HLC's instant is carried through `_alarm_payload` →
|
|
||||||
`_sync_transport` → the cache's `published_at`. Expiring is safe because
|
`_sync_transport` → the cache's `published_at`. Expiring is safe because
|
||||||
08:00 is the latest the phone can ever arm. An **undated** record is
|
08:00 is the latest the phone can ever arm. An **undated** record is
|
||||||
trusted, not expired: the GitHub mirror has no per-field HLC, so treating
|
trusted: the GitHub mirror has no per-field HLC, so treating "cannot tell"
|
||||||
"cannot tell" as "too old" would break that backend entirely.
|
as "too old" would break that backend entirely.
|
||||||
- **Degraded reads log at INFO, not WARNING.** `get_alarm()` runs every minute;
|
- **Degraded reads log at INFO, not WARNING.** `get_alarm()` runs every minute;
|
||||||
a persistent condition logged loudly is 1440 journal lines a day. `_trigger`
|
a loud persistent condition is 1440 journal lines a day. `_trigger` emits the
|
||||||
emits the single WARNING that matters: firing *now* on a non-phone time.
|
one WARNING that matters: firing *now* on a non-phone time.
|
||||||
- **The morning session is the carrot** (`_session.py`, `wake-alarm-session.timer`,
|
- **The morning session is the carrot** (`_session.py`, `wake-alarm-session.timer`,
|
||||||
**`DOCS-morning-session-pc.md`**): a completed-in-time morning defers the
|
**`DOCS-morning-session-pc.md`**): a completed-in-time morning defers the
|
||||||
workout and LeetCode locks to 11:00 via one signed file both consumers read.
|
workout and LeetCode locks to 11:00 via one signed file both consumers read.
|
||||||
@ -160,11 +166,10 @@ is what `_trigger` starts, and it now runs one leg: `screen_locker.screen_lock`.
|
|||||||
Its alarm leg was removed in the same change that deleted `_alarm.py`.
|
Its alarm leg was removed in the same change that deleted `_alarm.py`.
|
||||||
|
|
||||||
**When this package's module paths change, the orchestrator must change in the
|
**When this package's module paths change, the orchestrator must change in the
|
||||||
same commit.** Leaving it pointing at a module that no longer exists caused a
|
same commit.** A stale path caused a month-long silent production failure
|
||||||
month-long silent production failure once already (2026-05-28, orchestrator
|
(2026-05-28, orchestrator still on `python_pkg.screen_locker.screen_lock` after
|
||||||
still on `python_pkg.screen_locker.screen_lock` after screen-locker's
|
screen-locker's extraction): the alarm fired and dismissed correctly while the
|
||||||
extraction): the alarm fired and dismissed correctly while the workout lock
|
workout lock crashed with `ModuleNotFoundError` on every run.
|
||||||
crashed with `ModuleNotFoundError` on every run.
|
|
||||||
|
|
||||||
## Production dependency installation
|
## Production dependency installation
|
||||||
|
|
||||||
@ -176,41 +181,36 @@ site-packages:
|
|||||||
/usr/bin/python3 -m pip install --user --break-system-packages -e .
|
/usr/bin/python3 -m pip install --user --break-system-packages -e .
|
||||||
```
|
```
|
||||||
|
|
||||||
**Run `install.sh` (or `pip install -e`) from a durable clone**, not a scratch
|
**Run `install.sh` (or `pip install -e`) from a durable clone**
|
||||||
directory — it is editable, so a later `git pull` in that clone updates the
|
(`~/src/wake-alarm`, mirroring `~/src/screen-locker`), not a scratch directory:
|
||||||
running production code. From `/tmp` or via `pip install "wake_alarm @ git+..."`
|
it is editable, so a later `git pull` there updates the running production
|
||||||
you get a snapshot frozen at that commit, and the next push silently does not
|
code. From `/tmp` or via `pip install "wake_alarm @ git+..."` you get a
|
||||||
reach the running service. Convention: `~/src/wake-alarm`, mirroring
|
snapshot frozen at that commit, and the next push silently does not reach the
|
||||||
`~/src/screen-locker`.
|
service.
|
||||||
|
|
||||||
If you add a dependency and only install it into a dev venv, the service fails
|
A dependency installed only into a dev venv makes the service fail with
|
||||||
with `ModuleNotFoundError` on its next run — this exact gap caused a 3-day
|
`ModuleNotFoundError` on its next run (this gap caused a 3-day diet_guard
|
||||||
diet_guard outage. Verify against `/usr/bin/python3 -c "import <dep>"`.
|
outage). Verify against `/usr/bin/python3 -c "import <dep>"`.
|
||||||
|
|
||||||
## Uninstalling
|
## Uninstalling
|
||||||
|
|
||||||
`uninstall.sh`, never `rm -rf` on the repo: it also removes the root ring
|
`uninstall.sh`, never `rm -rf` on the repo: it also removes the root ring
|
||||||
unit, the logind power-key drop-in and an RTC alarm we armed, and retires the
|
unit, the logind power-key drop-in and an RTC alarm we armed, and retires the
|
||||||
old `/usr/local/bin/shutdown` wrapper wherever one survives. `install.sh` calls `uninstall.sh --retired-only` as its last step, so
|
old `/usr/local/bin/shutdown` wrapper wherever one survives. `install.sh` calls
|
||||||
**`uninstall.sh` is load-bearing for installing**, not just for removing —
|
`uninstall.sh --retired-only` last, so **`uninstall.sh` is load-bearing for
|
||||||
renaming or deleting it breaks a fresh install. That call is non-fatal and
|
installing** — renaming or deleting it breaks a fresh install. That call is
|
||||||
gated on `sudo -n`: the cleanup needs root, and a hard failure there would
|
non-fatal and gated on `sudo -n`: the cleanup needs root, and a hard failure
|
||||||
abort an install that had already placed the package and enabled 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.**
|
per-file redirect gets forgotten when a new writer appears (`_trigger` was
|
||||||
`_trigger` writes it now, and the trigger tests never redirected it — a
|
one), and the failure is silent: a green suite that stamped the live file.
|
||||||
per-file redirect is exactly the kind that gets forgotten when a new writer
|
|
||||||
appears, and the failure is silent: a green suite that quietly stamped the
|
|
||||||
live state file.
|
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
@ -220,13 +220,14 @@ and the root ring unit's `systemctl start|stop` lines live there.
|
|||||||
- lint: `pre-commit run ruff --all-files && cd phone_app && flutter analyze --fatal-infos --fatal-warnings`
|
- lint: `pre-commit run ruff --all-files && cd phone_app && flutter analyze --fatal-infos --fatal-warnings`
|
||||||
- coverage: `python -m pytest -q wake_alarm/tests/ --cov=wake_alarm --cov-branch --cov-report=xml --cov-fail-under=100`
|
- coverage: `python -m pytest -q wake_alarm/tests/ --cov=wake_alarm --cov-branch --cov-report=xml --cov-fail-under=100`
|
||||||
- coverage-gaps: `coverage-gaps coverage.xml`
|
- coverage-gaps: `coverage-gaps coverage.xml`
|
||||||
|
- 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`; watch live
|
Other: full lint gate `pre-commit run --all-files`; live log
|
||||||
`journalctl --user -fu wake-alarm-trigger.service`; `bash install.sh` /
|
`journalctl --user -fu wake-alarm-trigger.service`; `bash install.sh` /
|
||||||
`bash uninstall.sh`; shell/system scripts gate `bash scripts/vmbox/harness.sh`
|
`bash uninstall.sh`; shell/system scripts gate `bash scripts/vmbox/harness.sh`
|
||||||
(disposable Arch VM, **`DOCS-vmbox.md`**); emulator morning
|
(disposable Arch VM, **`DOCS-vmbox.md`**); emulator morning
|
||||||
`phone_app/scripts/emu_morning.py` (`DOCS-morning-session.md`); ring the phone
|
`phone_app/scripts/emu_morning.py` (`DOCS-morning-session.md`); ring the phone
|
||||||
via `lib/main_ring_probe.dart` (`DOCS-phone-alarm.md` — starts a **real**
|
via `lib/main_ring_probe.dart` (`DOCS-phone-alarm.md`, starts a **real**
|
||||||
alarm). The dev venv lacks `gatelock`: anything importing `_state` (incl.
|
alarm). The dev venv lacks `gatelock`: anything importing `_state` (incl.
|
||||||
`_trigger`) needs `/usr/bin/python3`, not `.venv/bin/python`.
|
`_trigger`) needs `/usr/bin/python3`, not `.venv/bin/python`.
|
||||||
|
|
||||||
@ -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).
|
||||||
@ -82,8 +82,18 @@ cutoffs, neither imports `crdt_sync`, neither talks to Firebase:
|
|||||||
**A PC booted mid-morning** has a missing or yesterday's file until the
|
**A PC booted mid-morning** has a missing or yesterday's file until the
|
||||||
timer's `Persistent=true` catch-up lands, and that needs the network. Only
|
timer's `Persistent=true` catch-up lands, and that needs the network. Only
|
||||||
the enforce path, only inside 05:00–11:00, and only when the file is not
|
the enforce path, only inside 05:00–11:00, and only when the file is not
|
||||||
today's, both consumers retry for ≤ 30 s (5 s steps) and then proceed as
|
today's, both consumers retry for ≤ 180 s (5 s steps) and then proceed as
|
||||||
normal with a WARNING. Status paths never wait; tests pin the retry to 0.
|
normal with a WARNING. Status paths never wait; tests pin the retry to 0.
|
||||||
|
The refresher itself retries an unreadable backend every 5 s for 150 s
|
||||||
|
(`REFRESH_RETRY_SECONDS`) before exiting 1 with a WARNING: a PC booted at
|
||||||
|
07:48 had no DNS for its first seconds, and the old single try left the next
|
||||||
|
chance at the 07:50 tick (2026-11-07).
|
||||||
|
|
||||||
|
**`next_step`** (signed with the rest): while the session is `in_progress`,
|
||||||
|
the label of the first leg not in the phone's `passed` map, else `null`.
|
||||||
|
Names and labels live in `_session_legs.py` and are pinned to the phone's
|
||||||
|
`SessionLeg` by `wake_alarm/tests/fixtures/session_legs.json`, asserted by a
|
||||||
|
Python and a Dart test.
|
||||||
|
|
||||||
## Known limits (v1, deliberate)
|
## Known limits (v1, deliberate)
|
||||||
|
|
||||||
|
|||||||
@ -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`.
|
||||||
|
|
||||||
@ -23,7 +23,7 @@ screen, and every log line and event says `sick_day`.
|
|||||||
| Per-locker sheet | `phone_app/lib/screens/sick_day_sheet.dart` (+ the dot in `day_cell.dart`) |
|
| Per-locker sheet | `phone_app/lib/screens/sick_day_sheet.dart` (+ the dot in `day_cell.dart`) |
|
||||||
| Sync | `phone_app/lib/services/sick_day_sync.dart` (shared tick: `day_pool_sync.dart`), Firebase only |
|
| Sync | `phone_app/lib/services/sick_day_sync.dart` (shared tick: `day_pool_sync.dart`), Firebase only |
|
||||||
| Ring path | `android/.../SickDays.kt` (+ `DayCache.kt`), read in `AlarmReceiver` through `RingDecision.kt` |
|
| Ring path | `android/.../SickDays.kt` (+ `DayCache.kt`), read in `AlarmReceiver` through `RingDecision.kt` |
|
||||||
| Stick | `StickCheck.kt`: verdict `sick_day`; the streak skips sick days like free days |
|
| Stick | `StickCheck.kt`: verdict `sick_day`; the streak skips sick days like free days; a ring skipped for a sick day stays `sick_day` after a later clear (`RingWatch.markSkipped`) |
|
||||||
| Pre-alarm sync | `PoolSyncAlarm.kt`, `PoolSyncSchedule.kt`, `PoolSyncEngine.kt` → `poolSyncMain` → `day_pool_refresh.dart` |
|
| Pre-alarm sync | `PoolSyncAlarm.kt`, `PoolSyncSchedule.kt`, `PoolSyncEngine.kt` → `poolSyncMain` → `day_pool_refresh.dart` |
|
||||||
|
|
||||||
## The picker
|
## The picker
|
||||||
|
|||||||
38
DOCS-textgate-keep.md
Normal file
38
DOCS-textgate-keep.md
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
# Text-free keep list
|
||||||
|
|
||||||
|
Every `textgate scan` hit that stays on purpose. `scripts/check_textgate_keep.sh`
|
||||||
|
runs the scan and fails on any hit no row below covers. Rework rationale and the
|
||||||
|
per-screen decisions: `~/data/wake-alarm_notext/keep.md` (2026-11-10 rework).
|
||||||
|
|
||||||
|
## Scan exceptions
|
||||||
|
|
||||||
|
First cell: a file, or a directory ending in `/`. Second cell: the exact text,
|
||||||
|
or `*` for any text. The checker parses only this table.
|
||||||
|
|
||||||
|
| Path | Text | Reason |
|
||||||
|
|---|---|---|
|
||||||
|
| `docs/explanations/` | * | Generated by the `explain-diff` skill (`docs/explanations/index.html`). Explanation pages for the repo, not app UI; a text-free explanation defeats its purpose. |
|
||||||
|
|
||||||
|
## Kept but not flagged by the scan
|
||||||
|
|
||||||
|
Rows copied from the rework's keep list. The scan does not report these today;
|
||||||
|
they are listed so the next rework does not delete them.
|
||||||
|
|
||||||
|
### OS-level labels: the app name only
|
||||||
|
|
||||||
|
| Where | Text | Reason |
|
||||||
|
|---|---|---|
|
||||||
|
| `phone_app/lib/ui/app_name.dart` `kAppName` | `WakeAlarm` | `MaterialApp.title`: the task-switcher name, a proper noun |
|
||||||
|
| `phone_app/android/app/src/main/AndroidManifest.xml` | `android:label="WakeAlarm"` | launcher label, a proper noun |
|
||||||
|
| `phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AppName.kt` `APP_NAME` | `WakeAlarm` | name of the ring and session notification channels |
|
||||||
|
|
||||||
|
### Content: data the program only displays
|
||||||
|
|
||||||
|
| Where | Content | Reason |
|
||||||
|
|---|---|---|
|
||||||
|
| `room_proof_screen.dart`, `session_tags_screen.dart` | registered NFC tag ids | authored identifiers read off the tag |
|
||||||
|
| `ring_challenge.dart` `challenge.display` | digits, operators, sequences, the reversed word | the thing you must read to dismiss; always visible |
|
||||||
|
| `home_location_screen.dart` | captured SSID, BSSIDs, coordinates | read from the radio |
|
||||||
|
| all screens | clock times, numeral dates, counts, kg, `N/M` | numbers |
|
||||||
|
| `escape_dialog.dart` | the excuse text kuhy types | typed value |
|
||||||
|
| `alarm_publisher.dart` two `publish()` failure strings | spoken labels, two distinct cue kinds | CLAUDE.md: keep both messages |
|
||||||
@ -30,16 +30,37 @@ 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
|
||||||
every 20 s.
|
every 20 s.
|
||||||
|
|
||||||
|
**A `no_session` ring after a phone ring is correct, not a missed read
|
||||||
|
(traced 2026-11-16).** On 2026-10-26 and 2026-11-01 the PC went
|
||||||
|
`waiting` → `no_session` at A+15. It never logged `phone_silent`, so it did
|
||||||
|
see `ring_started`. What it never saw was a session for today: the
|
||||||
|
session tick logged "Newest morning is 2026-10-25" and "2026-10-29" all
|
||||||
|
morning. Firebase agrees. On 11-01 the phone fired, opened the ring screen
|
||||||
|
at 07:43 and then logged nothing until a boot at 11:27: no `dismissed`
|
||||||
|
event, no session. On 10-26 the session started at 11:01. So the PC was
|
||||||
|
right on both days. A ringing phone that nobody dismisses is the case the
|
||||||
|
`no_session` row exists for. `test_fallback_policy.py`
|
||||||
|
(`test_ring_started_waits_for_the_session_grace`) pins it. Why the phone
|
||||||
|
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)
|
||||||
|
|
||||||
@ -54,7 +75,13 @@ lives in CMOS, so it survives however the PC goes down.
|
|||||||
29–44 s after the alarm (FADT: "RTC can wake system from S4 = 1").
|
29–44 s after the alarm (FADT: "RTC can wake system from S4 = 1").
|
||||||
A typed `shutdown` stays a real poweroff.
|
A typed `shutdown` stays a real poweroff.
|
||||||
- `poweroff`: no logind change; relies on the firmware waking from S5.
|
- `poweroff`: no logind change; relies on the firmware waking from S5.
|
||||||
Unverified until the host S5 test runs.
|
vmbox only, 2026-11-15 (`vm new --uefi`, OVMF): `rtcwake -m no -s 120`
|
||||||
|
then `systemctl poweroff` left AIE and `RTC_EN` set in CMOS, and the
|
||||||
|
guest cold-booted 12 s (guest clock) after the alarm (`result=woke`).
|
||||||
|
QEMU has no S5 wake path, so `vm wake` emulates the firmware half: this
|
||||||
|
proves the arming survives a poweroff, not that this board wakes from S5.
|
||||||
|
Host S5 firmware check dropped by kuhy 2026-11-15 (needs a physical
|
||||||
|
power-on).
|
||||||
|
|
||||||
### Phone stick (Tue/Wed/Thu, not free days)
|
### Phone stick (Tue/Wed/Thu, not free days)
|
||||||
|
|
||||||
@ -78,60 +105,13 @@ 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.
|
|
||||||
|
|
||||||
### Escape hatch (until 2026-10-15 inclusive)
|
### Escape hatch (until 2026-10-15 inclusive)
|
||||||
|
|
||||||
Home screen button "That was a bug". Needs a typed reason ≥ 40 characters.
|
Bug-glyph button on the stakes card (spoken label "That was a bug"; the
|
||||||
|
app is text-free since 2026-11-10). Needs a typed reason ≥ 40 characters.
|
||||||
It lifts the phone lockdown, clears the streak, cancels today's PC penalty,
|
It lifts the phone lockdown, clears the streak, cancels today's PC penalty,
|
||||||
stops a ringing PC alarm, and writes everything into the incident report.
|
stops a ringing PC alarm, and writes everything into the incident report.
|
||||||
Unlimited uses — every use is listed at the top of that day's report.
|
Unlimited uses — every use is listed at the top of that day's report.
|
||||||
@ -160,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/`)
|
||||||
|
|
||||||
@ -176,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
|
||||||
@ -187,10 +171,29 @@ 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`.
|
||||||
|
|
||||||
|
## The desktop must come back after lockdown (2026-11-20)
|
||||||
|
|
||||||
|
The carrot assumes the PC has a desktop in the morning. On 2026-11-20 it did
|
||||||
|
not: the nightly `auto-system-update` installed NVIDIA 620.73 and kernel 7.3.5
|
||||||
|
while the PC sat in night lockdown. At 05:00 the unlock started lightdm, Xorg
|
||||||
|
died on `NVRM: API mismatch`, lightdm hit `start-limit-hit`, and every later
|
||||||
|
trigger logged "already UNLOCKED". kuhy saw only the text console.
|
||||||
|
|
||||||
|
The fix lives in digital-wellbeing (`lib/payloads/night-lockdown-gui-recover.sh`):
|
||||||
|
a morning trigger that finds state UNLOCKED with lightdm down starts it again,
|
||||||
|
after `reset-failed`. On a driver mismatch it reloads the NVIDIA modules. When
|
||||||
|
the running kernel has no modules left, it reboots once that day. Boot units
|
||||||
|
that raced DNS (`reflector`, `periodic-system-startup`) now retry
|
||||||
|
(system-maintenance). The cause of that race: testsAndMisc's Arch performance
|
||||||
|
fixers had disabled `NetworkManager-wait-online`, so `network-online.target`
|
||||||
|
was reached before the LAN existed; they now keep it enabled. Nothing in this repo changed: the morning session and
|
||||||
|
its 11:00 deferral were fine; only the desktop was missing.
|
||||||
|
|
||||||
## Verification status (2026-10-01)
|
## Verification status (2026-10-01)
|
||||||
|
|
||||||
- vmbox gate (`scripts/vmbox/harness.sh`, `guest_cases_v2.sh`): install,
|
- vmbox gate (`scripts/vmbox/harness.sh`, `guest_cases_v2.sh`): install,
|
||||||
@ -201,17 +204,30 @@ PC (`events.jsonl` `event`): `fallback_tick` (only on decision change),
|
|||||||
root ALSA ring got `Device or resource busy` while PipeWire still held the
|
root ALSA ring got `Device or resource busy` while PipeWire still held the
|
||||||
card seconds after a PipeWire ring — at night the card is idle and opens
|
card seconds after a PipeWire ring — at night the card is idle and opens
|
||||||
(a silent root `aplay` passed), but a stream left open overnight would
|
(a silent root `aplay` passed), but a stream left open overnight would
|
||||||
keep it busy. **Open:** what the root ring does about a held card is
|
keep it busy. **Decided 2026-11-15:** on the *first* busy open (no retries)
|
||||||
kuhy's call (killing the holder was refused by the auto-mode classifier).
|
`ring_alsa.sh` rings through the user's PipeWire (`runuser`, then
|
||||||
|
`python -m wake_alarm._ring_main`); only if that fails does it `fuser -k
|
||||||
|
-TERM` the card's playback nodes once, retry ALSA once and exit non-zero.
|
||||||
|
Fallback before kill, because the holder is PipeWire itself. The fallback's
|
||||||
|
`ring_backend` event says `FAILED` (`started=false`) when PipeWire cannot
|
||||||
|
play, and the unit's non-zero exit is the loud failure; the user-level
|
||||||
|
fallback ring is the last line. Gate: vmbox `ring-alsa-busy-fallback`
|
||||||
|
(10 repetitions) and `ring-alsa-busy-fails-loudly`.
|
||||||
- Emulator (`wake_alarm_api36`): exact A+15 check hidden from the system
|
- Emulator (`wake_alarm_api36`): exact A+15 check hidden from the system
|
||||||
next-alarm, headless `ring_started` on a heads-up ring, boot-path miss
|
next-alarm, headless `ring_started` on a heads-up ring, boot-path miss
|
||||||
(phone off before the alarm) → lockdown through tomorrow, escape hatch.
|
(phone off before the alarm) → lockdown through tomorrow, escape hatch.
|
||||||
Not yet on the Pixel: the real focus-owner reaction and Firebase publish.
|
Not yet on the Pixel: the real focus-owner reaction and Firebase publish.
|
||||||
|
- Item 13 (black screen): dropped by kuhy 2026-11-12
|
||||||
|
- Two-tag dismiss on device: dropped by kuhy 2026-11-12
|
||||||
|
- Locked-keyguard dismiss on device: dropped by kuhy 2026-11-12
|
||||||
|
|
||||||
## Evidence for Claude
|
## Evidence for Claude
|
||||||
|
|
||||||
`python -m wake_alarm._audit [YYYY-MM-DD]` and the 11:05 timer write
|
`python -m wake_alarm._audit [YYYY-MM-DD] [--stdout | --force]` and the 11:05 timer write
|
||||||
`~/data/wake-alarm/incidents/<date>.md`: a merged phone + PC timeline, then
|
`~/data/wake-alarm/incidents/<date>.md` (outside the repo: personal data): a merged
|
||||||
expected-vs-observed checks (alarm known, RTC armed the night before, PC up
|
phone + PC timeline, then expected-vs-observed checks (alarm known, RTC armed, PC up
|
||||||
by `A`, ring/fallback, penalty, lockdown), mismatches and escape uses first.
|
by `A`, ring/fallback, penalty, lockdown, phone pushed within `PHONE_PUSH_STALE_SECONDS`
|
||||||
Outside the repo on purpose: it holds personal data.
|
= 24 h by newest dated HLC; n/a when Firebase is unreachable), mismatches and escapes first.
|
||||||
|
An existing report is never overwritten silently: exit 2 `refusing to overwrite <path>`
|
||||||
|
unless `--force`; `--stdout` (alias `--dry-run`) prints and writes nothing, not even
|
||||||
|
`audit_written`.
|
||||||
|
|||||||
@ -1,112 +0,0 @@
|
|||||||
# Refactor TODO — enforce the 250-line file cap
|
|
||||||
|
|
||||||
> **This file is a ready-to-use prompt.** Paste it to Claude, or open this repo
|
|
||||||
> and say "do refactor_claude_todo". It is self-contained: everything needed to
|
|
||||||
> execute is below. Generated 2026-08-14 from a measured survey of every repo.
|
|
||||||
|
|
||||||
## Goal
|
|
||||||
|
|
||||||
Every file in this repo must be **at most 250 lines** — source, tests, and
|
|
||||||
prose (`.md`/`.txt`/`.rst`/`.tex`) alike — and must **stay** that way forever,
|
|
||||||
enforced by a gate that fails the commit, not by a note anyone can ignore.
|
|
||||||
|
|
||||||
Why: a file that cannot be read in one piece forces re-reads and partial edits,
|
|
||||||
which is the single largest avoidable cost in an LLM-assisted workflow. Aim by
|
|
||||||
churn, not size alone — refactoring pays where code is read and changed often
|
|
||||||
(Fowler, _refactoring economic benefit_).
|
|
||||||
|
|
||||||
## Scope in this repo
|
|
||||||
|
|
||||||
- **18 files** currently exceed 250 lines (of 73 eligible files).
|
|
||||||
- **6,553 lines** sit in violation; longest file is **478 lines**.
|
|
||||||
|
|
||||||
Exempt (do NOT split these):
|
|
||||||
|
|
||||||
- generated files — `*.g.dart`, `*.freezed.dart`, `*.gr.dart`, `**/l10n/generated/**`,
|
|
||||||
anything with a `GENERATED` header
|
|
||||||
- markup — `.html`, `.css`, `.scss`
|
|
||||||
- data files — `.json`, `.yaml`, `.csv`, wordlists and other data-ish `.txt`
|
|
||||||
(mean line length under 25 chars)
|
|
||||||
|
|
||||||
## Violations, highest ROI first
|
|
||||||
|
|
||||||
ROI = lines x commits in the last year. Work top-down; a long file nobody edits
|
|
||||||
has near-zero payoff and should not be first.
|
|
||||||
|
|
||||||
| lines | commits/yr | kind | file |
|
|
||||||
| ----: | ---------: | :--- | :------------------------------------- |
|
|
||||||
| 478 | 15 | code | `wake_alarm/_alarm.py` |
|
|
||||||
| 438 | 12 | code | `wake_alarm/tests/test_alarm_part2.py` |
|
|
||||||
| 435 | 12 | code | `wake_alarm/tests/test_alarm.py` |
|
|
||||||
| 358 | 8 | code | `wake_alarm/tests/test_alarm_part3.py` |
|
|
||||||
| 457 | 4 | code | `wake_alarm/tests/test_alarm_sinks.py` |
|
|
||||||
| 283 | 6 | code | `wake_alarm/tests/test_alarm_part4.py` |
|
|
||||||
| 329 | 4 | code | `wake_alarm/_alarm_view.py` |
|
|
||||||
| 405 | 3 | code | `wake_alarm/_audio.py` |
|
|
||||||
| 386 | 3 | code | `wake_alarm/tests/test_sync.py` |
|
|
||||||
| 371 | 3 | code | `wake_alarm/_sync.py` |
|
|
||||||
| 317 | 3 | code | `wake_alarm/_escape_flow.py` |
|
|
||||||
| 314 | 3 | code | `wake_alarm/tests/test_state.py` |
|
|
||||||
| 420 | 2 | code | `wake_alarm/tests/test_alarm_audio.py` |
|
|
||||||
| 351 | 2 | code | `wake_alarm/tests/test_smart_plug.py` |
|
|
||||||
| 341 | 2 | code | `wake_alarm/_sinks.py` |
|
|
||||||
|
|
||||||
_(3 further files over 250 lines not listed — re-run the survey for the full set.)_
|
|
||||||
|
|
||||||
## How to split
|
|
||||||
|
|
||||||
- **Python** — extract cohesive helpers into sibling modules; keep the public
|
|
||||||
API and imports stable.
|
|
||||||
- **Shell** — split into `lib/*.sh` sourced by a thin entry script. Keep
|
|
||||||
`set -euo pipefail` in each.
|
|
||||||
- **Dart / TypeScript** — extract widgets/components into their own files.
|
|
||||||
- **Tests** — split by test-group into sibling files
|
|
||||||
(`foo.test.ts` -> `foo.parsing.test.ts`, `foo.render.test.ts`). Coverage must
|
|
||||||
not drop.
|
|
||||||
- **Docs** — split into topic files under `docs/` with an index. For an
|
|
||||||
oversized `CLAUDE.md`, move detail into referenced docs so the
|
|
||||||
always-loaded part shrinks.
|
|
||||||
|
|
||||||
**Do not** game the cap: no one-lining, no deleting tests, no moving code into
|
|
||||||
an exempt extension, no `# noqa`-style suppressions.
|
|
||||||
|
|
||||||
## Make it permanent (required — this is the point)
|
|
||||||
|
|
||||||
A refactor without a gate silently regrows. Before this task is done:
|
|
||||||
|
|
||||||
1. Wire the shared gate `~/src/utils/scripts/check_file_length.sh` into this repo's
|
|
||||||
`.pre-commit-config.yaml` as a local hook. If the repo has no pre-commit
|
|
||||||
config, add a minimal one.
|
|
||||||
2. The hook checks **files in the commit** (not the whole tree), so unrelated
|
|
||||||
commits never break, and it **fails** — exit 1, not a warning.
|
|
||||||
3. No baseline file and no allowlist. Those are suppressions.
|
|
||||||
4. If this repo has CI (`.github/workflows`), add the same check there so it
|
|
||||||
also fails on push.
|
|
||||||
|
|
||||||
## Done condition
|
|
||||||
|
|
||||||
- `bash ~/src/utils/scripts/check_file_length.sh --all` from this repo root exits 0.
|
|
||||||
- The repo's own test suite and coverage bar are still green.
|
|
||||||
- `pre-commit run --files <changed files>` passes.
|
|
||||||
- A deliberately over-250-line test file, staged, makes `git commit` **fail**.
|
|
||||||
- For a deployed daemon/app: the entry point still actually runs.
|
|
||||||
|
|
||||||
## Verify
|
|
||||||
|
|
||||||
Run the suite, then the alarm entry point. The phone_app companion needs `phone-deploy` verification if touched.
|
|
||||||
|
|
||||||
## Why this sat untouched (added 2026-08-24)
|
|
||||||
|
|
||||||
This repo ran a LOCAL `scripts/check_file_length.py` with `MAX_LINES = 500`,
|
|
||||||
under a hook named "Max file length (500 lines)". It reported "gated" while
|
|
||||||
permitting files every other repo rejects -- so the cap looked enforced and
|
|
||||||
nothing ever failed. The hook now delegates to the shared 250-line gate in
|
|
||||||
`~/src/utils`, which reports 17 real violations.
|
|
||||||
|
|
||||||
Done condition is now an exit code, not a count:
|
|
||||||
|
|
||||||
```
|
|
||||||
bash scripts/check_file_length.sh --all # must exit 0
|
|
||||||
```
|
|
||||||
|
|
||||||
REMOVE ME AFTER FINISH
|
|
||||||
@ -1,225 +0,0 @@
|
|||||||
# Wake-alarm hardening — continue here
|
|
||||||
|
|
||||||
REMOVE ME AFTER FINISH
|
|
||||||
|
|
||||||
Phases 0–7 are committed (`4286fcb`..`f5eb7fc`). This file is the entry point
|
|
||||||
for the rest. **Full plan, with every measured finding:**
|
|
||||||
`~/.claude/plans/wake-alarm-still-does-witty-toucan.md` — read it before
|
|
||||||
starting; this file deliberately does not duplicate it.
|
|
||||||
|
|
||||||
## Done so far
|
|
||||||
|
|
||||||
| Item | State |
|
|
||||||
|---|---|
|
|
||||||
| 6 audio (HDMI silent) | **Done.** `_reactivate` wired into `WakeAlarm`; verified on the host — the HDMI sink appeared and became default. |
|
|
||||||
| 7 speakers | `DOCS-speaker-recommendation.md`. Prose only, done. |
|
|
||||||
| 9 refactor | `_alarm.py` 478→250. 12 new modules; see `DOCS-architecture.md`. |
|
|
||||||
| 11 failsafe | `FAILSAFE_SILENCE_SECONDS=300`, audio only. Escalation re-tuned to fit inside it. |
|
|
||||||
| 12 logging | JSONL + cross-process dedupe + derived correlation id. |
|
|
||||||
| 14 fans | Gone: code, script, sudoers entry, installed state. Three stale doc/message references cleaned up in phase 6. |
|
|
||||||
| 2 power button | **Done.** `_inhibit.py` (logind block, self-terminating, stale cleanup by pid via `/proc`) + `_alarm_session.py` fire-time record, re-fired by `_trigger` outside the catch-up window. |
|
|
||||||
| 10 vmbox | **Done.** `scripts/vmbox/harness.sh` + `DOCS-vmbox.md`. 8 cases, fails closed. Found 2 live bugs the host could not reach. |
|
|
||||||
| 5 curtains | **Done.** `_curtains.py` driver protocol + no-op default, called from `prepare_hardware()`. `DOCS-curtains-hardware.md` has the buy list. |
|
|
||||||
| 1/4 phone alarm | **Done, verified on the phone.** Five Kotlin files behind one MethodChannel + the Dart ring screen. Fires from Doze on time, wakes the screen over the lockscreen, rings through DND on STREAM_ALARM, and dismisses via an NFC tap + challenge. Confirmed by the user on the Pixel 6a, not inferred. |
|
|
||||||
| 3 room proofs | **Mostly done.** NFC works end to end: `NfcReader.kt` (hand-written), Settings → "Room proof" registers the tag, and a tap satisfies the gate. Steps+elapsed is the fallback. QR is specified, persisted and unit-tested but has **no scanner UI** — `mobile_scanner` is the droppable extra. |
|
|
||||||
|
|
||||||
## Remaining, in order
|
|
||||||
|
|
||||||
1. ~~QR scanner UI~~ — **cancelled 2026-08-30.** QR was deleted rather than
|
|
||||||
finished: it had never been reachable at ring time (no scanner package, no
|
|
||||||
CAMERA permission, `onQrScanned` had no caller), and a printed code is
|
|
||||||
photographable, so completing it would have added a bypass to the very gate
|
|
||||||
the same change was hardening. The dismiss path is now a strict sequence:
|
|
||||||
tag 1 → 25 steps + 2 min → tag 2 → 3 challenges.
|
|
||||||
2. **Item 8, mutual gating.** Phone half is now in place. This is the phase
|
|
||||||
that legitimately touches `_sync.py`, so it carries that split (see below).
|
|
||||||
3. **Item 13, black screen.** Different repo (`~/src/testsAndMisc/
|
|
||||||
linux_configuration`), host-only, blocks nothing.
|
|
||||||
|
|
||||||
### Verified end to end on the Pixel 6a, 2026-08-27
|
|
||||||
|
|
||||||
**The whole path is confirmed on hardware, by the user, not inferred:**
|
|
||||||
|
|
||||||
- Fires from Doze on time (22:03:01 for a 22:03 arm), registered by the system
|
|
||||||
as `RTC_WAKEUP` / "Next wake from idle".
|
|
||||||
- Wakes the screen (`Asleep`→`Awake`) and puts `AlarmActivity` on top over the
|
|
||||||
lockscreen, with the full-screen-intent notification posted.
|
|
||||||
- **Rings through DND** — `zen_mode=1`, player `state:started` on
|
|
||||||
`usage=USAGE_ALARM`/`STREAM_ALARM(4)`, `mutedState:none`. The STREAM_ALARM
|
|
||||||
claim is measured, no longer assumed.
|
|
||||||
- NFC tag registers (Settings → Room proof) and **a tap dismisses**:
|
|
||||||
`tag discovered: 0465dab3ce2a81` on the ring screen, challenge solved,
|
|
||||||
alarm silent.
|
|
||||||
- Step counter reaches the gate.
|
|
||||||
|
|
||||||
**Four defects were found only because it was run on the phone**, every one
|
|
||||||
invisible to the emulator (no NFC, no step sensor) and to the widget tests
|
|
||||||
(which mock the channel):
|
|
||||||
|
|
||||||
1. `AlarmActivity.onPause` called `NfcReader.stop()`. `enableReaderMode` is
|
|
||||||
per-activity but `disableReaderMode` is global, so anything briefly in
|
|
||||||
front of the ring screen killed polling for the rest of the ring.
|
|
||||||
2. `TYPE_STEP_COUNTER` is cumulative and on-change: it emits nothing until the
|
|
||||||
user has already walked, and the first emission was being eaten as the
|
|
||||||
baseline, so the screen sat at `0/25` forever. `TYPE_STEP_DETECTOR` is now
|
|
||||||
primary — one event per stride, no baseline to miss.
|
|
||||||
3. NFC does not poll while the ring shows over a locked keyguard
|
|
||||||
(`mScreenState=ON_LOCKED`). `requestDismissKeyguard()` is called on fire.
|
|
||||||
It does **not** silently unlock a secured phone — it raises the PIN prompt
|
|
||||||
— so "tap without touching the phone" was never achievable on a secured
|
|
||||||
device. Say that plainly; don't let docs imply otherwise.
|
|
||||||
4. The **flash** challenge hides its code after 4s, which is unsolvable when
|
|
||||||
the screen is reached by walking to another room. Removed from the phone's
|
|
||||||
rotation, with a test asserting no self-hiding challenge is ever shown.
|
|
||||||
|
|
||||||
**A process lesson worth more than any of them:** after hardware confirmed the
|
|
||||||
path worked, the next change bundled a MethodChannel restructure with a bug
|
|
||||||
fix and regressed both NFC and steps. The user caught it. When hardware has
|
|
||||||
just gone green, make the smallest possible delta on top of *that exact state*
|
|
||||||
— never a restructure and a fix together.
|
|
||||||
|
|
||||||
### Fully automatic, verified on the Pixel 2026-08-27
|
|
||||||
|
|
||||||
The alarm is no longer opt-in and can no longer be weakened:
|
|
||||||
|
|
||||||
- **Arms itself with zero taps.** Launching the app was enough —
|
|
||||||
`dumpsys alarm` showed `RTC_WAKEUP ... com.kuhy.wake_alarm_sync/.AlarmReceiver`
|
|
||||||
at `2026-08-28 08:00:00`, `window=0`, `exactAllowReason=policy_permission`.
|
|
||||||
- **08:00 daily is baked in** (`AlarmPolicy.baselineHour`, mirrored by the PC's
|
|
||||||
`FALLBACK_ALARM_HOUR`). There is no arm button and no cancel — the Kotlin
|
|
||||||
`cancel` handler is deleted, so the capability does not exist rather than
|
|
||||||
being one `invokeMethod` away.
|
|
||||||
- **Earlier-only ratchet, confirmed on-device.** Picking a later time was
|
|
||||||
rejected on the phone with "That is not earlier than 08:00. The alarm can
|
|
||||||
only be moved earlier.", and the armed alarm stayed at 08:00. An earlier
|
|
||||||
start is one-shot and resets after the alarm fires.
|
|
||||||
- **Daily watchdog** (`AlarmWatchdog`) re-arms if nothing is scheduled, and
|
|
||||||
`BootReceiver` re-establishes it because `setInexactRepeating` does not
|
|
||||||
survive a reboot.
|
|
||||||
- **PC watchdog:** `_trigger._clamp_to_baseline()` refuses any resolved alarm
|
|
||||||
later than 08:00 whatever its source, so a stale or tampered remote value
|
|
||||||
cannot move the alarm later through sync.
|
|
||||||
|
|
||||||
### DND: verified for priority mode, NOT for total silence
|
|
||||||
|
|
||||||
Measured on the Pixel: `STREAM_ALARM` is unmuted under **priority** DND
|
|
||||||
(`zen_mode=1`, mask `0x1a6`) and **muted** under **total silence**
|
|
||||||
(`zen_mode=2`, mask `0x9be`). The confirmed ring was priority DND. No audio
|
|
||||||
flag escapes total silence, so if that gap matters the fix is a zen-policy
|
|
||||||
check at arm time, not an audio change. Detail in `DOCS-phone-alarm.md`.
|
|
||||||
|
|
||||||
Two harness traps found while testing this, worth keeping:
|
|
||||||
|
|
||||||
- **Do not pass `--build-number` to a probe build** — it produced a
|
|
||||||
non-running APK.
|
|
||||||
- **The arm probe can register for TOMORROW.** It calls `schedule()`, then
|
|
||||||
`main.dart`'s `rearm()` recomputes `nextOccurrence`; if the armed minute has
|
|
||||||
passed by then the alarm lands on the next day. Always re-check the
|
|
||||||
registered `triggerTime` is today before waiting for a ring.
|
|
||||||
|
|
||||||
### Still unverified
|
|
||||||
|
|
||||||
- The **two-tag sequence** has not been walked end to end on the phone: only
|
|
||||||
one physical tag is registered, so every on-device run so far has fallen
|
|
||||||
through to the 5-minute bypass. Needs a second tag.
|
|
||||||
- The **locked-keyguard** dismiss was not run to completion: the confirmed run
|
|
||||||
was on an unlocked phone. The PIN-prompt path is implemented but unproven.
|
|
||||||
|
|
||||||
## Decisions already made — do not re-litigate
|
|
||||||
|
|
||||||
- Failsafe stops **sound only**; lock, challenge and workout gate persist.
|
|
||||||
- Gating is **phone first, then PC**, with a bounded escape: if sync is
|
|
||||||
unreachable for ~600 s the PC gate degrades to locally-solvable, logged
|
|
||||||
WARNING. Without that, a Firebase outage means you can neither dismiss nor
|
|
||||||
get to work.
|
|
||||||
- Room proof: NFC **or** QR qualifies. **Steps alone does not** — the phone is
|
|
||||||
stationary in the other room while you walk *to* it, so steps only accrue
|
|
||||||
after pickup and can be faked by shaking it in bed. Steps + elapsed time is
|
|
||||||
the fallback when both others fail. (I narrowed "any one satisfies" here;
|
|
||||||
say if you disagree.)
|
|
||||||
- Phone alarm: hand-written Kotlin behind one MethodChannel, **not** a plugin.
|
|
||||||
AGP 9.0.1 / Gradle 9.1 / Kotlin 2.3.20 is bleeding edge and a plugin that
|
|
||||||
won't compile breaks the build outright. `STREAM_ALARM` is load-bearing —
|
|
||||||
it is what ignores DND and silent mode.
|
|
||||||
- Curtains: no hardware; pluggable driver + logging no-op default.
|
|
||||||
- Quality bar: 100% branch coverage, no new `# noqa` / `type: ignore`.
|
|
||||||
|
|
||||||
## Traps found in the phone session
|
|
||||||
|
|
||||||
- **The plan's `LogStore.changes` does not exist.** `crdt_sync_dart` has no
|
|
||||||
Stream at all. Re-arm therefore needs three explicit hooks — startup,
|
|
||||||
BOOT_COMPLETED, dismiss — and dropping any one makes the alarm ring once
|
|
||||||
and then silently stop forever.
|
|
||||||
- **The Android SDK was never missing, only unexported.** `~/sdk/Android/Sdk` has
|
|
||||||
`cmdline-tools`, `emulator` and `platform-tools`; only `adb` was on PATH.
|
|
||||||
Export `ANDROID_HOME` rather than installing anything.
|
|
||||||
- **A permission declared in the manifest is not a permission granted.**
|
|
||||||
Both `POST_NOTIFICATIONS` and `ACTIVITY_RECOGNITION` are runtime grants, and
|
|
||||||
each one missing silently breaks a different half of the dismiss path
|
|
||||||
(no full-screen intent / no step sensor). The AVD caught both because a
|
|
||||||
freshly installed app there sits at `importance=NONE`.
|
|
||||||
- **A debug probe entrypoint with its own UI proves nothing about the route.**
|
|
||||||
The first probe rendered its own widget, so the AVD run validated the Kotlin
|
|
||||||
and nothing about `/ring`. Point the probe at the real app widget.
|
|
||||||
|
|
||||||
## Traps that cost time this session
|
|
||||||
|
|
||||||
- **The 250-line gate fires on *staged* files.** Touching a file means
|
|
||||||
splitting it in the same commit. Still over (re-measured 2026-08-27, after
|
|
||||||
phase 6): `test_sync.py` 386, `_sync.py` 371, `test_smart_plug.py` 351,
|
|
||||||
`_sinks.py` 341, `_alarm_view.py` 329, `_escape_flow.py` 317,
|
|
||||||
`test_state.py` 314. Budget for it. `test_trigger.py` is now split and
|
|
||||||
under.
|
|
||||||
- **`morning_routine/_orchestrator.py:39` hardcodes `"wake_alarm._alarm"`**
|
|
||||||
(different repo, `~/src/testsAndMisc`). Any module-path change updates it in the
|
|
||||||
*same* commit. This exact omission caused a month-long silent outage. Keep
|
|
||||||
`main()` in `_alarm.py`.
|
|
||||||
- **Splitting a test file loses its fixtures.** `_make_mock_tk`,
|
|
||||||
`_block_real_tk` and `_block_extra_devices` live *after* the imports, so a
|
|
||||||
naive header-copy drops them and every test errors. Copy the whole region
|
|
||||||
before the first `class`. Also: a multi-line module docstring gets stranded
|
|
||||||
if you replace only its first line.
|
|
||||||
- **Moving a symbol breaks `patch("wake_alarm._alarm.X")` silently** — the
|
|
||||||
patch stops intercepting and the test asserts nothing. Grep the whole
|
|
||||||
`tests/` tree for the old target after any move.
|
|
||||||
- **Autoformat strips an import added before its first usage.** `struct`
|
|
||||||
vanished from the extracted `_tone.py`; ruff, mypy and pylint all passed.
|
|
||||||
Only running it caught the `NameError`. Add import and usage in one edit.
|
|
||||||
- **Never let a beep-loop test miss its rung.** A test that patches only one
|
|
||||||
of `_beep_soft/_medium/_loud` and waits for it will spin forever on the real
|
|
||||||
audio stack and hang the whole suite instead of failing. Patch all three.
|
|
||||||
- Run tests with `/usr/bin/python3`, not the dev venv (no `gatelock` there).
|
|
||||||
- **`vm run` does not propagate the guest command's exit code** — it reports
|
|
||||||
the VM's verdict. A gate built on it fails *open*. See `DOCS-vmbox.md`.
|
|
||||||
- **`_state.py`'s UTC `_today_str()` must NOT be flipped to local**, despite
|
|
||||||
what the plan says. `screen_locker/_wake_state.py` mirrors the helper and
|
|
||||||
reads the same `wake_state.json`; flipping it loses an earned workout skip
|
|
||||||
for any dismissal between 00:00 and 02:00 local. `_alarm_session.py` shows
|
|
||||||
the way around it: carry an aware `fired_at`, compare elapsed time, no date
|
|
||||||
key at all.
|
|
||||||
- **Do not split a file the current change does not already have to touch.**
|
|
||||||
The gate fires on *staged* files, so an oversized file only becomes your
|
|
||||||
problem once you edit it. Editing `_sync.py` merely to repoint an import
|
|
||||||
pulled its 371 lines into the changeset and cascaded into five new modules
|
|
||||||
and a broken tree before being reverted. Prefer putting a new constant in
|
|
||||||
its single consumer (as `_curtains.py` does) over touching `_constants.py`.
|
|
||||||
- **A `__main__` CLI extracted to a new module breaks its documented command
|
|
||||||
silently.** `python -m wake_alarm._sync --show` printed nothing and exited
|
|
||||||
0 — invisible to ruff, mypy, pylint and the suite alike. If a later phase
|
|
||||||
moves that CLI, run the documented command and check the *output*.
|
|
||||||
- **Ruff's autofix will gut a function** whose results are only printed —
|
|
||||||
it stripped both the assignments and the `print` from a vmbox check, and
|
|
||||||
every linter stayed green. Grep the file for its output call after any
|
|
||||||
autofix.
|
|
||||||
|
|
||||||
## Verify
|
|
||||||
|
|
||||||
```
|
|
||||||
/usr/bin/python3 -m pytest wake_alarm/tests/ -q # 455 pass, 100% cov
|
|
||||||
bash scripts/vmbox/harness.sh # 8/8 cases, exit 0
|
|
||||||
pre-commit run --files <changed>
|
|
||||||
/usr/bin/python3 -m wake_alarm._trigger --dry-run
|
|
||||||
/usr/bin/python3 -m wake_alarm._alarm --demo # real window; ask first
|
|
||||||
```
|
|
||||||
|
|
||||||
Done = every item above shipped, this file deleted.
|
|
||||||
@ -1,63 +0,0 @@
|
|||||||
# Hardware ideas: defeat a fully-powered-off phone
|
|
||||||
|
|
||||||
REMOVE ME AFTER FINISH
|
|
||||||
|
|
||||||
Both items below were scoped during the 2026-09-23 workday-stick session
|
|
||||||
(`DOCS-morning-session-pc.md`) and explicitly deferred out of scope for that
|
|
||||||
session: no existing firmware project and no owned wearable, both need a real
|
|
||||||
purchase before any code gets written. Written here instead of
|
|
||||||
`~/src/todo/BACKLOG.md` because that file is gitignored/export-only from the
|
|
||||||
todo app and a manual edit there is silently lost on the next export — this
|
|
||||||
is the durable copy.
|
|
||||||
|
|
||||||
## Item 1 — second wake-alarm device: rings independently of the phone's power state
|
|
||||||
|
|
||||||
### what
|
|
||||||
An ESP32 + buzzer that polls the same Firebase alarm/session record
|
|
||||||
wake-alarm already reads and keeps ringing until it sees a dismiss or a
|
|
||||||
started session — so powering the phone off can no longer silently kill the
|
|
||||||
whole wake attempt the way it does today.
|
|
||||||
|
|
||||||
### where
|
|
||||||
new repo (no existing ESP32/PlatformIO/Arduino project anywhere in `~/src`
|
|
||||||
to build on — checked). Firebase-only, per the "new syncing apps are
|
|
||||||
Firebase-only" rule.
|
|
||||||
|
|
||||||
### must
|
|
||||||
- must not require the phone to relay anything — the whole point is
|
|
||||||
surviving the phone being off.
|
|
||||||
- optional: a physical snooze/dismiss button, since the phone's own dismiss
|
|
||||||
gate isn't reachable from the device.
|
|
||||||
|
|
||||||
### done
|
|
||||||
On a Tue/Wed/Thu, power the phone off right at the alarm and the ESP32
|
|
||||||
still rings, and keeps ringing, until the phone's session shows a start.
|
|
||||||
|
|
||||||
### verify
|
|
||||||
Bench test first (USB power, no case), then a real overnight run.
|
|
||||||
|
|
||||||
### read first
|
|
||||||
- `DOCS-phone-alarm.md` (the Firebase alarm schema to poll)
|
|
||||||
- `DOCS-morning-session-pc.md` (why this exists: the workday-stick project,
|
|
||||||
2026-09-23)
|
|
||||||
|
|
||||||
## Item 2 — wearable wake-defeat check
|
|
||||||
|
|
||||||
### what
|
|
||||||
A cheap fitness band whose own sleep log (stored on the band, synced later)
|
|
||||||
can show "asleep again after the alarm rang" even when the phone was fully
|
|
||||||
off and missed the whole thing.
|
|
||||||
|
|
||||||
### where
|
|
||||||
new app or an extension of `phone_app/`, once a device is picked.
|
|
||||||
|
|
||||||
### must
|
|
||||||
- must not: buy or integrate anything before checking Gadgetbridge's
|
|
||||||
current supported-device list — research first, kuhy owns no wearable and
|
|
||||||
none is integrated anywhere in `~/src` today (checked).
|
|
||||||
|
|
||||||
### done
|
|
||||||
Not yet scoped — picking a supported device is the blocking step.
|
|
||||||
|
|
||||||
### verify
|
|
||||||
Blank — desktop, once there's something to verify.
|
|
||||||
@ -1,90 +0,0 @@
|
|||||||
# Wake enforcement v2 — follow-ups for the next session
|
|
||||||
|
|
||||||
REMOVE ME AFTER FINISH
|
|
||||||
|
|
||||||
Handoff from the 2026-10-01 session that built v2. Read
|
|
||||||
`DOCS-wake-enforcement.md` (the contract + verification status) and
|
|
||||||
`AGENTS.md` first. Start **after the morning of 2026-10-02** so there is real
|
|
||||||
evidence to check.
|
|
||||||
|
|
||||||
## Prompt to paste into the new session
|
|
||||||
|
|
||||||
> Work through ~/src/wake-alarm/TODO-wake-enforcement-v2-followups.md top to
|
|
||||||
> bottom. Verify each item yourself on the real target (phone 23181JEGR08034,
|
|
||||||
> this PC) before calling it done, then delete the TODO file in the final
|
|
||||||
> commit.
|
|
||||||
|
|
||||||
## 1. Check the first real morning (2026-10-02, Fri, carrot day)
|
|
||||||
|
|
||||||
- `python -m wake_alarm._audit 2026-10-02` (and the 11:05 file in
|
|
||||||
`~/data/wake-alarm/incidents/`). Expected: phone `alarm_fired`
|
|
||||||
(`reason=daily`), `ring_started_published` with `source=alarm` (headless
|
|
||||||
engine, release build — never verified in release before) or
|
|
||||||
`ring_screen`, `stick_check` verdict for a non-stick day, no fallback ring
|
|
||||||
unless the phone really was silent.
|
|
||||||
- `adb logcat` for `WakeAlarmHeadless` / `WakeAlarmStick*` if anything is
|
|
||||||
missing. Firebase fields `ring_started`, `phone_events` must be non-empty
|
|
||||||
(`enforcement_view(fetch_firebase_logs())`).
|
|
||||||
- Any MISMATCH in the report is a bug to fix, not a note.
|
|
||||||
|
|
||||||
## 2. focus-owner reacting to a real lockdown (needs kuhy's OK + timing)
|
|
||||||
|
|
||||||
Never verified on the Pixel. Either wait for the first real Tue/Wed/Thu miss
|
|
||||||
and read focus-owner's Debug log (`LOCKDOWN_ACTIVATED` with the through-date,
|
|
||||||
then a `WORKDAY_LOCKDOWN` pass), or — with kuhy's explicit OK, at a time he
|
|
||||||
names — trigger one and lift it with the escape button (logs an escape).
|
|
||||||
|
|
||||||
## 3. Root ring vs a card held busy by PipeWire
|
|
||||||
|
|
||||||
Host test 2026-10-01: `wake-alarm-ring-alsa.service` got `Device or resource
|
|
||||||
busy` while the user's PipeWire held card `Generic_1` (ALC897). kuhy approved
|
|
||||||
killing the holder (`fuser -k -TERM /dev/snd/pcmC<N>D0p` after 3 busy opens,
|
|
||||||
in `scripts/pc/ring_alsa.sh`), but the auto-mode classifier refused the edit
|
|
||||||
twice. **kuhy must add a permission rule first**, or choose the non-killing
|
|
||||||
alternative: when the root unit cannot open the card, `_ring_player` falls
|
|
||||||
back to `PipeWireBackend` (PipeWire holds the card, so it can mix the ring
|
|
||||||
in). Add a vmbox case that holds `snd-dummy` open and proves the ring still
|
|
||||||
plays.
|
|
||||||
|
|
||||||
## 4. S5 (poweroff) RTC wake test on the host
|
|
||||||
|
|
||||||
Hibernate (S4) wake is verified and is the default mode. S5 is not. The
|
|
||||||
self-resume boot unit (`~/data/claude-scratch/wake-fw/s5_after_boot.sh`,
|
|
||||||
never installed) was refused by the classifier. Simplest: with kuhy present,
|
|
||||||
`sudo -n rtcwake -m no -s 240` + record the epoch, `systemctl poweroff`; kuhy
|
|
||||||
powers on if it does not wake; then compare `uptime -s` with the epoch. If S5
|
|
||||||
works, decide with kuhy whether to switch `pc_wake.json` to `poweroff` (covers
|
|
||||||
a typed `shutdown`, not just the power key).
|
|
||||||
|
|
||||||
## 5. utils dependency upgrade — prepared, uncommitted
|
|
||||||
|
|
||||||
In `~/src/utils` (do NOT stage the other session's `ts_config/README.md`,
|
|
||||||
`scripts/lib/alias-imports.mjs`, `test/alias-imports.test.js`): pylint 4.1.1
|
|
||||||
×3, typescript-eslint 8.71.0 (ts_config/ts_core/web_ui), @eslint-react
|
|
||||||
5.23.3, eslint-plugin-sonarjs 4.2.2, pnpm 12.8.1 (+ lockfiles,
|
|
||||||
`ts_config/pnpm-workspace.yaml`), allowlist: typescript-eslint entry removed,
|
|
||||||
typescript entry now `blocked_by: transitive:typescript-eslint@8.71.0`.
|
|
||||||
Lint + tests pass in all three. `finish_auto.sh` fails at its test step with
|
|
||||||
corepack `MODULE_NOT_FOUND .../pnpm/12.8.1/bin/pnpm.cjs` (pnpm 12.8 ships a
|
|
||||||
native binary; corepack 0.36 can't launch it). Global pnpm 12.8.1 is now
|
|
||||||
installed directly (`corepack disable pnpm`); find what in the gate still
|
|
||||||
calls corepack (read `~/data/claude-scratch/wake-v2/utils-commit.log`), fix,
|
|
||||||
commit, watch CI green.
|
|
||||||
|
|
||||||
## 6. Fleet repos still pinning typescript-eslint 8.70.0
|
|
||||||
|
|
||||||
The allowlist entry that excused them is gone, so their freshness gate turns
|
|
||||||
red on the next run: konbini-67, iron-and-anvil, awesome-mcp-explorer,
|
|
||||||
europe-county-map and any other repo pinning it (`grep -rl
|
|
||||||
'"typescript-eslint": "8.70.0"' ~/src --include=package.json`). Bump each to
|
|
||||||
8.71.0, lint + test, commit, CI green.
|
|
||||||
|
|
||||||
## 7. Small leftovers
|
|
||||||
|
|
||||||
- `~/src/todo`: `cupertino_icons` 1.0.9 → 2.0.0 — another session had
|
|
||||||
uncommitted work there; only bump once its tree is clean.
|
|
||||||
- Global `~/.claude/CLAUDE.md` sandbox-first note says the vmbox guest is
|
|
||||||
BIOS-only; vmbox has `--uefi` and `vm wake` (RTC-wake emulation) since
|
|
||||||
utils 694c013. Ask kuhy before editing that file.
|
|
||||||
- Clear the test data left in the `wake_alarm_api36` emulator (escape for
|
|
||||||
10-01, ringStarted, stick state) before it is ever signed into sync.
|
|
||||||
26
install.sh
26
install.sh
@ -11,7 +11,7 @@
|
|||||||
# What it does:
|
# What it does:
|
||||||
# 1. Installs wake_alarm + dependencies for /usr/bin/python
|
# 1. Installs wake_alarm + dependencies for /usr/bin/python
|
||||||
# 2. Installs the systemd user units and enables their timers (trigger,
|
# 2. Installs the systemd user units and enables their timers (trigger,
|
||||||
# session, fallback, rtc, audit)
|
# session, strip, fallback, rtc, audit)
|
||||||
# 3. Installs the root pieces of the fallback alarm: the ring WAVs, the
|
# 3. Installs the root pieces of the fallback alarm: the ring WAVs, the
|
||||||
# ALSA ring script + system unit, the sudoers lines that let the user
|
# ALSA ring script + system unit, the sudoers lines that let the user
|
||||||
# start/stop that unit, and (pc_wake.json "hibernate" mode only) the
|
# start/stop that unit, and (pc_wake.json "hibernate" mode only) the
|
||||||
@ -47,6 +47,8 @@ readonly TRIGGER_SERVICE_SRC="$SCRIPT_DIR/wake-alarm-trigger.service"
|
|||||||
readonly TRIGGER_TIMER_SRC="$SCRIPT_DIR/wake-alarm-trigger.timer"
|
readonly TRIGGER_TIMER_SRC="$SCRIPT_DIR/wake-alarm-trigger.timer"
|
||||||
readonly SESSION_SERVICE_SRC="$SCRIPT_DIR/wake-alarm-session.service"
|
readonly SESSION_SERVICE_SRC="$SCRIPT_DIR/wake-alarm-session.service"
|
||||||
readonly SESSION_TIMER_SRC="$SCRIPT_DIR/wake-alarm-session.timer"
|
readonly SESSION_TIMER_SRC="$SCRIPT_DIR/wake-alarm-session.timer"
|
||||||
|
readonly STRIP_SERVICE_SRC="$SCRIPT_DIR/wake-alarm-strip.service"
|
||||||
|
readonly STRIP_PATH_SRC="$SCRIPT_DIR/wake-alarm-strip.path"
|
||||||
readonly SYSTEMD_USER_DIR="$HOME/.config/systemd/user"
|
readonly SYSTEMD_USER_DIR="$HOME/.config/systemd/user"
|
||||||
# Enforcement v2 user units (service + timer each).
|
# Enforcement v2 user units (service + timer each).
|
||||||
readonly V2_UNITS=(wake-alarm-fallback wake-alarm-rtc wake-alarm-audit)
|
readonly V2_UNITS=(wake-alarm-fallback wake-alarm-rtc wake-alarm-audit)
|
||||||
@ -55,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)"
|
||||||
@ -62,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=""
|
||||||
@ -73,14 +78,18 @@ cleanup() {
|
|||||||
trap cleanup EXIT
|
trap cleanup EXIT
|
||||||
|
|
||||||
install_ring_audio() {
|
install_ring_audio() {
|
||||||
|
# fuser (psmisc): the ring script's last resort frees a held card with it.
|
||||||
|
command -v fuser >/dev/null 2>&1 || sudo pacman -S --needed --noconfirm psmisc
|
||||||
# Generated, never committed: the binary hook forbids WAVs in the repo.
|
# Generated, never committed: the binary hook forbids WAVs in the repo.
|
||||||
/usr/bin/python3 -m wake_alarm._ring_wav --write "$TEMP_DIR/wav" >/dev/null
|
/usr/bin/python3 -m wake_alarm._ring_wav --write "$TEMP_DIR/wav" >/dev/null
|
||||||
sudo install -D -m 0644 "$TEMP_DIR/wav/ring.wav" "$WAV_DIR/ring.wav"
|
sudo install -D -m 0644 "$TEMP_DIR/wav/ring.wav" "$WAV_DIR/ring.wav"
|
||||||
sudo install -D -m 0644 "$TEMP_DIR/wav/ring_loop.wav" "$WAV_DIR/ring_loop.wav"
|
sudo install -D -m 0644 "$TEMP_DIR/wav/ring_loop.wav" "$WAV_DIR/ring_loop.wav"
|
||||||
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"
|
||||||
sudo install -m 0644 "$PC_DIR/$ALSA_UNIT" "/etc/systemd/system/$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 "$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() {
|
||||||
@ -97,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() {
|
||||||
@ -130,11 +139,16 @@ echo "[1/4] Installing wake_alarm for /usr/bin/python..."
|
|||||||
echo " Installed. Verifying import..."
|
echo " Installed. Verifying import..."
|
||||||
/usr/bin/python3 -c "import wake_alarm; import gatelock"
|
/usr/bin/python3 -c "import wake_alarm; import gatelock"
|
||||||
echo " wake_alarm and gatelock import under /usr/bin/python."
|
echo " wake_alarm and gatelock import under /usr/bin/python."
|
||||||
|
# The alarm is end-to-end encrypted: without crdt_sync (pynacl, argon2-cffi)
|
||||||
|
# the trigger can only fall back to the cache and 08:00. Fail the install.
|
||||||
|
/usr/bin/python3 -c "import crdt_sync, nacl, argon2"
|
||||||
|
echo " crdt_sync (E2E) imports under /usr/bin/python."
|
||||||
|
|
||||||
echo "[2/4] Installing systemd user units..."
|
echo "[2/4] Installing systemd user units..."
|
||||||
mkdir -p "$SYSTEMD_USER_DIR"
|
mkdir -p "$SYSTEMD_USER_DIR"
|
||||||
cp "$TRIGGER_SERVICE_SRC" "$TRIGGER_TIMER_SRC" \
|
cp "$TRIGGER_SERVICE_SRC" "$TRIGGER_TIMER_SRC" \
|
||||||
"$SESSION_SERVICE_SRC" "$SESSION_TIMER_SRC" "$SYSTEMD_USER_DIR/"
|
"$SESSION_SERVICE_SRC" "$SESSION_TIMER_SRC" \
|
||||||
|
"$STRIP_SERVICE_SRC" "$STRIP_PATH_SRC" "$SYSTEMD_USER_DIR/"
|
||||||
for unit in "${V2_UNITS[@]}"; do
|
for unit in "${V2_UNITS[@]}"; do
|
||||||
cp "$SCRIPT_DIR/$unit.service" "$SCRIPT_DIR/$unit.timer" "$SYSTEMD_USER_DIR/"
|
cp "$SCRIPT_DIR/$unit.service" "$SCRIPT_DIR/$unit.timer" "$SYSTEMD_USER_DIR/"
|
||||||
done
|
done
|
||||||
@ -143,6 +157,8 @@ systemctl --user enable --now wake-alarm-trigger.timer
|
|||||||
echo " Trigger timer enabled and started (ticks once a minute)."
|
echo " Trigger timer enabled and started (ticks once a minute)."
|
||||||
systemctl --user enable --now wake-alarm-session.timer
|
systemctl --user enable --now wake-alarm-session.timer
|
||||||
echo " Session timer enabled (07:00-11:00, every 2 min)."
|
echo " Session timer enabled (07:00-11:00, every 2 min)."
|
||||||
|
systemctl --user enable --now wake-alarm-strip.path
|
||||||
|
echo " Strip path enabled (corner reminder while the morning is in progress)."
|
||||||
for unit in "${V2_UNITS[@]}"; do
|
for unit in "${V2_UNITS[@]}"; do
|
||||||
systemctl --user enable --now "$unit.timer"
|
systemctl --user enable --now "$unit.timer"
|
||||||
done
|
done
|
||||||
|
|||||||
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)
|
||||||
|
|||||||
@ -27,13 +27,15 @@ class AlarmReceiver : BroadcastReceiver() {
|
|||||||
}
|
}
|
||||||
// A shared free or sick day means the alarm does not ring -- not
|
// A shared free or sick day means the alarm does not ring -- not
|
||||||
// later, not quieter, not at all -- and nothing ring-related is
|
// later, not quieter, not at all -- and nothing ring-related is
|
||||||
// recorded: no markFired (the stick's own check skips the day too)
|
// recorded: no markFired and no ring_started for the PC. Only the
|
||||||
// and no ring_started for the PC. Re-arm for tomorrow (the armed
|
// skip itself is latched, so the stick still stands the day down if
|
||||||
|
// the mark is cleared after the ring time. Re-arm for tomorrow (the armed
|
||||||
// instant has passed, so it rolls over) so the day after is normal.
|
// instant has passed, so it rolls over) so the day after is normal.
|
||||||
// Both caches fail closed: unreadable means ring.
|
// Both caches fail closed: unreadable means ring.
|
||||||
val skip = RingDecision.skip(FreeDays.isToday(context), SickDays.isToday(context))
|
val skip = RingDecision.skip(FreeDays.isToday(context), SickDays.isToday(context))
|
||||||
if (skip != null) {
|
if (skip != null) {
|
||||||
Log.i(TAG, "${skip.label}: not ringing; re-armed for tomorrow")
|
Log.i(TAG, "${skip.label}: not ringing; re-armed for tomorrow")
|
||||||
|
RingWatch.markSkipped(context, skip)
|
||||||
EventLog.append(context, "alarm_fired", mapOf("reason" to skip.wire))
|
EventLog.append(context, "alarm_fired", mapOf("reason" to skip.wire))
|
||||||
AlarmScheduler.rearmFromStorage(context)
|
AlarmScheduler.rearmFromStorage(context)
|
||||||
return
|
return
|
||||||
@ -47,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. */
|
||||||
@ -105,10 +105,9 @@ class AlarmService : Service() {
|
|||||||
// IMPORTANCE_HIGH is required for a full-screen intent to be honoured.
|
// IMPORTANCE_HIGH is required for a full-screen intent to be honoured.
|
||||||
val channel = NotificationChannel(
|
val channel = NotificationChannel(
|
||||||
CHANNEL_ID,
|
CHANNEL_ID,
|
||||||
"Wake alarm",
|
APP_NAME,
|
||||||
NotificationManager.IMPORTANCE_HIGH,
|
NotificationManager.IMPORTANCE_HIGH,
|
||||||
).apply {
|
).apply {
|
||||||
description = "The ringing wake alarm"
|
|
||||||
// The service owns sound and vibration, so the channel must not add
|
// The service owns sound and vibration, so the channel must not add
|
||||||
// its own — a channel sound would play on the notification stream
|
// its own — a channel sound would play on the notification stream
|
||||||
// and be silenced by DND, unlike STREAM_ALARM.
|
// and be silenced by DND, unlike STREAM_ALARM.
|
||||||
@ -129,8 +128,6 @@ class AlarmService : Service() {
|
|||||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
)
|
)
|
||||||
return Notification.Builder(this, CHANNEL_ID)
|
return Notification.Builder(this, CHANNEL_ID)
|
||||||
.setContentTitle("Wake alarm")
|
|
||||||
.setContentText("Tap to dismiss")
|
|
||||||
.setSmallIcon(android.R.drawable.ic_lock_idle_alarm)
|
.setSmallIcon(android.R.drawable.ic_lock_idle_alarm)
|
||||||
.setCategory(Notification.CATEGORY_ALARM)
|
.setCategory(Notification.CATEGORY_ALARM)
|
||||||
.setOngoing(true)
|
.setOngoing(true)
|
||||||
|
|||||||
@ -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")
|
||||||
|
|||||||
@ -0,0 +1,9 @@
|
|||||||
|
package com.kuhy.wake_alarm_sync
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The app's only visible word, used as every notification channel's name.
|
||||||
|
*
|
||||||
|
* Matches `android:label` in AndroidManifest.xml and Dart's `kAppName`, so the
|
||||||
|
* notification settings name the app the way the launcher does.
|
||||||
|
*/
|
||||||
|
const val APP_NAME = "WakeAlarm"
|
||||||
@ -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,14 +30,27 @@ 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
|
||||||
if (engine != null) return
|
|
||||||
|
/**
|
||||||
|
* 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 (entrypoint == PUBLISH_ENTRYPOINT) pending = context.applicationContext to entrypoint
|
||||||
|
Log.w(TAG, "headless engine already running; $entrypoint ${if (pending != null) "queued" else "ignored"}")
|
||||||
|
return
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
val app = context.applicationContext
|
val app = context.applicationContext
|
||||||
val created = FlutterEngine(app)
|
val created = FlutterEngine(app)
|
||||||
@ -52,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")
|
||||||
@ -67,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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -32,9 +32,19 @@ object RingWatch {
|
|||||||
private const val KEY_FIRED_DATE = "fired_date"
|
private const val KEY_FIRED_DATE = "fired_date"
|
||||||
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_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) {
|
||||||
@ -42,6 +52,34 @@ object RingWatch {
|
|||||||
DateHistory.add(prefs(context), KEY_DISMISSED_DATES, LocalDate.now())
|
DateHistory.add(prefs(context), KEY_DISMISSED_DATES, LocalDate.now())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Latches that today's ring stood down for [skip]; called from
|
||||||
|
* [AlarmReceiver]. The stick reads it back via [skippedOn], so clearing
|
||||||
|
* the mark later that day cannot make the silenced day a miss.
|
||||||
|
*/
|
||||||
|
fun markSkipped(context: Context, skip: RingSkip) {
|
||||||
|
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. */
|
||||||
|
fun skippedOn(context: Context, day: LocalDate): RingSkip? =
|
||||||
|
RingSkip.entries.firstOrNull {
|
||||||
|
DateHistory.contains(prefs(context), KEY_SKIPPED_PREFIX + it.wire, day)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Whether the dismiss gate completed on [day]; read by [StickRunner],
|
* Whether the dismiss gate completed on [day]; read by [StickRunner],
|
||||||
* which judges past days too. The single [KEY_DISMISSED_DATE] predates
|
* which judges past days too. The single [KEY_DISMISSED_DATE] predates
|
||||||
|
|||||||
@ -15,7 +15,7 @@ import java.time.LocalDate
|
|||||||
*
|
*
|
||||||
* Two jobs, one record. The launcher starts [MainActivity], and it has to
|
* Two jobs, one record. The launcher starts [MainActivity], and it has to
|
||||||
* know *before any Dart runs* whether to step aside into the session screen;
|
* know *before any Dart runs* whether to step aside into the session screen;
|
||||||
* the notification needs the leg text with no engine running behind it.
|
* the notification needs the leg glyph with no engine running behind it.
|
||||||
* Dart rewrites this cache on every leg change (`updateSessionNotice`) and
|
* Dart rewrites this cache on every leg change (`updateSessionNotice`) and
|
||||||
* `finishSession` clears it, so it is only ever as stale as the last change.
|
* `finishSession` clears it, so it is only ever as stale as the last change.
|
||||||
*
|
*
|
||||||
@ -50,8 +50,7 @@ object SessionNotice {
|
|||||||
.apply()
|
.apply()
|
||||||
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||||
manager.createNotificationChannel(
|
manager.createNotificationChannel(
|
||||||
NotificationChannel(CHANNEL_ID, "Morning session", NotificationManager.IMPORTANCE_LOW)
|
NotificationChannel(CHANNEL_ID, APP_NAME, NotificationManager.IMPORTANCE_LOW),
|
||||||
.apply { description = "The live morning checklist" },
|
|
||||||
)
|
)
|
||||||
manager.notify(NOTIFICATION_ID, build(context, label, deadlineMillis))
|
manager.notify(NOTIFICATION_ID, build(context, label, deadlineMillis))
|
||||||
}
|
}
|
||||||
@ -87,7 +86,6 @@ object SessionNotice {
|
|||||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
)
|
)
|
||||||
val builder = Notification.Builder(context, CHANNEL_ID)
|
val builder = Notification.Builder(context, CHANNEL_ID)
|
||||||
.setContentTitle("Morning session")
|
|
||||||
.setContentText(label)
|
.setContentText(label)
|
||||||
.setSmallIcon(android.R.drawable.ic_lock_idle_alarm)
|
.setSmallIcon(android.R.drawable.ic_lock_idle_alarm)
|
||||||
.setCategory(Notification.CATEGORY_REMINDER)
|
.setCategory(Notification.CATEGORY_REMINDER)
|
||||||
|
|||||||
@ -38,6 +38,20 @@ data class StickInputs(
|
|||||||
val state: StickState,
|
val state: StickState,
|
||||||
/** The last day whose verdict was final, or null before the first run. */
|
/** The last day whose verdict was final, or null before the first run. */
|
||||||
val checkedThrough: LocalDate?,
|
val checkedThrough: LocalDate?,
|
||||||
|
/**
|
||||||
|
* Why the daily ring stood down on a day, latched by [AlarmReceiver] at
|
||||||
|
* ring time, or null when it rang (or the phone was off). Outlives a
|
||||||
|
* later clear of the mark: the ring was silenced, so no dismiss was
|
||||||
|
* possible, and a clear at 11:38 must not turn the day into a miss
|
||||||
|
* (2026-11-11).
|
||||||
|
*/
|
||||||
|
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. */
|
||||||
@ -53,14 +67,19 @@ 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, 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.
|
||||||
* Nothing here needs the ring to have *fired*: a phone switched off before
|
* Nothing here needs the ring to have *fired*: a phone switched off before
|
||||||
* the alarm misses exactly like one left ringing (hole 1 of the contract).
|
* the alarm misses exactly like one left ringing (hole 1 of the contract).
|
||||||
@ -76,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)
|
||||||
@ -87,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
|
||||||
@ -100,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. */
|
||||||
@ -116,19 +149,28 @@ 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.
|
||||||
if (inputs.isSick(day)) return StickVerdict.SICK_DAY to state
|
if (inputs.isSick(day)) return StickVerdict.SICK_DAY to state
|
||||||
|
when (inputs.ringSkippedOn(day)) {
|
||||||
|
RingSkip.FREE_DAY -> return StickVerdict.FREE_DAY to state
|
||||||
|
RingSkip.SICK_DAY -> return StickVerdict.SICK_DAY to state
|
||||||
|
null -> Unit
|
||||||
|
}
|
||||||
// A dismissed or escaped stick day breaks the chain: the streak
|
// A dismissed or escaped stick day breaks the chain: the streak
|
||||||
// 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -138,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -159,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
|
||||||
@ -173,6 +230,6 @@ object StickCheck {
|
|||||||
fun isStickDay(day: LocalDate): Boolean = day.dayOfWeek in WorkdayStick.STICK_DAYS
|
fun isStickDay(day: LocalDate): Boolean = day.dayOfWeek in WorkdayStick.STICK_DAYS
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A day the stick skips entirely: free or sick. */
|
/** A day the stick skips entirely: free or sick, now or at ring time. */
|
||||||
val StickInputs.standsDown: (LocalDate) -> Boolean
|
val StickInputs.standsDown: (LocalDate) -> Boolean
|
||||||
get() = { isFree(it) || isSick(it) }
|
get() = { isFree(it) || isSick(it) || ringSkippedOn(it) != 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 {
|
||||||
@ -35,6 +35,8 @@ object StickRunner {
|
|||||||
isSick = { SickDays.isSick(context, it) },
|
isSick = { SickDays.isSick(context, it) },
|
||||||
state = before,
|
state = before,
|
||||||
checkedThrough = StickStore.checkedThrough(context),
|
checkedThrough = StickStore.checkedThrough(context),
|
||||||
|
ringSkippedOn = { RingWatch.skippedOn(context, it) },
|
||||||
|
bypassOn = { RingWatch.bypassOn(context, it) },
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
for ((day, verdict) in run.verdicts) {
|
for ((day, verdict) in run.verdicts) {
|
||||||
@ -48,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
|
||||||
@ -69,7 +76,7 @@ object StickRunner {
|
|||||||
fun onDismissed(context: Context) {
|
fun onDismissed(context: Context) {
|
||||||
val today = LocalDate.now()
|
val today = LocalDate.now()
|
||||||
if (!StickCheck.isStickDay(today) || FreeDays.isFree(context, today) ||
|
if (!StickCheck.isStickDay(today) || FreeDays.isFree(context, today) ||
|
||||||
SickDays.isSick(context, today)
|
SickDays.isSick(context, today) || RingWatch.skippedOn(context, today) != null
|
||||||
) {
|
) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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))
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -20,6 +20,7 @@ class StickCheckSickTest {
|
|||||||
free: Set<LocalDate> = emptySet(),
|
free: Set<LocalDate> = emptySet(),
|
||||||
state: StickState = StickState(),
|
state: StickState = StickState(),
|
||||||
checkedThrough: LocalDate? = null,
|
checkedThrough: LocalDate? = null,
|
||||||
|
skipped: Map<LocalDate, RingSkip> = emptyMap(),
|
||||||
) = StickInputs(
|
) = StickInputs(
|
||||||
now = now,
|
now = now,
|
||||||
alarm = LocalTime.of(7, 30),
|
alarm = LocalTime.of(7, 30),
|
||||||
@ -29,6 +30,7 @@ class StickCheckSickTest {
|
|||||||
isSick = { it in sick },
|
isSick = { it in sick },
|
||||||
state = state,
|
state = state,
|
||||||
checkedThrough = checkedThrough,
|
checkedThrough = checkedThrough,
|
||||||
|
ringSkippedOn = { skipped[it] },
|
||||||
)
|
)
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -58,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)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -73,6 +75,40 @@ class StickCheckSickTest {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aSickMarkClearedAfterTheSkippedRingIsStillSick() {
|
||||||
|
// 2026-11-11: the ring stood down for a sick day at A, the mark was
|
||||||
|
// cleared at 11:38, and the 19:31 run must not call the day a miss.
|
||||||
|
val run = StickCheck.run(
|
||||||
|
inputs(wed.atTime(19, 31), skipped = mapOf(wed to RingSkip.SICK_DAY)),
|
||||||
|
)
|
||||||
|
assertEquals(StickVerdict.SICK_DAY, run.verdicts.single().verdict)
|
||||||
|
assertEquals(StickState(), run.state)
|
||||||
|
assertNull(run.signalUntil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aFreeMarkClearedAfterTheSkippedRingIsStillFree() {
|
||||||
|
val run = StickCheck.run(
|
||||||
|
inputs(wed.atTime(19, 31), skipped = mapOf(wed to RingSkip.FREE_DAY)),
|
||||||
|
)
|
||||||
|
assertEquals(StickVerdict.FREE_DAY, run.verdicts.single().verdict)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aSkippedRingDayIsSkippedWhenTheStreakLooksBack() {
|
||||||
|
val before = StickState(streak = 1, lockedThrough = wed, lastMiss = tue)
|
||||||
|
val run = StickCheck.run(
|
||||||
|
inputs(
|
||||||
|
thu.atTime(9, 0),
|
||||||
|
state = before,
|
||||||
|
checkedThrough = tue,
|
||||||
|
skipped = mapOf(wed to RingSkip.SICK_DAY),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertEquals(2, run.state.streak)
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun aFreeDayIsStillNamedFree() {
|
fun aFreeDayIsStillNamedFree() {
|
||||||
val run = StickCheck.run(inputs(wed.atTime(9, 0), free = setOf(wed)))
|
val run = StickCheck.run(inputs(wed.atTime(9, 0), free = setOf(wed)))
|
||||||
|
|||||||
@ -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
|
||||||
|
|||||||
@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
|
|||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
zipStorePath=wrapper/dists
|
zipStorePath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-all.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.2-all.zip
|
||||||
|
|||||||
@ -1,4 +1,9 @@
|
|||||||
import 'package:flutter/material.dart';
|
// Framework material, for its MaterialLocalizations delegate only: material_ui
|
||||||
|
// ships its own MaterialLocalizations type, so crdt_sync_flutter's dialogs
|
||||||
|
// (framework `showDialog`) found none and threw a null check.
|
||||||
|
// ignore: deprecated_member_use, the only source of the framework delegate.
|
||||||
|
import 'package:flutter/material.dart' as fw show DefaultMaterialLocalizations;
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
import 'package:wake_alarm_sync/screens/home_screen.dart';
|
import 'package:wake_alarm_sync/screens/home_screen.dart';
|
||||||
import 'package:wake_alarm_sync/screens/ring_screen.dart';
|
import 'package:wake_alarm_sync/screens/ring_screen.dart';
|
||||||
@ -6,7 +11,9 @@ 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/theme.dart';
|
import 'package:wake_alarm_sync/ui/theme.dart';
|
||||||
|
|
||||||
/// Route the Kotlin `AlarmActivity` hands to the engine as its initial
|
/// Route the Kotlin `AlarmActivity` hands to the engine as its initial
|
||||||
@ -39,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.
|
||||||
@ -63,9 +74,13 @@ class WakeAlarmSyncApp extends StatelessWidget {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return MaterialApp(
|
return MaterialApp(
|
||||||
title: 'Wake Alarm Sync',
|
title: kAppName,
|
||||||
theme: buildAppTheme(),
|
theme: buildAppTheme(),
|
||||||
navigatorKey: navigatorKey,
|
navigatorKey: navigatorKey,
|
||||||
|
localizationsDelegates: const <LocalizationsDelegate<dynamic>>[
|
||||||
|
fw.DefaultMaterialLocalizations.delegate,
|
||||||
|
DefaultWidgetsLocalizations.delegate,
|
||||||
|
],
|
||||||
// AlarmActivity sets its initial route to kRingRoute, so the ring screen
|
// AlarmActivity sets its initial route to kRingRoute, so the ring screen
|
||||||
// is what comes up over the lockscreen; the launcher still gets home.
|
// is what comes up over the lockscreen; the launcher still gets home.
|
||||||
routes: <String, WidgetBuilder>{
|
routes: <String, WidgetBuilder>{
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
import 'package:wake_alarm_sync/main.dart';
|
import 'package:wake_alarm_sync/main.dart';
|
||||||
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
import 'package:wake_alarm_sync/main.dart';
|
import 'package:wake_alarm_sync/main.dart';
|
||||||
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
||||||
|
|||||||
@ -1,7 +1,8 @@
|
|||||||
import 'package:flutter/material.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();
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
import 'package:wake_alarm_sync/screens/room_proof_screen.dart';
|
import 'package:wake_alarm_sync/screens/room_proof_screen.dart';
|
||||||
|
|
||||||
|
|||||||
@ -1,7 +1,8 @@
|
|||||||
|
// phone-slot: not-shared-storage (path is per-package: Android/data/<package>/files)
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:path/path.dart' as p;
|
import 'package:path/path.dart' as p;
|
||||||
import 'package:path_provider/path_provider.dart';
|
import 'package:path_provider/path_provider.dart';
|
||||||
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
||||||
|
|||||||
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();
|
||||||
|
}
|
||||||
@ -1,4 +1,4 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/screens/day_cell.dart';
|
import 'package:wake_alarm_sync/screens/day_cell.dart';
|
||||||
import 'package:wake_alarm_sync/services/alarm_ramp.dart';
|
import 'package:wake_alarm_sync/services/alarm_ramp.dart';
|
||||||
import 'package:wake_alarm_sync/services/free_day_pool.dart';
|
import 'package:wake_alarm_sync/services/free_day_pool.dart';
|
||||||
@ -74,15 +74,24 @@ class DayCalendar extends StatelessWidget {
|
|||||||
/// Latest month the forward arrow reaches; null means no limit.
|
/// Latest month the forward arrow reaches; null means no limit.
|
||||||
final DateTime? lastMonth;
|
final DateTime? lastMonth;
|
||||||
|
|
||||||
static const _labels = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
|
|
||||||
static const _months = [
|
|
||||||
'January', 'February', 'March', 'April', 'May', 'June', 'July', //
|
|
||||||
'August', 'September', 'October', 'November', 'December',
|
|
||||||
];
|
|
||||||
|
|
||||||
bool _before(DateTime a, DateTime b) =>
|
bool _before(DateTime a, DateTime b) =>
|
||||||
a.year < b.year || (a.year == b.year && a.month < b.month);
|
a.year < b.year || (a.year == b.year && a.month < b.month);
|
||||||
|
|
||||||
|
Widget _weekdayDot(BuildContext context, int index) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final isWeekend = index == 5 || index == 6;
|
||||||
|
return Container(
|
||||||
|
width: isWeekend ? 8 : 6,
|
||||||
|
height: isWeekend ? 8 : 6,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
shape: BoxShape.circle,
|
||||||
|
color: isWeekend
|
||||||
|
? theme.colorScheme.primary
|
||||||
|
: theme.colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
@ -97,22 +106,26 @@ class DayCalendar extends StatelessWidget {
|
|||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: const Icon(Icons.chevron_left),
|
icon: const Icon(
|
||||||
tooltip: 'Previous month',
|
Icons.chevron_left,
|
||||||
|
semanticLabel: 'Previous month',
|
||||||
|
),
|
||||||
onPressed: canBack
|
onPressed: canBack
|
||||||
? () => onMonth(DateTime(month.year, month.month - 1))
|
? () => onMonth(DateTime(month.year, month.month - 1))
|
||||||
: null,
|
: null,
|
||||||
),
|
),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Text(
|
child: Text(
|
||||||
'${_months[month.month - 1]} ${month.year}',
|
'${month.month.toString().padLeft(2, '0')}/${month.year}',
|
||||||
textAlign: TextAlign.center,
|
textAlign: TextAlign.center,
|
||||||
style: theme.textTheme.titleMedium,
|
style: theme.textTheme.titleMedium,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: const Icon(Icons.chevron_right),
|
icon: const Icon(
|
||||||
tooltip: 'Next month',
|
Icons.chevron_right,
|
||||||
|
semanticLabel: 'Next month',
|
||||||
|
),
|
||||||
onPressed: canForward
|
onPressed: canForward
|
||||||
? () => onMonth(DateTime(month.year, month.month + 1))
|
? () => onMonth(DateTime(month.year, month.month + 1))
|
||||||
: null,
|
: null,
|
||||||
@ -121,17 +134,8 @@ class DayCalendar extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
for (final label in _labels)
|
for (var i = 0; i < 7; i++)
|
||||||
Expanded(
|
Expanded(child: Center(child: _weekdayDot(context, i))),
|
||||||
child: Center(
|
|
||||||
child: Text(
|
|
||||||
label,
|
|
||||||
style: theme.textTheme.labelSmall?.copyWith(
|
|
||||||
color: theme.colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
Widget _dot(Color color) => Container(
|
Widget _dot(Color color) => Container(
|
||||||
key: const ValueKey<String>('day-badge'),
|
key: const ValueKey<String>('day-badge'),
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/services/weight_entry.dart';
|
import 'package:wake_alarm_sync/services/weight_entry.dart';
|
||||||
|
|
||||||
/// Five chips, 1 to 5: the morning's energy, tapped next to the weigh-in.
|
/// Five chips, 1 to 5: the morning's energy, tapped next to the weigh-in.
|
||||||
@ -28,7 +28,12 @@ class EnergyPicker extends StatelessWidget {
|
|||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
Text('Energy', style: Theme.of(context).textTheme.labelLarge),
|
const Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Icon(Icons.bolt, semanticLabel: 'Energy'),
|
||||||
|
SizedBox(width: 8),
|
||||||
|
],
|
||||||
|
),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
Row(
|
Row(
|
||||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/services/stakes.dart';
|
import 'package:wake_alarm_sync/services/stakes.dart';
|
||||||
|
|
||||||
/// Asks why this morning should be excused; the reason, or null if
|
/// Asks why this morning should be excused; the reason, or null if
|
||||||
@ -34,50 +34,67 @@ class _EscapeDialogState extends State<EscapeDialog> {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
final ready = _length >= escapeReasonMinChars;
|
final ready = _length >= escapeReasonMinChars;
|
||||||
|
const reasonWords = 'What went wrong?';
|
||||||
return AlertDialog(
|
return AlertDialog(
|
||||||
// The keyboard covers half a small screen; scroll instead of overflow.
|
// The keyboard covers half a small screen; scroll instead of overflow.
|
||||||
scrollable: true,
|
scrollable: true,
|
||||||
title: const Text('That was a bug'),
|
icon: const Icon(
|
||||||
|
Icons.bug_report_outlined,
|
||||||
|
semanticLabel: 'That was a bug',
|
||||||
|
),
|
||||||
content: Column(
|
content: Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
const Text(
|
MergeSemantics(
|
||||||
'Lifts the app lockdown, clears the streak, cancels today’s PC '
|
child: Semantics(
|
||||||
'penalty and stops a ringing PC. Every use is listed in the '
|
label: reasonWords,
|
||||||
'incident report.',
|
child: TextField(
|
||||||
),
|
controller: _reason,
|
||||||
const SizedBox(height: 16),
|
autofocus: true,
|
||||||
TextField(
|
maxLines: 4,
|
||||||
controller: _reason,
|
minLines: 2,
|
||||||
autofocus: true,
|
decoration: const InputDecoration(
|
||||||
maxLines: 4,
|
prefixIcon: Icon(Icons.edit_note),
|
||||||
minLines: 2,
|
border: OutlineInputBorder(),
|
||||||
decoration: const InputDecoration(
|
),
|
||||||
labelText: 'What went wrong?',
|
onChanged: (_) => setState(() {}),
|
||||||
border: OutlineInputBorder(),
|
),
|
||||||
),
|
),
|
||||||
onChanged: (_) => setState(() {}),
|
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Text(
|
Row(
|
||||||
'$_length / $escapeReasonMinChars characters',
|
children: <Widget>[
|
||||||
style: theme.textTheme.bodySmall?.copyWith(
|
Expanded(
|
||||||
color: theme.colorScheme.onSurfaceVariant,
|
child: LinearProgressIndicator(
|
||||||
),
|
value: (_length / escapeReasonMinChars)
|
||||||
|
.clamp(0, 1)
|
||||||
|
.toDouble(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Text(
|
||||||
|
'$_length/$escapeReasonMinChars',
|
||||||
|
style: theme.textTheme.bodySmall?.copyWith(
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
actions: <Widget>[
|
actions: <Widget>[
|
||||||
TextButton(
|
IconButton(
|
||||||
|
key: const Key('escape-cancel'),
|
||||||
onPressed: () => Navigator.of(context).pop(),
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
child: const Text('Cancel'),
|
icon: const Icon(Icons.close, semanticLabel: 'Cancel'),
|
||||||
),
|
),
|
||||||
FilledButton(
|
FilledButton(
|
||||||
|
key: const Key('escape-confirm'),
|
||||||
onPressed: ready
|
onPressed: ready
|
||||||
? () => Navigator.of(context).pop(_reason.text.trim())
|
? () => Navigator.of(context).pop(_reason.text.trim())
|
||||||
: null,
|
: null,
|
||||||
child: const Text('Excuse this morning'),
|
child: const Icon(Icons.check, semanticLabel: 'Excuse this morning'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|||||||
@ -1,7 +1,8 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/screens/day_calendar.dart';
|
import 'package:wake_alarm_sync/screens/day_calendar.dart';
|
||||||
import 'package:wake_alarm_sync/services/free_day_pool.dart';
|
import 'package:wake_alarm_sync/services/free_day_pool.dart';
|
||||||
import 'package:wake_alarm_sync/ui/theme.dart';
|
import 'package:wake_alarm_sync/ui/cues.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/dashed_slot.dart';
|
||||||
|
|
||||||
/// One upcoming free day, as the list shows it.
|
/// One upcoming free day, as the list shows it.
|
||||||
typedef UpcomingFreeDay = ({DateTime day, String reason});
|
typedef UpcomingFreeDay = ({DateTime day, String reason});
|
||||||
@ -45,70 +46,78 @@ class FreeDaysBody extends StatelessWidget {
|
|||||||
/// Called when the user gives a day back.
|
/// Called when the user gives a day back.
|
||||||
final void Function(DateTime day) onRelease;
|
final void Function(DateTime day) onRelease;
|
||||||
|
|
||||||
static const _weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
|
String _toDdMmYyyy(DateTime day) {
|
||||||
|
final d = day.day.toString().padLeft(2, '0');
|
||||||
String _label(DateTime day) =>
|
final m = day.month.toString().padLeft(2, '0');
|
||||||
'${_weekdays[day.weekday - 1]} ${FreeDayPool.toIso(day)}';
|
return '$d.$m.${day.year}';
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
final statusColors = theme.extension<AppStatusColors>()!;
|
|
||||||
return SafeArea(
|
return SafeArea(
|
||||||
child: ListView(
|
child: ListView(
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(16),
|
||||||
children: [
|
children: [
|
||||||
Text(
|
Row(
|
||||||
'$remaining of ${FreeDayPool.annualBudget}',
|
children: [
|
||||||
style: theme.textTheme.displayMedium?.copyWith(
|
const Icon(Icons.event_available),
|
||||||
fontWeight: FontWeight.bold,
|
const SizedBox(width: 8),
|
||||||
),
|
Text(
|
||||||
|
'$remaining/${FreeDayPool.annualBudget}',
|
||||||
|
style: theme.textTheme.displayMedium?.copyWith(
|
||||||
|
fontWeight: FontWeight.bold,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
Text(
|
Text(
|
||||||
'free days left in $year',
|
'$year',
|
||||||
style: theme.textTheme.bodyMedium?.copyWith(
|
style: theme.textTheme.bodyMedium?.copyWith(
|
||||||
color: theme.colorScheme.onSurfaceVariant,
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Text(
|
|
||||||
'On a free day nothing locks, nothing rings and nothing asks. '
|
|
||||||
'Every app, at once.',
|
|
||||||
style: theme.textTheme.bodySmall?.copyWith(
|
|
||||||
color: theme.colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (status.isNotEmpty) ...[
|
if (status.isNotEmpty) ...[
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Text(
|
StatusCue(semanticLabel: status),
|
||||||
status,
|
|
||||||
maxLines: 4,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
style: TextStyle(
|
|
||||||
color: status.contains('Error')
|
|
||||||
? theme.colorScheme.error
|
|
||||||
: statusColors.success,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
calendar,
|
calendar,
|
||||||
const SizedBox(height: 24),
|
const SizedBox(height: 24),
|
||||||
Text('Booked ahead', style: theme.textTheme.titleMedium),
|
Row(
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.upcoming,
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
semanticLabel: 'Booked ahead',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
if (upcoming.isEmpty)
|
if (upcoming.isEmpty)
|
||||||
Text(
|
const SpokenLabel(
|
||||||
'None. Tap a date above to book one.',
|
semanticLabel: 'None. Tap a date above to book one.',
|
||||||
style: TextStyle(color: theme.colorScheme.onSurfaceVariant),
|
child: DashedSlot(),
|
||||||
),
|
),
|
||||||
for (final entry in upcoming)
|
for (final entry in upcoming)
|
||||||
ListTile(
|
ListTile(
|
||||||
contentPadding: EdgeInsets.zero,
|
contentPadding: EdgeInsets.zero,
|
||||||
title: Text(_label(entry.day)),
|
title: Text(_toDdMmYyyy(entry.day)),
|
||||||
subtitle: entry.reason.isEmpty ? null : Text(entry.reason),
|
subtitle: entry.reason.isEmpty
|
||||||
trailing: TextButton(
|
? null
|
||||||
|
: KeyedSubtree(
|
||||||
|
key: ValueKey<String>(
|
||||||
|
'content:reason-${FreeDayPool.toIso(entry.day)}',
|
||||||
|
),
|
||||||
|
child: Text(entry.reason),
|
||||||
|
),
|
||||||
|
trailing: IconButton(
|
||||||
|
key: ValueKey<String>(
|
||||||
|
'release-${FreeDayPool.toIso(entry.day)}',
|
||||||
|
),
|
||||||
|
icon: const Icon(Icons.event_busy, semanticLabel: 'Release'),
|
||||||
onPressed: busy ? null : () => onRelease(entry.day),
|
onPressed: busy ? null : () => onRelease(entry.day),
|
||||||
child: const Text('Release'),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
|||||||
@ -1,12 +1,13 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/screens/day_calendar.dart';
|
import 'package:wake_alarm_sync/screens/day_calendar.dart';
|
||||||
import 'package:wake_alarm_sync/screens/free_days_body.dart';
|
import 'package:wake_alarm_sync/screens/free_days_body.dart';
|
||||||
import 'package:wake_alarm_sync/services/free_day_pool.dart';
|
import 'package:wake_alarm_sync/services/free_day_pool.dart';
|
||||||
import 'package:wake_alarm_sync/services/free_day_sync.dart';
|
import 'package:wake_alarm_sync/services/free_day_sync.dart';
|
||||||
import 'package:wake_alarm_sync/services/sick_day_pool.dart';
|
import 'package:wake_alarm_sync/services/sick_day_pool.dart';
|
||||||
import 'package:wake_alarm_sync/services/sick_day_sync.dart';
|
import 'package:wake_alarm_sync/services/sick_day_sync.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/cues.dart';
|
||||||
|
|
||||||
/// The one picker for the shared free-day pool.
|
/// The one picker for the shared free-day pool.
|
||||||
///
|
///
|
||||||
@ -173,17 +174,23 @@ class _FreeDaysScreenState extends State<FreeDaysScreen> {
|
|||||||
final pool = _pool;
|
final pool = _pool;
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: const Text('Free days'),
|
// title removed
|
||||||
actions: [
|
actions: [
|
||||||
IconButton(
|
Tooltip(
|
||||||
icon: const Icon(Icons.sync),
|
message: 'Sync',
|
||||||
tooltip: 'Sync now',
|
child: IconButton(
|
||||||
onPressed: _busy ? null : () => unawaited(_sync()),
|
icon: const Icon(Icons.sync, semanticLabel: 'Sync now'),
|
||||||
|
onPressed: _busy ? null : () => unawaited(_sync()),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
body: pool == null
|
body: pool == null
|
||||||
? Center(child: Text(_status.isEmpty ? 'Loading…' : _status))
|
? Center(
|
||||||
|
child: _status.isEmpty
|
||||||
|
? const CircularProgressIndicator()
|
||||||
|
: StatusCue(semanticLabel: _status),
|
||||||
|
)
|
||||||
: FreeDaysBody(
|
: FreeDaysBody(
|
||||||
year: _today.year,
|
year: _today.year,
|
||||||
remaining: pool.remaining(_today.year),
|
remaining: pool.remaining(_today.year),
|
||||||
|
|||||||
@ -1,8 +1,9 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:github_device_auth/github_device_auth.dart';
|
import 'package:github_device_auth/github_device_auth.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/services/sync_settings.dart';
|
import 'package:wake_alarm_sync/services/sync_settings.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/cues.dart';
|
||||||
|
|
||||||
/// The GitHub mirror screen: cutover-only sync transport, not a peer of
|
/// The GitHub mirror screen: cutover-only sync transport, not a peer of
|
||||||
/// Firebase.
|
/// Firebase.
|
||||||
@ -86,62 +87,53 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final isConnected = _settings.isConfigured;
|
final isConnected = _settings.isConfigured;
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(title: const Text('Advanced sync (GitHub)')),
|
appBar: AppBar(),
|
||||||
body: SafeArea(
|
body: SafeArea(
|
||||||
child: SingleChildScrollView(
|
child: SingleChildScrollView(
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(16),
|
||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
Align(
|
Tooltip(
|
||||||
alignment: Alignment.centerLeft,
|
message: isConnected ? 'Connected' : 'Disconnected',
|
||||||
child: Text(
|
child: Icon(
|
||||||
isConnected
|
isConnected ? Icons.link : Icons.link_off,
|
||||||
|
color: isConnected
|
||||||
|
? Theme.of(context).colorScheme.tertiary
|
||||||
|
: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
size: 32,
|
||||||
|
semanticLabel: isConnected
|
||||||
? 'Connected to GitHub.'
|
? 'Connected to GitHub.'
|
||||||
: 'Not connected to GitHub.',
|
: 'Not connected to GitHub.',
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 16,
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
if (!isConnected)
|
if (!isConnected)
|
||||||
ElevatedButton.icon(
|
Tooltip(
|
||||||
onPressed: _busy ? null : _connectGitHub,
|
message: 'Connect',
|
||||||
icon: const Icon(Icons.link),
|
child: ElevatedButton(
|
||||||
label: const Text('Connect GitHub'),
|
key: const ValueKey<String>('github-connect'),
|
||||||
|
onPressed: _busy ? null : _connectGitHub,
|
||||||
|
child: const Icon(
|
||||||
|
Icons.link,
|
||||||
|
semanticLabel: 'Connect GitHub',
|
||||||
|
),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
else
|
else
|
||||||
OutlinedButton.icon(
|
Tooltip(
|
||||||
onPressed: _busy ? null : _disconnect,
|
message: 'Disconnect',
|
||||||
icon: const Icon(Icons.link_off),
|
child: OutlinedButton(
|
||||||
label: const Text('Disconnect GitHub'),
|
key: const ValueKey<String>('github-disconnect'),
|
||||||
),
|
onPressed: _busy ? null : _disconnect,
|
||||||
const SizedBox(height: 16),
|
child: const Icon(
|
||||||
Text(
|
Icons.link_off,
|
||||||
'PC config — the PC reads Firebase first and falls back '
|
semanticLabel: 'Disconnect GitHub',
|
||||||
'to GitHub. For the GitHub fallback, create:\n'
|
),
|
||||||
'~/.config/wake_alarm/sync.json\n\n'
|
|
||||||
'{ "token": "<same token>" }\n\n'
|
|
||||||
'The token needs "repo" scope so the PC can read '
|
|
||||||
'kuhyx/syncs.',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 16,
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (_status.isNotEmpty) ...[
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
Text(
|
|
||||||
_status,
|
|
||||||
style: TextStyle(
|
|
||||||
color: _status.startsWith('Error')
|
|
||||||
? Theme.of(context).colorScheme.error
|
|
||||||
: null,
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
const SizedBox(height: 16),
|
||||||
|
StatusCue(semanticLabel: _status),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/screens/home_history_card.dart';
|
|
||||||
import 'package:wake_alarm_sync/screens/home_presence_line.dart';
|
import 'package:wake_alarm_sync/screens/home_presence_line.dart';
|
||||||
import 'package:wake_alarm_sync/screens/stakes_card.dart';
|
import 'package:wake_alarm_sync/screens/home_tiles.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/cues.dart';
|
||||||
import 'package:wake_alarm_sync/ui/theme.dart';
|
import 'package:wake_alarm_sync/ui/theme.dart';
|
||||||
|
|
||||||
/// The home screen's body: the armed time, the earlier-only control and the
|
/// The home screen's body: the armed time, the earlier-only control and the
|
||||||
@ -54,92 +54,113 @@ class HomeBody extends StatelessWidget {
|
|||||||
/// Called after the escape hatch was used, so the screen publishes it.
|
/// Called after the escape hatch was used, so the screen publishes it.
|
||||||
final VoidCallback? onEscaped;
|
final VoidCallback? onEscaped;
|
||||||
|
|
||||||
|
IconData? _statusIcon(String status) {
|
||||||
|
if (status.startsWith('Connect a sync backend')) return Icons.cloud_off;
|
||||||
|
if (status.startsWith('Sync store unavailable')) return Icons.sync_problem;
|
||||||
|
if (status.contains('✓')) return Icons.cloud_done;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
return SafeArea(
|
return SafeArea(
|
||||||
child: Center(
|
// Fits one screen: stakes and history sit behind tiles. The scroll view
|
||||||
child: SingleChildScrollView(
|
// is only the landscape safety net (~360px of body height); in portrait
|
||||||
padding: const EdgeInsets.all(32),
|
// its extent is 0, which `home_fit_test.dart` asserts.
|
||||||
child: Column(
|
child: LayoutBuilder(
|
||||||
mainAxisSize: MainAxisSize.min,
|
builder: (context, box) => SingleChildScrollView(
|
||||||
children: [
|
padding: const EdgeInsets.all(24),
|
||||||
const Text('Alarm is armed for', style: TextStyle(fontSize: 16)),
|
child: ConstrainedBox(
|
||||||
HomePresenceLine(key: ValueKey<int>(syncEpoch)),
|
constraints: BoxConstraints(minHeight: box.maxHeight - 48),
|
||||||
const SizedBox(height: 16),
|
child: Center(
|
||||||
Text(
|
child: Column(
|
||||||
time,
|
mainAxisSize: MainAxisSize.min,
|
||||||
style: Theme.of(
|
children: [
|
||||||
context,
|
Tooltip(
|
||||||
).textTheme.displayLarge?.copyWith(fontWeight: FontWeight.bold),
|
message: 'Armed',
|
||||||
),
|
child: Icon(
|
||||||
const SizedBox(height: 8),
|
Icons.alarm_on,
|
||||||
Text(
|
size: 32,
|
||||||
isOverridden
|
color: theme.colorScheme.primary,
|
||||||
? 'One-shot early start — back to $baseline '
|
semanticLabel: 'Alarm is armed for',
|
||||||
'after it rings'
|
),
|
||||||
: 'Every day. It cannot be turned off.',
|
|
||||||
textAlign: TextAlign.center,
|
|
||||||
style: const TextStyle(fontSize: 13),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 32),
|
|
||||||
SizedBox(
|
|
||||||
width: double.infinity,
|
|
||||||
child: OutlinedButton.icon(
|
|
||||||
onPressed: busy ? null : onPickEarlier,
|
|
||||||
icon: const Icon(Icons.arrow_upward),
|
|
||||||
label: const Text('Wake me earlier tomorrow'),
|
|
||||||
style: OutlinedButton.styleFrom(
|
|
||||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
|
||||||
),
|
),
|
||||||
),
|
HomePresenceLine(key: ValueKey<int>(syncEpoch)),
|
||||||
),
|
const SizedBox(height: 16),
|
||||||
const SizedBox(height: 24),
|
Text(
|
||||||
if (status.isNotEmpty)
|
time,
|
||||||
Text(
|
style: theme.textTheme.displayLarge?.copyWith(
|
||||||
status,
|
fontWeight: FontWeight.bold,
|
||||||
textAlign: TextAlign.center,
|
),
|
||||||
// Bounded: status can be a raw `'Error: $e'`, i.e. an
|
|
||||||
// arbitrarily long exception toString(). Unbounded, that
|
|
||||||
// alone added 100-150px and pushed this column past the
|
|
||||||
// viewport even in portrait. The scroll view above makes
|
|
||||||
// the overflow recoverable; this keeps it from happening.
|
|
||||||
maxLines: 4,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
style: TextStyle(
|
|
||||||
color: status.contains('Error')
|
|
||||||
? Theme.of(context).colorScheme.error
|
|
||||||
: Theme.of(
|
|
||||||
context,
|
|
||||||
).extension<AppStatusColors>()!.success,
|
|
||||||
),
|
),
|
||||||
),
|
const SizedBox(height: 8),
|
||||||
const SizedBox(height: 24),
|
if (isOverridden)
|
||||||
// A third distinct key in this Column, for the same reason as
|
Row(
|
||||||
// the history card's below.
|
mainAxisSize: MainAxisSize.min,
|
||||||
StakesCard(
|
children: [
|
||||||
key: ValueKey<String>('stakes-$syncEpoch'),
|
Tooltip(
|
||||||
busy: busy,
|
message: 'Oneshot',
|
||||||
onEscaped: onEscaped,
|
child: Icon(
|
||||||
),
|
Icons.restore,
|
||||||
const SizedBox(height: 24),
|
size: 18,
|
||||||
// Not `ValueKey<int>(syncEpoch)`: the presence line above
|
semanticLabel:
|
||||||
// already carries that key in this Column, and two children
|
'One-shot early start, back to $baseline '
|
||||||
// with one key mis-reconcile silently in release -- the old
|
'after it rings',
|
||||||
// presence element was painted here.
|
),
|
||||||
HomeHistoryCard(key: ValueKey<String>('history-$syncEpoch')),
|
),
|
||||||
if (!configured) ...[
|
Text(baseline),
|
||||||
const SizedBox(height: 16),
|
],
|
||||||
Text(
|
)
|
||||||
'Open Settings (gear icon) to connect Firebase.',
|
else
|
||||||
textAlign: TextAlign.center,
|
Tooltip(
|
||||||
style: TextStyle(
|
message: 'Daily',
|
||||||
color: Theme.of(
|
child: Icon(
|
||||||
context,
|
Icons.all_inclusive,
|
||||||
).extension<AppStatusColors>()!.warning,
|
size: 18,
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
semanticLabel: 'Every day. It cannot be turned off.',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 32),
|
||||||
|
SizedBox(
|
||||||
|
width: double.infinity,
|
||||||
|
child: OutlinedButton(
|
||||||
|
onPressed: busy ? null : onPickEarlier,
|
||||||
|
style: OutlinedButton.styleFrom(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||||
|
),
|
||||||
|
child: const Icon(
|
||||||
|
Icons.arrow_upward,
|
||||||
|
semanticLabel: 'Wake me earlier tomorrow',
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
const SizedBox(height: 24),
|
||||||
],
|
if (status.isNotEmpty) ...[
|
||||||
],
|
StatusCue(semanticLabel: status, icon: _statusIcon(status)),
|
||||||
|
const SizedBox(height: 24),
|
||||||
|
],
|
||||||
|
HomeTiles(
|
||||||
|
syncEpoch: syncEpoch,
|
||||||
|
busy: busy,
|
||||||
|
onEscaped: onEscaped,
|
||||||
|
),
|
||||||
|
if (!configured) ...[
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
Tooltip(
|
||||||
|
message: 'Offline',
|
||||||
|
child: Icon(
|
||||||
|
Icons.cloud_off,
|
||||||
|
size: 28,
|
||||||
|
color: theme.extension<AppStatusColors>()!.warning,
|
||||||
|
semanticLabel: 'Open Settings to connect Firebase',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@ -1,9 +1,12 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.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_store.dart';
|
import 'package:wake_alarm_sync/services/session_store.dart';
|
||||||
import 'package:wake_alarm_sync/services/weight_entry.dart';
|
import 'package:wake_alarm_sync/services/weight_entry.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/dashed_slot.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/spoken_label.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/theme.dart';
|
||||||
|
|
||||||
/// How many mornings the home screen shows.
|
/// How many mornings the home screen shows.
|
||||||
const int kHistoryShown = 7;
|
const int kHistoryShown = 7;
|
||||||
@ -15,17 +18,23 @@ const int kHistoryShown = 7;
|
|||||||
/// first session has finished — an empty card would only say "not yet".
|
/// first session has finished — an empty card would only say "not yet".
|
||||||
class HomeHistoryCard extends StatefulWidget {
|
class HomeHistoryCard extends StatefulWidget {
|
||||||
/// Creates the card; [store] is injectable for tests.
|
/// Creates the card; [store] is injectable for tests.
|
||||||
const HomeHistoryCard({super.key, this.store});
|
const HomeHistoryCard({super.key, this.store, this.emptyText});
|
||||||
|
|
||||||
/// Session persistence; defaults to SharedPreferences.
|
/// Session persistence; defaults to SharedPreferences.
|
||||||
final SessionStore? store;
|
final SessionStore? store;
|
||||||
|
|
||||||
|
/// Shown once loading found no finished morning, instead of nothing. The
|
||||||
|
/// home screen opens this card from a tile, so a blank sheet needs a
|
||||||
|
/// sentence.
|
||||||
|
final String? emptyText;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<HomeHistoryCard> createState() => _HomeHistoryCardState();
|
State<HomeHistoryCard> createState() => _HomeHistoryCardState();
|
||||||
}
|
}
|
||||||
|
|
||||||
class _HomeHistoryCardState extends State<HomeHistoryCard> {
|
class _HomeHistoryCardState extends State<HomeHistoryCard> {
|
||||||
List<MorningSession> _sessions = const <MorningSession>[];
|
List<MorningSession> _sessions = const <MorningSession>[];
|
||||||
|
bool _loaded = false;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
@ -36,24 +45,30 @@ class _HomeHistoryCardState extends State<HomeHistoryCard> {
|
|||||||
Future<void> _load() async {
|
Future<void> _load() async {
|
||||||
final history = await (widget.store ?? SessionStore()).history();
|
final history = await (widget.store ?? SessionStore()).history();
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _sessions = history.take(kHistoryShown).toList());
|
setState(() {
|
||||||
|
_sessions = history.take(kHistoryShown).toList();
|
||||||
|
_loaded = true;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
if (_sessions.isEmpty) return const SizedBox.shrink();
|
if (_sessions.isEmpty) {
|
||||||
final theme = Theme.of(context);
|
final empty = widget.emptyText;
|
||||||
|
return _loaded && empty != null
|
||||||
|
? SpokenLabel(semanticLabel: empty, child: const DashedSlot())
|
||||||
|
: const SizedBox.shrink();
|
||||||
|
}
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
Text('Last mornings', style: theme.textTheme.titleMedium),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
for (var i = 0; i < _sessions.length; i++)
|
for (var i = 0; i < _sessions.length; i++)
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.symmetric(vertical: 2),
|
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||||
child: Text(
|
child: _MorningRow(
|
||||||
describeMorning(_sessions[i], previousWeight: _previousWeight(i)),
|
key: ValueKey<String>('history-${_sessions[i].date}'),
|
||||||
style: theme.textTheme.bodyMedium,
|
session: _sessions[i],
|
||||||
|
previousWeight: _previousWeight(i),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@ -70,6 +85,67 @@ class _HomeHistoryCardState extends State<HomeHistoryCard> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One morning as glyphs and numbers; [describeMorning] is its spoken form.
|
||||||
|
class _MorningRow extends StatelessWidget {
|
||||||
|
const _MorningRow({
|
||||||
|
required this.session,
|
||||||
|
required this.previousWeight,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
final MorningSession session;
|
||||||
|
final double? previousWeight;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final status = theme.extension<AppStatusColors>();
|
||||||
|
final muted = theme.colorScheme.onSurfaceVariant;
|
||||||
|
final (IconData outcome, Color colour) = switch (session.outcome) {
|
||||||
|
SessionOutcome.completed => (
|
||||||
|
Icons.check_circle,
|
||||||
|
status?.success ?? Colors.green,
|
||||||
|
),
|
||||||
|
SessionOutcome.failed => (Icons.cancel, theme.colorScheme.error),
|
||||||
|
SessionOutcome.active => (Icons.more_horiz, muted),
|
||||||
|
};
|
||||||
|
final kg = session.weightKg;
|
||||||
|
final previous = previousWeight;
|
||||||
|
final energy = session.energy;
|
||||||
|
return SpokenLabel(
|
||||||
|
semanticLabel: describeMorning(session, previousWeight: previous),
|
||||||
|
// Wrap, not Row: a long weight delta must not overflow a narrow sheet.
|
||||||
|
child: Wrap(
|
||||||
|
crossAxisAlignment: WrapCrossAlignment.center,
|
||||||
|
children: <Widget>[
|
||||||
|
Text(session.date.substring(5)),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Icon(outcome, color: colour, size: 20),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Icon(Icons.replay, size: 16, color: muted),
|
||||||
|
Text('${session.reRings}'),
|
||||||
|
if (kg != null) ...<Widget>[
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Icon(Icons.monitor_weight_outlined, size: 16, color: muted),
|
||||||
|
Text('$kg'),
|
||||||
|
if (previous != null) Text(' (${_signed(kg - previous)})'),
|
||||||
|
],
|
||||||
|
if (energy != null) ...<Widget>[
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Icon(Icons.bolt, size: 16, color: muted),
|
||||||
|
Text('$energy/$maxEnergy'),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String _signed(double delta) {
|
||||||
|
final sign = delta > 0 ? '+' : (delta < 0 ? '−' : '±');
|
||||||
|
return '$sign${delta.abs().toStringAsFixed(1)}';
|
||||||
|
}
|
||||||
|
|
||||||
/// One line for [session]: `09-16 ✓ 0 re-rings · 72.4 kg (−0.3) · energy 3/5`.
|
/// One line for [session]: `09-16 ✓ 0 re-rings · 72.4 kg (−0.3) · energy 3/5`.
|
||||||
String describeMorning(MorningSession session, {double? previousWeight}) {
|
String describeMorning(MorningSession session, {double? previousWeight}) {
|
||||||
final mark = switch (session.outcome) {
|
final mark = switch (session.outcome) {
|
||||||
@ -83,9 +159,7 @@ String describeMorning(MorningSession session, {double? previousWeight}) {
|
|||||||
if (kg != null) {
|
if (kg != null) {
|
||||||
weight = ' · $kg kg';
|
weight = ' · $kg kg';
|
||||||
if (previousWeight != null) {
|
if (previousWeight != null) {
|
||||||
final delta = kg - previousWeight;
|
weight += ' (${_signed(kg - previousWeight)})';
|
||||||
final sign = delta > 0 ? '+' : (delta < 0 ? '−' : '±');
|
|
||||||
weight += ' ($sign${delta.abs().toStringAsFixed(1)})';
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
final energy = session.energy == null
|
final energy = session.energy == null
|
||||||
|
|||||||
@ -1,8 +1,10 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.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/home_location_settings.dart';
|
import 'package:wake_alarm_sync/services/home_location_settings.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/cues.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/dashed_slot.dart';
|
||||||
|
|
||||||
/// Registers the Wi-Fi and coordinate that mean "home".
|
/// Registers the Wi-Fi and coordinate that mean "home".
|
||||||
///
|
///
|
||||||
@ -111,53 +113,95 @@ class _HomeLocationScreenState extends State<HomeLocationScreen> {
|
|||||||
_ => 'Nothing readable here.',
|
_ => 'Nothing readable here.',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
Widget _valueRow(IconData icon, String semanticLabel, Widget value) {
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 12),
|
||||||
|
child: Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
Icon(icon, semanticLabel: semanticLabel, size: 24),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Expanded(child: value),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(title: const Text('Home location')),
|
appBar: AppBar(),
|
||||||
body: ListView(
|
body: ListView(
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(16),
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
Text(
|
_valueRow(
|
||||||
'Away from home the two NFC tags are unreachable, so they are '
|
Icons.wifi,
|
||||||
'skipped and the alarm asks the usual questions instead. The '
|
'Home Wi-Fi',
|
||||||
'walk is always required.',
|
KeyedSubtree(
|
||||||
style: theme.textTheme.bodyMedium,
|
key: const ValueKey<String>('content:home-ssid'),
|
||||||
|
child: _home.ssid != null
|
||||||
|
? Text(_home.ssid!)
|
||||||
|
: const DashedSlot(),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 20),
|
_valueRow(
|
||||||
Text('Home Wi-Fi', style: theme.textTheme.titleMedium),
|
Icons.router,
|
||||||
Text(_home.ssid ?? 'not captured'),
|
'Access points',
|
||||||
const SizedBox(height: 12),
|
KeyedSubtree(
|
||||||
Text('Access points', style: theme.textTheme.titleMedium),
|
key: const ValueKey<String>('content:home-bssids'),
|
||||||
Text(_home.bssids.isEmpty ? 'none' : _home.bssids.join('\n')),
|
child: _home.bssids.isEmpty
|
||||||
const SizedBox(height: 12),
|
? const DashedSlot()
|
||||||
Text('Coordinate', style: theme.textTheme.titleMedium),
|
: Text(_home.bssids.join('\n')),
|
||||||
Text(
|
),
|
||||||
_home.hasCoordinate
|
),
|
||||||
? '${_home.lat!.toStringAsFixed(5)}, '
|
_valueRow(
|
||||||
|
Icons.place,
|
||||||
|
'Coordinate',
|
||||||
|
KeyedSubtree(
|
||||||
|
key: const ValueKey<String>('content:home-coord'),
|
||||||
|
child: _home.hasCoordinate
|
||||||
|
? Text(
|
||||||
|
'${_home.lat!.toStringAsFixed(5)}, '
|
||||||
'${_home.lon!.toStringAsFixed(5)} '
|
'${_home.lon!.toStringAsFixed(5)} '
|
||||||
'(±${_home.radiusMeters.round()} m)'
|
'(±${_home.radiusMeters.round()} m)',
|
||||||
: 'not captured',
|
)
|
||||||
|
: const DashedSlot(),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 24),
|
const SizedBox(height: 24),
|
||||||
FilledButton(
|
Row(
|
||||||
onPressed: _busy ? null : _capture,
|
children: <Widget>[
|
||||||
child: const Text('Capture this place as home'),
|
FilledButton(
|
||||||
),
|
onPressed: _busy ? null : _capture,
|
||||||
const SizedBox(height: 8),
|
child: const Icon(
|
||||||
Text(
|
Icons.my_location,
|
||||||
'Press once on each Wi-Fi band (2.4 GHz and 5 GHz) so a band '
|
semanticLabel: 'Capture this place as home',
|
||||||
'switch overnight is not mistaken for travelling.',
|
),
|
||||||
style: theme.textTheme.bodySmall,
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Icon(
|
||||||
|
Icons.network_wifi_2_bar,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
semanticLabel: 'Press once on each Wi-Fi band, 2.4 and 5 GHz',
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Icon(
|
||||||
|
Icons.network_wifi,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
semanticLabel: 'Press once on each Wi-Fi band, 2.4 and 5 GHz',
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: _home.isConfigured ? _clear : null,
|
onPressed: _home.isConfigured ? _clear : null,
|
||||||
child: const Text('Forget home'),
|
child: const Icon(
|
||||||
|
Icons.delete_outline,
|
||||||
|
semanticLabel: 'Forget home',
|
||||||
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Text(_status, style: theme.textTheme.bodyMedium),
|
StatusCue(semanticLabel: _status),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@ -1,7 +1,8 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/services/home_presence.dart';
|
import 'package:wake_alarm_sync/services/home_presence.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/cues.dart';
|
||||||
|
|
||||||
/// One line saying what tonight's alarm will demand, and why.
|
/// One line saying what tonight's alarm will demand, and why.
|
||||||
///
|
///
|
||||||
@ -52,14 +53,26 @@ class _HomePresenceLineState extends State<HomePresenceLine> {
|
|||||||
final verdict = _verdict;
|
final verdict = _verdict;
|
||||||
if (verdict == null) return const SizedBox.shrink();
|
if (verdict == null) return const SizedBox.shrink();
|
||||||
final atHome = verdict.state == PresenceState.home;
|
final atHome = verdict.state == PresenceState.home;
|
||||||
|
final theme = Theme.of(context);
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.only(top: 12),
|
padding: const EdgeInsets.only(top: 12),
|
||||||
child: Text(
|
child: SpokenLabel(
|
||||||
atHome
|
semanticLabel: atHome
|
||||||
? 'Tonight: tags required — ${verdict.detail}'
|
? 'Tonight: tags required — ${verdict.detail}'
|
||||||
: 'Tonight: tags skipped — ${verdict.detail}',
|
: 'Tonight: tags skipped — ${verdict.detail}',
|
||||||
textAlign: TextAlign.center,
|
child: Row(
|
||||||
style: Theme.of(context).textTheme.bodySmall,
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
atHome ? Icons.nfc : Icons.directions_walk,
|
||||||
|
size: 18,
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Icon(atHome ? Icons.home : Icons.explore, size: 18),
|
||||||
|
],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +1,8 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'dart:developer' as developer;
|
import 'dart:developer' as developer;
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
import 'package:wake_alarm_sync/screens/free_days_screen.dart';
|
import 'package:wake_alarm_sync/screens/free_days_screen.dart';
|
||||||
import 'package:wake_alarm_sync/screens/home_body.dart';
|
import 'package:wake_alarm_sync/screens/home_body.dart';
|
||||||
@ -14,6 +15,7 @@ import 'package:wake_alarm_sync/services/alarm_sync_service.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/firebase_backend.dart';
|
import 'package:wake_alarm_sync/services/firebase_backend.dart';
|
||||||
import 'package:wake_alarm_sync/services/sync_settings.dart';
|
import 'package:wake_alarm_sync/services/sync_settings.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/motion_route.dart';
|
||||||
|
|
||||||
/// Main screen: displays the current alarm time and syncs it to the PC via
|
/// Main screen: displays the current alarm time and syncs it to the PC via
|
||||||
/// the shared crdt_sync transport.
|
/// the shared crdt_sync transport.
|
||||||
@ -114,12 +116,15 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
final picked = await showTimePicker(
|
final picked = await showTimePicker(
|
||||||
context: context,
|
context: context,
|
||||||
initialTime: TimeOfDay(hour: _hour, minute: _minute),
|
initialTime: TimeOfDay(hour: _hour, minute: _minute),
|
||||||
helpText: 'Earlier than $current only',
|
helpText: '',
|
||||||
);
|
);
|
||||||
if (picked == null) return;
|
if (picked == null) return;
|
||||||
|
// The tap that sets the alarm: felt now, before any await or intent.
|
||||||
|
unawaited(HapticFeedback.mediumImpact());
|
||||||
final accepted = await AlarmPolicy.setEarlier(picked.hour, picked.minute);
|
final accepted = await AlarmPolicy.setEarlier(picked.hour, picked.minute);
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
if (!accepted) {
|
if (!accepted) {
|
||||||
|
unawaited(HapticFeedback.heavyImpact());
|
||||||
setState(
|
setState(
|
||||||
() => _status =
|
() => _status =
|
||||||
'That is not earlier than $current. The alarm can only be '
|
'That is not earlier than $current. The alarm can only be '
|
||||||
@ -171,28 +176,29 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: const Text('Wake Alarm Sync'),
|
|
||||||
actions: [
|
actions: [
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: Icon(
|
icon: Icon(
|
||||||
Icons.event_available,
|
Icons.event_available,
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
semanticLabel: 'Free days',
|
||||||
),
|
),
|
||||||
tooltip: 'Free days',
|
tooltip: 'Free-days',
|
||||||
onPressed: () => Navigator.push<void>(
|
onPressed: () => Navigator.push<void>(
|
||||||
context,
|
context,
|
||||||
MaterialPageRoute<void>(builder: (_) => const FreeDaysScreen()),
|
appRoute<void>(context, (_) => const FreeDaysScreen()),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: Icon(
|
icon: Icon(
|
||||||
Icons.sick_outlined,
|
Icons.sick_outlined,
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
semanticLabel: 'Sick days',
|
||||||
),
|
),
|
||||||
tooltip: 'Sick days',
|
tooltip: 'Sick-days',
|
||||||
onPressed: () => Navigator.push<void>(
|
onPressed: () => Navigator.push<void>(
|
||||||
context,
|
context,
|
||||||
MaterialPageRoute<void>(builder: (_) => const SickDaysScreen()),
|
appRoute<void>(context, (_) => const SickDaysScreen()),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
@ -200,12 +206,14 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
Icons.settings,
|
Icons.settings,
|
||||||
// Dimmed relative to the adjacent title text (rule 28).
|
// Dimmed relative to the adjacent title text (rule 28).
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
semanticLabel: 'Settings',
|
||||||
),
|
),
|
||||||
onPressed: () async {
|
onPressed: () async {
|
||||||
await Navigator.push<void>(
|
await Navigator.push<void>(
|
||||||
context,
|
context,
|
||||||
MaterialPageRoute<void>(
|
appRoute<void>(
|
||||||
builder: (_) => SettingsScreen(alarmService: _service),
|
context,
|
||||||
|
(_) => SettingsScreen(alarmService: _service),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
// Publish too, not just reload: a tag registered in Settings
|
// Publish too, not just reload: a tag registered in Settings
|
||||||
|
|||||||
106
phone_app/lib/screens/home_tiles.dart
Normal file
106
phone_app/lib/screens/home_tiles.dart
Normal file
@ -0,0 +1,106 @@
|
|||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
import 'package:wake_alarm_sync/screens/home_history_card.dart';
|
||||||
|
import 'package:wake_alarm_sync/screens/stakes_card.dart';
|
||||||
|
|
||||||
|
/// The two detail tiles under the alarm time: today's stakes and the last
|
||||||
|
/// week of mornings.
|
||||||
|
///
|
||||||
|
/// The home screen fits one phone screen with no scrolling, so these cards
|
||||||
|
/// moved behind a tap instead of stacking under the control. Each opens its
|
||||||
|
/// full card in a bottom sheet; nothing was dropped.
|
||||||
|
class HomeTiles extends StatelessWidget {
|
||||||
|
/// Creates the tiles; [syncEpoch] and [busy] reach the cards they open.
|
||||||
|
const HomeTiles({
|
||||||
|
required this.syncEpoch,
|
||||||
|
required this.busy,
|
||||||
|
this.onEscaped,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Bumped after every sync; a sheet opened afterwards loads fresh data.
|
||||||
|
final int syncEpoch;
|
||||||
|
|
||||||
|
/// Disables the escape hatch while the screen is syncing.
|
||||||
|
final bool busy;
|
||||||
|
|
||||||
|
/// Called after the escape hatch was used, so the screen publishes it.
|
||||||
|
final VoidCallback? onEscaped;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(
|
||||||
|
child: _Tile(
|
||||||
|
key: const Key('home-tile-stakes'),
|
||||||
|
icon: Icons.gavel_outlined,
|
||||||
|
semanticLabel: "Today's stakes",
|
||||||
|
sheet: StakesCard(
|
||||||
|
key: ValueKey<String>('stakes-$syncEpoch'),
|
||||||
|
busy: busy,
|
||||||
|
onEscaped: onEscaped,
|
||||||
|
emptyText: 'No stakes to show: the native side has not answered.',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Expanded(
|
||||||
|
child: _Tile(
|
||||||
|
key: const Key('home-tile-history'),
|
||||||
|
icon: Icons.history,
|
||||||
|
semanticLabel: 'Last mornings',
|
||||||
|
sheet: HomeHistoryCard(
|
||||||
|
key: ValueKey<String>('history-$syncEpoch'),
|
||||||
|
emptyText: 'No finished morning yet.',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _Tile extends StatelessWidget {
|
||||||
|
const _Tile({
|
||||||
|
required this.icon,
|
||||||
|
required this.semanticLabel,
|
||||||
|
required this.sheet,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
final IconData icon;
|
||||||
|
final String semanticLabel;
|
||||||
|
final Widget sheet;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return Card(
|
||||||
|
color: theme.colorScheme.surfaceContainerHigh,
|
||||||
|
margin: EdgeInsets.zero,
|
||||||
|
clipBehavior: Clip.antiAlias,
|
||||||
|
child: InkWell(
|
||||||
|
onTap: () => showModalBottomSheet<void>(
|
||||||
|
context: context,
|
||||||
|
isScrollControlled: true,
|
||||||
|
builder: (_) => SafeArea(
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
padding: const EdgeInsets.all(24),
|
||||||
|
child: sheet,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 12),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Icon(icon, size: 32, semanticLabel: semanticLabel),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,9 +1,10 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/screens/ring_challenge.dart';
|
import 'package:wake_alarm_sync/screens/ring_challenge.dart';
|
||||||
import 'package:wake_alarm_sync/screens/ring_checklist.dart';
|
import 'package:wake_alarm_sync/screens/ring_checklist.dart';
|
||||||
import 'package:wake_alarm_sync/screens/ring_stakes_line.dart';
|
import 'package:wake_alarm_sync/screens/ring_stakes_line.dart';
|
||||||
import 'package:wake_alarm_sync/services/challenge.dart';
|
import 'package:wake_alarm_sync/services/challenge.dart';
|
||||||
import 'package:wake_alarm_sync/services/dismiss_gate.dart';
|
import 'package:wake_alarm_sync/services/dismiss_gate.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/cues.dart';
|
||||||
|
|
||||||
/// The ring screen's body: the checklist, or the live challenge, plus status.
|
/// The ring screen's body: the checklist, or the live challenge, plus status.
|
||||||
///
|
///
|
||||||
@ -38,7 +39,6 @@ class RingBody extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
|
||||||
final inChallenges = gate.stage == DismissStage.challenges;
|
final inChallenges = gate.stage == DismissStage.challenges;
|
||||||
return PopScope(
|
return PopScope(
|
||||||
// The alarm cannot be escaped with back; dismissing is the only way out.
|
// The alarm cannot be escaped with back; dismissing is the only way out.
|
||||||
@ -50,7 +50,6 @@ class RingBody extends StatelessWidget {
|
|||||||
child: Column(
|
child: Column(
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
Text('Wake up', style: theme.textTheme.headlineMedium),
|
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
const RingStakesLine(),
|
const RingStakesLine(),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
@ -65,7 +64,7 @@ class RingBody extends StatelessWidget {
|
|||||||
else
|
else
|
||||||
RingChecklist(gate: gate),
|
RingChecklist(gate: gate),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Text(status, style: theme.textTheme.bodyMedium),
|
_StatusRow(status: status),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@ -74,3 +73,21 @@ class RingBody extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class _StatusRow extends StatelessWidget {
|
||||||
|
const _StatusRow({required this.status});
|
||||||
|
|
||||||
|
final String status;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final match = RegExp(r'\d+(/\d+)?').firstMatch(status);
|
||||||
|
return Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
StatusCue(semanticLabel: status),
|
||||||
|
if (match != null) ...[const SizedBox(width: 8), Text(match.group(0)!)],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/services/challenge.dart';
|
import 'package:wake_alarm_sync/services/challenge.dart';
|
||||||
import 'package:wake_alarm_sync/services/dismiss_gate.dart';
|
import 'package:wake_alarm_sync/services/dismiss_gate.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/spoken_label.dart';
|
||||||
|
|
||||||
/// The question half of the ring screen, shown once the walk is proven.
|
/// The question half of the ring screen, shown once the walk is proven.
|
||||||
class RingChallenge extends StatelessWidget {
|
class RingChallenge extends StatelessWidget {
|
||||||
@ -32,37 +33,99 @@ class RingChallenge extends StatelessWidget {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
|
final colorScheme = theme.colorScheme;
|
||||||
|
const answerWords = 'Answer';
|
||||||
return Column(
|
return Column(
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
Text(
|
SpokenLabel(
|
||||||
'Question ${passed + 1} of $total',
|
semanticLabel: 'Question ${passed + 1} of $total',
|
||||||
style: theme.textTheme.labelLarge,
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Text('${passed + 1}/$total', style: theme.textTheme.labelLarge),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: List.generate(total, (i) {
|
||||||
|
final filled = i < passed;
|
||||||
|
final current = i == passed;
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 2),
|
||||||
|
child: Icon(
|
||||||
|
filled
|
||||||
|
? Icons.circle
|
||||||
|
: current
|
||||||
|
? Icons.circle_outlined
|
||||||
|
: Icons.circle_outlined,
|
||||||
|
size: 8,
|
||||||
|
color: filled
|
||||||
|
? colorScheme.primary
|
||||||
|
: current
|
||||||
|
? colorScheme.primary
|
||||||
|
: colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Text(challenge.hint, style: theme.textTheme.bodyLarge),
|
SpokenLabel(
|
||||||
|
semanticLabel: challenge.hint,
|
||||||
|
child: Icon(
|
||||||
|
_kindIcon(challenge.kind),
|
||||||
|
size: 40,
|
||||||
|
color: colorScheme.primary,
|
||||||
|
),
|
||||||
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
Text(
|
KeyedSubtree(
|
||||||
// Always visible: a challenge that hides itself is unsolvable when
|
key: const ValueKey<String>('content:challenge'),
|
||||||
// the user reaches the screen having walked in from another room.
|
child: Text(
|
||||||
challenge.display,
|
challenge.display,
|
||||||
textAlign: TextAlign.center,
|
textAlign: TextAlign.center,
|
||||||
style: theme.textTheme.displaySmall,
|
style: theme.textTheme.displaySmall,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
TextField(
|
MergeSemantics(
|
||||||
controller: controller,
|
child: Semantics(
|
||||||
autofocus: true,
|
label: answerWords,
|
||||||
textCapitalization: TextCapitalization.characters,
|
child: TextField(
|
||||||
decoration: const InputDecoration(labelText: 'Answer'),
|
controller: controller,
|
||||||
onSubmitted: (_) => onSubmit(),
|
autofocus: true,
|
||||||
|
textCapitalization: TextCapitalization.characters,
|
||||||
|
decoration: const InputDecoration(prefixIcon: Icon(Icons.edit)),
|
||||||
|
onSubmitted: (_) => onSubmit(),
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
FilledButton(onPressed: onSubmit, child: const Text('Submit')),
|
FilledButton(
|
||||||
|
key: const Key('ring-submit'),
|
||||||
|
style: FilledButton.styleFrom(minimumSize: const Size(160, 48)),
|
||||||
|
onPressed: onSubmit,
|
||||||
|
child: const Icon(Icons.check, semanticLabel: 'Submit'),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
IconData _kindIcon(ChallengeKind kind) {
|
||||||
|
switch (kind) {
|
||||||
|
case ChallengeKind.math:
|
||||||
|
return Icons.calculate_outlined;
|
||||||
|
case ChallengeKind.sort:
|
||||||
|
return Icons.trending_up;
|
||||||
|
case ChallengeKind.sequence:
|
||||||
|
return Icons.more_horiz;
|
||||||
|
case ChallengeKind.reverse:
|
||||||
|
return Icons.swap_horiz;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Logs [challenge] so a hardware test can be scripted.
|
/// Logs [challenge] so a hardware test can be scripted.
|
||||||
///
|
///
|
||||||
/// Debug aid only: the answer is already on screen for whoever is holding
|
/// Debug aid only: the answer is already on screen for whoever is holding
|
||||||
|
|||||||
@ -1,5 +1,7 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/services/dismiss_gate.dart';
|
import 'package:wake_alarm_sync/services/dismiss_gate.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/room_proof.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/spoken_label.dart';
|
||||||
|
|
||||||
/// The three-step progress list shown while the room proof is incomplete.
|
/// The three-step progress list shown while the room proof is incomplete.
|
||||||
///
|
///
|
||||||
@ -25,6 +27,7 @@ class RingChecklist extends StatelessWidget {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
|
final colorScheme = theme.colorScheme;
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
@ -32,42 +35,98 @@ class RingChecklist extends StatelessWidget {
|
|||||||
if (!(gate.bypassActive && stage != DismissStage.steps))
|
if (!(gate.bypassActive && stage != DismissStage.steps))
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||||
child: Row(
|
child: SpokenLabel(
|
||||||
children: <Widget>[
|
semanticLabel: label,
|
||||||
Icon(
|
key: ValueKey<String>('ring-row-${stage.name}'),
|
||||||
_isDone(stage)
|
child: Row(
|
||||||
? Icons.check_circle
|
children: <Widget>[
|
||||||
: Icons.radio_button_unchecked,
|
Icon(
|
||||||
color: _isDone(stage)
|
_isDone(stage)
|
||||||
? theme.colorScheme.primary
|
? Icons.check_circle
|
||||||
: theme.disabledColor,
|
: Icons.radio_button_unchecked,
|
||||||
),
|
color: _isDone(stage)
|
||||||
const SizedBox(width: 12),
|
? colorScheme.primary
|
||||||
Text(
|
: theme.disabledColor,
|
||||||
label,
|
size: gate.stage == stage ? 32 : 24,
|
||||||
style: gate.stage == stage
|
),
|
||||||
? theme.textTheme.titleMedium
|
const SizedBox(width: 12),
|
||||||
: theme.textTheme.bodyMedium,
|
_stageGlyphs(stage, gate.stage == stage, colorScheme),
|
||||||
),
|
],
|
||||||
],
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
if (gate.bypassActive)
|
if (gate.bypassActive)
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.only(top: 12),
|
padding: const EdgeInsets.only(top: 12),
|
||||||
child: Text(
|
child: SpokenLabel(
|
||||||
// This line persists; the status below it is overwritten by the
|
semanticLabel: gate.awayActive
|
||||||
// live step count within seconds, so the reason the tags went
|
|
||||||
// away has to live here or the user never sees it.
|
|
||||||
gate.awayActive
|
|
||||||
? 'Away from home — the tags are elsewhere. Walk, then '
|
? 'Away from home — the tags are elsewhere. Walk, then '
|
||||||
'answer ${gate.challengesRequired} questions.'
|
'answer ${gate.challengesRequired} questions.'
|
||||||
: 'Tags unavailable — walk, then answer '
|
: 'Tags unavailable — walk, then answer '
|
||||||
'${gate.challengesRequired} questions instead.',
|
'${gate.challengesRequired} questions instead.',
|
||||||
style: theme.textTheme.bodyMedium,
|
key: const Key('ring-bypass'),
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Icon(
|
||||||
|
gate.awayActive ? Icons.explore : Icons.block,
|
||||||
|
color: colorScheme.error,
|
||||||
|
),
|
||||||
|
const Icon(Icons.arrow_forward, size: 16),
|
||||||
|
const Icon(Icons.directions_walk),
|
||||||
|
const Icon(Icons.arrow_forward, size: 16),
|
||||||
|
const Icon(Icons.quiz_outlined),
|
||||||
|
Text('${gate.challengesRequired}'),
|
||||||
|
],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Widget _stageGlyphs(DismissStage stage, bool current, ColorScheme cs) {
|
||||||
|
final primary = cs.primary;
|
||||||
|
final muted = cs.onSurfaceVariant;
|
||||||
|
final color = current ? primary : muted;
|
||||||
|
final size = current ? 32.0 : 24.0;
|
||||||
|
switch (stage) {
|
||||||
|
case DismissStage.tag1:
|
||||||
|
return Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Icon(Icons.nfc, size: size, color: color),
|
||||||
|
Text(
|
||||||
|
'1',
|
||||||
|
style: TextStyle(fontSize: size, color: color),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
case DismissStage.steps:
|
||||||
|
return Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Icon(Icons.directions_walk, size: size, color: color),
|
||||||
|
Text(
|
||||||
|
'${RoomProof.requiredSteps}',
|
||||||
|
style: TextStyle(fontSize: size, color: color),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
case DismissStage.tag2:
|
||||||
|
return Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Icon(Icons.nfc, size: size, color: color),
|
||||||
|
Text(
|
||||||
|
'2',
|
||||||
|
style: TextStyle(fontSize: size, color: color),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
case DismissStage.challenges:
|
||||||
|
case DismissStage.done:
|
||||||
|
return const SizedBox.shrink();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'dart:developer' as developer;
|
import 'dart:developer' as developer;
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/screens/ring_body.dart';
|
import 'package:wake_alarm_sync/screens/ring_body.dart';
|
||||||
import 'package:wake_alarm_sync/screens/ring_challenge.dart';
|
import 'package:wake_alarm_sync/screens/ring_challenge.dart';
|
||||||
import 'package:wake_alarm_sync/services/alarm_policy.dart';
|
import 'package:wake_alarm_sync/services/alarm_policy.dart';
|
||||||
|
|||||||
@ -1,8 +1,10 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/services/enforcement_bridge.dart';
|
import 'package:wake_alarm_sync/services/enforcement_bridge.dart';
|
||||||
import 'package:wake_alarm_sync/services/today_stakes.dart';
|
import 'package:wake_alarm_sync/services/today_stakes.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/cues.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/spoken_label.dart';
|
||||||
import 'package:wake_alarm_sync/ui/theme.dart';
|
import 'package:wake_alarm_sync/ui/theme.dart';
|
||||||
|
|
||||||
/// The ring screen's one line: what not dismissing costs today.
|
/// The ring screen's one line: what not dismissing costs today.
|
||||||
@ -23,7 +25,7 @@ class RingStakesLine extends StatefulWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _RingStakesLineState extends State<RingStakesLine> {
|
class _RingStakesLineState extends State<RingStakesLine> {
|
||||||
String? _line;
|
({DateTime by, DateTime lockThrough})? _stakes;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
@ -32,32 +34,59 @@ class _RingStakesLineState extends State<RingStakesLine> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _load() async {
|
Future<void> _load() async {
|
||||||
String? line;
|
({DateTime by, DateTime lockThrough})? stakes;
|
||||||
try {
|
try {
|
||||||
final state = await (widget.bridge ?? EnforcementBridge()).state();
|
final state = await (widget.bridge ?? EnforcementBridge()).state();
|
||||||
line = state == null ? null : ringStakesLine(state);
|
stakes = state == null ? null : ringStakes(state);
|
||||||
} on Exception {
|
} on Exception {
|
||||||
line = null;
|
stakes = null;
|
||||||
}
|
}
|
||||||
if (!mounted || line == null) return;
|
if (!mounted || stakes == null) return;
|
||||||
setState(() => _line = line);
|
setState(() => _stakes = stakes);
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final line = _line;
|
final stakes = _stakes;
|
||||||
if (line == null) return const SizedBox.shrink();
|
if (stakes == null) return const SizedBox.shrink();
|
||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
|
final statusColors = theme.extension<AppStatusColors>();
|
||||||
|
final warningColor = statusColors?.warning ?? Colors.amber;
|
||||||
|
final line =
|
||||||
|
'Stick day: no dismiss by ${hhmm(stakes.by)} → apps locked through '
|
||||||
|
'${formatDay(stakes.lockThrough)}';
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.only(bottom: 16),
|
padding: const EdgeInsets.only(bottom: 16),
|
||||||
child: Text(
|
child: SpokenLabel(
|
||||||
line,
|
semanticLabel: line,
|
||||||
textAlign: TextAlign.center,
|
child: Row(
|
||||||
style: theme.textTheme.bodyMedium?.copyWith(
|
mainAxisSize: MainAxisSize.min,
|
||||||
// Null-safe: a missing theme extension must not break a ring.
|
children: <Widget>[
|
||||||
color: theme.extension<AppStatusColors>()?.warning,
|
Tooltip(
|
||||||
|
message: 'Deadline',
|
||||||
|
child: Icon(Icons.gavel_outlined, color: warningColor),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Text(hhmm(stakes.by), style: TextStyle(color: warningColor)),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
const Icon(Icons.arrow_forward, size: 16),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Tooltip(
|
||||||
|
message: 'Lock',
|
||||||
|
child: Icon(Icons.lock_outline, color: warningColor),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Text(
|
||||||
|
_formatLockDate(stakes.lockThrough),
|
||||||
|
style: TextStyle(color: warningColor),
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String _formatLockDate(DateTime d) =>
|
||||||
|
'${d.day.toString().padLeft(2, '0')}'
|
||||||
|
'.${d.month.toString().padLeft(2, '0')}';
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,8 +1,10 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.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/ui/cues.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/dashed_slot.dart';
|
||||||
|
|
||||||
/// Registers the two NFC tags the dismiss sequence walks between.
|
/// Registers the two NFC tags the dismiss sequence walks between.
|
||||||
///
|
///
|
||||||
@ -43,7 +45,17 @@ class _RoomProofScreenState extends State<RoomProofScreen> {
|
|||||||
Future<void> _load() async {
|
Future<void> _load() async {
|
||||||
final settings = await RoomProofSettings.load();
|
final settings = await RoomProofSettings.load();
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _settings = settings);
|
var status = '';
|
||||||
|
for (var i = 0; i < RoomProofSettings.requiredTagCount; i++) {
|
||||||
|
if (settings.tagAt(i) != null) {
|
||||||
|
status = 'Tag ${i + 1} registered.';
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setState(() {
|
||||||
|
_settings = settings;
|
||||||
|
_status = status;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _startScan(int slot) async {
|
Future<void> _startScan(int slot) async {
|
||||||
@ -89,18 +101,33 @@ class _RoomProofScreenState extends State<RoomProofScreen> {
|
|||||||
final scanning = _scanningSlot == slot;
|
final scanning = _scanningSlot == slot;
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.only(bottom: 24),
|
padding: const EdgeInsets.only(bottom: 24),
|
||||||
child: Column(
|
child: Row(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
Text('Tag ${slot + 1}: ${id ?? "none registered"}'),
|
CircleAvatar(radius: 14, child: Text('${slot + 1}')),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(width: 12),
|
||||||
|
Expanded(
|
||||||
|
child: id != null
|
||||||
|
? KeyedSubtree(
|
||||||
|
key: ValueKey<String>('content:tag-$slot'),
|
||||||
|
child: Text(id),
|
||||||
|
)
|
||||||
|
: const DashedSlot(),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
FilledButton(
|
FilledButton(
|
||||||
|
key: ValueKey<String>('register-$slot'),
|
||||||
onPressed: _scanningSlot != null ? null : () => _startScan(slot),
|
onPressed: _scanningSlot != null ? null : () => _startScan(slot),
|
||||||
child: Text(
|
child: scanning
|
||||||
scanning
|
? const SizedBox.square(
|
||||||
? 'Waiting for tag…'
|
dimension: 20,
|
||||||
: 'Register tag ${slot + 1}${id == null ? "" : " again"}',
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
),
|
)
|
||||||
|
: Icon(
|
||||||
|
id == null ? Icons.add : Icons.refresh,
|
||||||
|
semanticLabel: id == null
|
||||||
|
? 'Register tag ${slot + 1}'
|
||||||
|
: 'Register tag ${slot + 1} again',
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@ -110,20 +137,15 @@ class _RoomProofScreenState extends State<RoomProofScreen> {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(title: const Text('Room proof')),
|
appBar: AppBar(),
|
||||||
body: Padding(
|
body: Padding(
|
||||||
padding: const EdgeInsets.all(24),
|
padding: const EdgeInsets.all(24),
|
||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
const Text(
|
|
||||||
'Put the two tags in different rooms. Dismissing the alarm '
|
|
||||||
'means tapping tag 1, walking, then tapping tag 2.',
|
|
||||||
),
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
for (var i = 0; i < RoomProofSettings.requiredTagCount; i++)
|
for (var i = 0; i < RoomProofSettings.requiredTagCount; i++)
|
||||||
_slotRow(i),
|
_slotRow(i),
|
||||||
Text(_status),
|
StatusCue(semanticLabel: _status),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@ -1,7 +1,11 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/screens/energy_picker.dart';
|
import 'package:wake_alarm_sync/screens/energy_picker.dart';
|
||||||
import 'package:wake_alarm_sync/screens/session_checklist.dart';
|
import 'package:wake_alarm_sync/screens/session_checklist.dart';
|
||||||
import 'package:wake_alarm_sync/services/morning_session.dart';
|
import 'package:wake_alarm_sync/services/morning_session.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/cues.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/theme.dart';
|
||||||
|
|
||||||
|
const _weightSemantics = 'Weight (kg)';
|
||||||
|
|
||||||
/// The session screen's body: the checklist, the check-in, the clocks.
|
/// The session screen's body: the checklist, the check-in, the clocks.
|
||||||
///
|
///
|
||||||
@ -49,8 +53,9 @@ class SessionBody extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
|
||||||
final leg = session.currentLeg;
|
final leg = session.currentLeg;
|
||||||
|
final reRingWords =
|
||||||
|
'Re-rings: ${session.reRings}/${MorningSession.maxReRings}';
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
body: SafeArea(
|
body: SafeArea(
|
||||||
child: SingleChildScrollView(
|
child: SingleChildScrollView(
|
||||||
@ -58,58 +63,54 @@ class SessionBody extends StatelessWidget {
|
|||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
Text('Stay up', style: theme.textTheme.headlineMedium),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Text(
|
|
||||||
'The alarm is off. It comes back if a step below is missed. '
|
|
||||||
'Leaving the app is fine — the notification brings you back.',
|
|
||||||
style: theme.textTheme.bodyMedium,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
SessionChecklist(session: session, now: now),
|
SessionChecklist(session: session, now: now),
|
||||||
const SizedBox(height: 24),
|
const SizedBox(height: 24),
|
||||||
if (_awaitingWeight) ...<Widget>[
|
if (_awaitingWeight) ...<Widget>[
|
||||||
EnergyPicker(selected: energy, onSelect: onSelectEnergy),
|
EnergyPicker(selected: energy, onSelect: onSelectEnergy),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
TextField(
|
MergeSemantics(
|
||||||
controller: controller,
|
child: Semantics(
|
||||||
keyboardType: const TextInputType.numberWithOptions(
|
label: _weightSemantics,
|
||||||
decimal: true,
|
child: TextField(
|
||||||
|
controller: controller,
|
||||||
|
keyboardType: const TextInputType.numberWithOptions(
|
||||||
|
decimal: true,
|
||||||
|
),
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
prefixIcon: Icon(Icons.monitor_weight_outlined),
|
||||||
|
border: OutlineInputBorder(),
|
||||||
|
),
|
||||||
|
onSubmitted: (_) => onSubmitWeight(),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'Weight (kg)',
|
|
||||||
border: OutlineInputBorder(),
|
|
||||||
),
|
|
||||||
onSubmitted: (_) => onSubmitWeight(),
|
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
FilledButton(
|
FilledButton(
|
||||||
|
key: const Key('session-log-weight'),
|
||||||
onPressed: onSubmitWeight,
|
onPressed: onSubmitWeight,
|
||||||
child: const Text('Log weight'),
|
child: const Icon(Icons.check, semanticLabel: 'Log weight'),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
],
|
],
|
||||||
if (leg != null)
|
if (leg != null) ...<Widget>[
|
||||||
Text(
|
SpokenLabel(
|
||||||
_deadlineLine(leg),
|
semanticLabel: _deadlineWords(leg),
|
||||||
textAlign: TextAlign.center,
|
child: _DeadlineRow(leg: leg, session: session, now: now),
|
||||||
style: theme.textTheme.titleMedium,
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
],
|
||||||
|
SpokenLabel(
|
||||||
|
semanticLabel: reRingWords,
|
||||||
|
child: Row(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
|
children: <Widget>[
|
||||||
|
const Icon(Icons.replay, size: 16),
|
||||||
|
Text('${session.reRings}/${MorningSession.maxReRings}'),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
|
||||||
Text(
|
|
||||||
'Re-rings: ${session.reRings}/${MorningSession.maxReRings}',
|
|
||||||
textAlign: TextAlign.center,
|
|
||||||
style: theme.textTheme.bodySmall,
|
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
if (status.isNotEmpty)
|
Center(child: StatusCue(semanticLabel: status)),
|
||||||
Text(
|
|
||||||
status,
|
|
||||||
textAlign: TextAlign.center,
|
|
||||||
maxLines: 3,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
style: theme.textTheme.bodyLarge,
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@ -117,10 +118,10 @@ class SessionBody extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
String _deadlineLine(SessionLeg leg) {
|
String _deadlineWords(SessionLeg leg) {
|
||||||
final soonest = session.earliest(leg);
|
final soonest = session.earliest(leg);
|
||||||
if (soonest != null && now.isBefore(soonest)) {
|
if (soonest != null && now.isBefore(soonest)) {
|
||||||
return 'Shower — tag counts in ${_mmss(soonest.difference(now))}';
|
return 'Shower tag counts in ${_mmss(soonest.difference(now))}';
|
||||||
}
|
}
|
||||||
final deadline = session.deadline(leg);
|
final deadline = session.deadline(leg);
|
||||||
if (now.isBefore(deadline)) {
|
if (now.isBefore(deadline)) {
|
||||||
@ -135,3 +136,54 @@ class SessionBody extends StatelessWidget {
|
|||||||
return '$m:$s';
|
return '$m:$s';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class _DeadlineRow extends StatelessWidget {
|
||||||
|
const _DeadlineRow({
|
||||||
|
required this.leg,
|
||||||
|
required this.session,
|
||||||
|
required this.now,
|
||||||
|
});
|
||||||
|
|
||||||
|
final SessionLeg leg;
|
||||||
|
final MorningSession session;
|
||||||
|
final DateTime now;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final soonest = session.earliest(leg);
|
||||||
|
if (soonest != null && now.isBefore(soonest)) {
|
||||||
|
return Row(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
|
children: <Widget>[
|
||||||
|
const Icon(Icons.shower),
|
||||||
|
const Icon(Icons.hourglass_top),
|
||||||
|
Text(_mmss(soonest.difference(now))),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final deadline = session.deadline(leg);
|
||||||
|
if (now.isBefore(deadline)) {
|
||||||
|
return Row(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
|
children: <Widget>[
|
||||||
|
const Icon(Icons.alarm),
|
||||||
|
Text(_mmss(deadline.difference(now))),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final statusColors = theme.extension<AppStatusColors>();
|
||||||
|
return Row(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
|
children: <Widget>[
|
||||||
|
Icon(Icons.alarm_off, color: statusColors?.warning ?? Colors.amber),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String _mmss(Duration d) {
|
||||||
|
final m = d.inMinutes.toString().padLeft(2, '0');
|
||||||
|
final s = (d.inSeconds % 60).toString().padLeft(2, '0');
|
||||||
|
return '$m:$s';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.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/weight_entry.dart';
|
import 'package:wake_alarm_sync/services/weight_entry.dart';
|
||||||
|
|||||||
@ -1,6 +1,8 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.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/weight_entry.dart';
|
import 'package:wake_alarm_sync/services/weight_entry.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/spoken_label.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/theme.dart';
|
||||||
|
|
||||||
/// The session's progress list: the weigh-in, then every leg with a tag.
|
/// The session's progress list: the weigh-in, then every leg with a tag.
|
||||||
///
|
///
|
||||||
@ -23,50 +25,142 @@ class SessionChecklist extends StatelessWidget {
|
|||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
final weighed = session.weightKg != null || session.pendingWeightKg != null;
|
final weighed = session.weightKg != null || session.pendingWeightKg != null;
|
||||||
final current = session.currentLeg;
|
final current = session.currentLeg;
|
||||||
final rows = <(String, bool, bool)>[
|
final rows = <Widget>[
|
||||||
(
|
_WeighInRow(
|
||||||
'Weigh in${_kg(session)}',
|
session: session,
|
||||||
weighed,
|
weighed: weighed,
|
||||||
!weighed && current == SessionLeg.bathroomIn,
|
current: current,
|
||||||
|
theme: theme,
|
||||||
),
|
),
|
||||||
for (final leg in SessionLeg.values)
|
for (final leg in SessionLeg.values)
|
||||||
if (session.passedHow[leg] != LegPass.skipped)
|
if (session.passedHow[leg] != LegPass.skipped)
|
||||||
(
|
_LegRow(
|
||||||
_label(leg),
|
session: session,
|
||||||
session.passedAt.containsKey(leg),
|
leg: leg,
|
||||||
leg == current && (leg != SessionLeg.bathroomIn || weighed),
|
current: current,
|
||||||
|
theme: theme,
|
||||||
|
weighed: weighed,
|
||||||
),
|
),
|
||||||
];
|
];
|
||||||
return Column(
|
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: rows);
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
}
|
||||||
children: <Widget>[
|
}
|
||||||
for (final (label, done, live) in rows)
|
|
||||||
Padding(
|
class _WeighInRow extends StatelessWidget {
|
||||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
const _WeighInRow({
|
||||||
child: Row(
|
required this.session,
|
||||||
children: <Widget>[
|
required this.weighed,
|
||||||
Icon(
|
required this.current,
|
||||||
done ? Icons.check_circle : Icons.radio_button_unchecked,
|
required this.theme,
|
||||||
color: done ? theme.colorScheme.primary : theme.disabledColor,
|
});
|
||||||
),
|
|
||||||
const SizedBox(width: 12),
|
final MorningSession session;
|
||||||
Expanded(
|
final bool weighed;
|
||||||
child: Text(
|
final SessionLeg? current;
|
||||||
label,
|
final ThemeData theme;
|
||||||
style: live
|
|
||||||
? theme.textTheme.titleMedium
|
@override
|
||||||
: theme.textTheme.bodyMedium,
|
Widget build(BuildContext context) {
|
||||||
),
|
final live = !weighed && current == SessionLeg.bathroomIn;
|
||||||
),
|
return SpokenLabel(
|
||||||
],
|
semanticLabel: weighed
|
||||||
|
? session.energy == null
|
||||||
|
? 'Weight logged'
|
||||||
|
: 'Weigh in — ${session.weightKg ?? session.pendingWeightKg} kg · energy ${session.energy}/$maxEnergy'
|
||||||
|
: 'Weigh in',
|
||||||
|
key: const ValueKey<String>('session-row-weigh'),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Icon(
|
||||||
|
weighed ? Icons.check_circle : Icons.radio_button_unchecked,
|
||||||
|
color: weighed ? theme.colorScheme.primary : theme.disabledColor,
|
||||||
),
|
),
|
||||||
),
|
const SizedBox(width: 12),
|
||||||
],
|
Icon(
|
||||||
|
Icons.monitor_weight_outlined,
|
||||||
|
size: 32,
|
||||||
|
color: live ? theme.colorScheme.primary : null,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
if (weighed) ...<Widget>[
|
||||||
|
Text('${session.weightKg ?? session.pendingWeightKg}'),
|
||||||
|
if (session.energy != null) ...<Widget>[
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
const Icon(Icons.bolt, size: 18),
|
||||||
|
Text('${session.energy}/$maxEnergy'),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _LegRow extends StatelessWidget {
|
||||||
|
const _LegRow({
|
||||||
|
required this.session,
|
||||||
|
required this.leg,
|
||||||
|
required this.current,
|
||||||
|
required this.theme,
|
||||||
|
required this.weighed,
|
||||||
|
});
|
||||||
|
|
||||||
|
final MorningSession session;
|
||||||
|
final SessionLeg leg;
|
||||||
|
final SessionLeg? current;
|
||||||
|
final ThemeData theme;
|
||||||
|
final bool weighed;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final done = session.passedAt.containsKey(leg);
|
||||||
|
final how = session.passedHow[leg];
|
||||||
|
final live = leg == current && (leg != SessionLeg.bathroomIn || weighed);
|
||||||
|
final bypassed = how == LegPass.bypassed;
|
||||||
|
|
||||||
|
final statusColors = theme.extension<AppStatusColors>();
|
||||||
|
final warningColor = statusColors?.warning ?? Colors.amber;
|
||||||
|
|
||||||
|
IconData frontIcon;
|
||||||
|
if (done) {
|
||||||
|
frontIcon = bypassed ? Icons.timer_off : Icons.check_circle;
|
||||||
|
} else {
|
||||||
|
frontIcon = Icons.radio_button_unchecked;
|
||||||
|
}
|
||||||
|
|
||||||
|
Color frontColor;
|
||||||
|
if (done) {
|
||||||
|
frontColor = bypassed ? warningColor : theme.colorScheme.primary;
|
||||||
|
} else {
|
||||||
|
frontColor = theme.disabledColor;
|
||||||
|
}
|
||||||
|
|
||||||
|
return SpokenLabel(
|
||||||
|
semanticLabel: how == null ? leg.label : _semanticLabel(leg, how),
|
||||||
|
key: ValueKey<String>('session-row-${leg.name}'),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Icon(frontIcon, color: frontColor, size: live ? 32 : 24),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
_legIcon(
|
||||||
|
leg,
|
||||||
|
size: live ? 32 : 24,
|
||||||
|
color: live ? theme.colorScheme.primary : null,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
const Icon(Icons.nfc, size: 18),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
String _label(SessionLeg leg) {
|
String _semanticLabel(SessionLeg leg, LegPass how) {
|
||||||
final how = session.passedHow[leg];
|
|
||||||
if (how == LegPass.bypassed) return '${leg.label} (skipped by the clock)';
|
if (how == LegPass.bypassed) return '${leg.label} (skipped by the clock)';
|
||||||
if (leg == SessionLeg.bathroomIn && !session.bathroomTagRequired) {
|
if (leg == SessionLeg.bathroomIn && !session.bathroomTagRequired) {
|
||||||
return 'Weight logged';
|
return 'Weight logged';
|
||||||
@ -74,12 +168,20 @@ class SessionChecklist extends StatelessWidget {
|
|||||||
return leg.label;
|
return leg.label;
|
||||||
}
|
}
|
||||||
|
|
||||||
static String _kg(MorningSession session) {
|
Widget _legIcon(SessionLeg leg, {double size = 24, Color? color}) {
|
||||||
final kg = session.weightKg ?? session.pendingWeightKg;
|
return Icon(_legIconData(leg), size: size, color: color);
|
||||||
if (kg == null) return '';
|
}
|
||||||
final energy = session.energy;
|
|
||||||
return energy == null
|
IconData _legIconData(SessionLeg leg) {
|
||||||
? ' — $kg kg'
|
switch (leg) {
|
||||||
: ' — $kg kg · energy $energy/$maxEnergy';
|
case SessionLeg.bathroomIn:
|
||||||
|
return Icons.bathroom_outlined;
|
||||||
|
case SessionLeg.showerDone:
|
||||||
|
return Icons.shower;
|
||||||
|
case SessionLeg.dressed:
|
||||||
|
return Icons.checkroom;
|
||||||
|
case SessionLeg.atDesk:
|
||||||
|
return Icons.desk;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/main.dart';
|
import 'package:wake_alarm_sync/main.dart';
|
||||||
import 'package:wake_alarm_sync/screens/session_body.dart';
|
import 'package:wake_alarm_sync/screens/session_body.dart';
|
||||||
import 'package:wake_alarm_sync/screens/session_checkin.dart';
|
import 'package:wake_alarm_sync/screens/session_checkin.dart';
|
||||||
@ -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;
|
||||||
|
|||||||
@ -1,8 +1,10 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.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/session_tag_settings.dart';
|
import 'package:wake_alarm_sync/services/session_tag_settings.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/cues.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/dashed_slot.dart';
|
||||||
|
|
||||||
/// Registers the three NFC tags the morning session walks through.
|
/// Registers the three NFC tags the morning session walks through.
|
||||||
///
|
///
|
||||||
@ -81,52 +83,67 @@ class _SessionTagsScreenState extends State<SessionTagsScreen> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
IconData _iconForSlot(SessionTagSlot slot) => switch (slot) {
|
||||||
|
SessionTagSlot.bathroom => Icons.shower,
|
||||||
|
SessionTagSlot.wardrobe => Icons.checkroom,
|
||||||
|
SessionTagSlot.desk => Icons.desk,
|
||||||
|
};
|
||||||
|
|
||||||
|
String _semanticLabelForSlot(SessionTagSlot slot) => switch (slot) {
|
||||||
|
SessionTagSlot.bathroom => 'Bathroom (scale + shower)',
|
||||||
|
SessionTagSlot.wardrobe => 'Wardrobe',
|
||||||
|
SessionTagSlot.desk => 'Desk',
|
||||||
|
};
|
||||||
|
|
||||||
Widget _slotRow(SessionTagSlot slot) {
|
Widget _slotRow(SessionTagSlot slot) {
|
||||||
final id = _settings.tagAt(slot);
|
final id = _settings.tagAt(slot);
|
||||||
final scanning = _scanning == slot;
|
final scanning = _scanning == slot;
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.only(bottom: 24),
|
padding: const EdgeInsets.only(bottom: 24),
|
||||||
child: Column(
|
child: Row(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
Text('${_title(slot)}: ${id ?? "none registered"}'),
|
Icon(_iconForSlot(slot), semanticLabel: _semanticLabelForSlot(slot)),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(width: 12),
|
||||||
|
Expanded(
|
||||||
|
child: id != null
|
||||||
|
? KeyedSubtree(
|
||||||
|
key: ValueKey<String>('content:tag-${slot.name}'),
|
||||||
|
child: Text(id),
|
||||||
|
)
|
||||||
|
: const DashedSlot(),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
FilledButton(
|
FilledButton(
|
||||||
|
key: ValueKey<String>('register-${slot.name}'),
|
||||||
onPressed: _scanning != null ? null : () => _startScan(slot),
|
onPressed: _scanning != null ? null : () => _startScan(slot),
|
||||||
child: Text(
|
child: scanning
|
||||||
scanning
|
? const SizedBox.square(
|
||||||
? 'Waiting for tag…'
|
dimension: 20,
|
||||||
: 'Register ${slot.name} tag${id == null ? "" : " again"}',
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
),
|
)
|
||||||
|
: Icon(
|
||||||
|
id == null ? Icons.add : Icons.refresh,
|
||||||
|
semanticLabel: id == null
|
||||||
|
? 'Register ${slot.name} tag'
|
||||||
|
: 'Register ${slot.name} tag again',
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
static String _title(SessionTagSlot slot) => switch (slot) {
|
|
||||||
SessionTagSlot.bathroom => 'Bathroom (scale + shower)',
|
|
||||||
SessionTagSlot.wardrobe => 'Wardrobe',
|
|
||||||
SessionTagSlot.desk => 'Desk',
|
|
||||||
};
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(title: const Text('Morning session tags')),
|
appBar: AppBar(),
|
||||||
body: Padding(
|
body: Padding(
|
||||||
padding: const EdgeInsets.all(24),
|
padding: const EdgeInsets.all(24),
|
||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
const Text(
|
|
||||||
'After the alarm is dismissed: weigh in and tap the bathroom '
|
|
||||||
'tag, shower and tap it again, tap the wardrobe tag dressed, '
|
|
||||||
'then the desk tag. A slot left empty is skipped.',
|
|
||||||
),
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
for (final slot in SessionTagSlot.values) _slotRow(slot),
|
for (final slot in SessionTagSlot.values) _slotRow(slot),
|
||||||
Text(_status),
|
StatusCue(semanticLabel: _status),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@ -1,16 +1,22 @@
|
|||||||
import 'dart:developer' as developer;
|
import 'dart:developer' as developer;
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
|
||||||
|
show E2ePassphraseButton;
|
||||||
|
import 'package:kuhy_credit/kuhy_credit.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:sync_settings_ui/sync_settings_ui.dart';
|
import 'package:sync_settings_ui/sync_settings_ui.dart';
|
||||||
|
|
||||||
import 'package:wake_alarm_sync/screens/github_mirror_screen.dart';
|
import 'package:wake_alarm_sync/screens/github_mirror_screen.dart';
|
||||||
import 'package:wake_alarm_sync/screens/home_location_screen.dart';
|
import 'package:wake_alarm_sync/screens/home_location_screen.dart';
|
||||||
import 'package:wake_alarm_sync/screens/room_proof_screen.dart';
|
import 'package:wake_alarm_sync/screens/room_proof_screen.dart';
|
||||||
import 'package:wake_alarm_sync/screens/session_tags_screen.dart';
|
import 'package:wake_alarm_sync/screens/session_tags_screen.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/alarm_sync_e2e.dart';
|
||||||
import 'package:wake_alarm_sync/services/alarm_sync_service.dart';
|
import 'package:wake_alarm_sync/services/alarm_sync_service.dart';
|
||||||
import 'package:wake_alarm_sync/services/data_transfer.dart';
|
import 'package:wake_alarm_sync/services/data_transfer.dart';
|
||||||
import 'package:wake_alarm_sync/services/firebase_backend.dart';
|
import 'package:wake_alarm_sync/services/firebase_backend.dart';
|
||||||
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/ui/motion_route.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/theme.dart';
|
||||||
|
|
||||||
/// Settings screen: links to the two sync surfaces.
|
/// Settings screen: links to the two sync surfaces.
|
||||||
///
|
///
|
||||||
@ -72,24 +78,41 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final colors = theme.colorScheme;
|
||||||
|
final statusColors = theme.extension<AppStatusColors>();
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: const Text('Settings'),
|
|
||||||
actions: [
|
actions: [
|
||||||
IconButton(
|
// End-to-end encryption passphrase: a closed lock while the last
|
||||||
key: const Key('settings-export'),
|
// sync found no usable key, so nothing reaches the PC until set.
|
||||||
icon: const Icon(Icons.upload_file, semanticLabel: 'Export data'),
|
ValueListenableBuilder<bool>(
|
||||||
onPressed: () => _run(context, () async {
|
valueListenable: alarmSyncLocked,
|
||||||
await (onExport ?? () => saveExport(alarm: alarmService))();
|
builder: (_, locked, _) => E2ePassphraseButton(
|
||||||
return true;
|
key: const Key('settings-e2e'),
|
||||||
}),
|
locked: locked,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
IconButton(
|
Tooltip(
|
||||||
key: const Key('settings-import'),
|
message: 'Export',
|
||||||
icon: const Icon(Icons.download, semanticLabel: 'Import data'),
|
child: IconButton(
|
||||||
onPressed: () => _run(
|
key: const Key('settings-export'),
|
||||||
context,
|
icon: const Icon(Icons.upload_file, semanticLabel: 'Export data'),
|
||||||
onImport ?? () => pickAndImport(alarm: alarmService),
|
onPressed: () => _run(context, () async {
|
||||||
|
await (onExport ?? () => saveExport(alarm: alarmService))();
|
||||||
|
return true;
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Tooltip(
|
||||||
|
message: 'Import',
|
||||||
|
child: IconButton(
|
||||||
|
key: const Key('settings-import'),
|
||||||
|
icon: const Icon(Icons.download, semanticLabel: 'Import data'),
|
||||||
|
onPressed: () => _run(
|
||||||
|
context,
|
||||||
|
onImport ?? () => pickAndImport(alarm: alarmService),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@ -98,13 +121,17 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(16),
|
||||||
children: [
|
children: [
|
||||||
ListTile(
|
ListTile(
|
||||||
|
key: const Key('settings-sync'),
|
||||||
contentPadding: EdgeInsets.zero,
|
contentPadding: EdgeInsets.zero,
|
||||||
title: const Text('Sync settings'),
|
leading: const Icon(
|
||||||
subtitle: const Text('Firebase sync'),
|
Icons.cloud_sync_outlined,
|
||||||
|
semanticLabel: 'Sync settings',
|
||||||
|
),
|
||||||
trailing: const Icon(Icons.chevron_right),
|
trailing: const Icon(Icons.chevron_right),
|
||||||
onTap: () => Navigator.of(context).push<void>(
|
onTap: () => Navigator.of(context).push<void>(
|
||||||
MaterialPageRoute(
|
appRoute<void>(
|
||||||
builder: (_) => SyncSettingsScreen(
|
context,
|
||||||
|
(_) => SyncSettingsScreen(
|
||||||
accountLoader: loadAccount,
|
accountLoader: loadAccount,
|
||||||
accountSaver: saveAccount,
|
accountSaver: saveAccount,
|
||||||
accountClearer: clearAccount,
|
accountClearer: clearAccount,
|
||||||
@ -117,41 +144,63 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
ListTile(
|
ListTile(
|
||||||
|
key: const Key('settings-room-proof'),
|
||||||
contentPadding: EdgeInsets.zero,
|
contentPadding: EdgeInsets.zero,
|
||||||
title: const Text('Room proof'),
|
leading: const Icon(Icons.nfc, semanticLabel: 'Room proof'),
|
||||||
subtitle: const Text('Two NFC tags, at two locations'),
|
|
||||||
trailing: const Icon(Icons.chevron_right),
|
trailing: const Icon(Icons.chevron_right),
|
||||||
onTap: () => Navigator.of(context).push<void>(
|
onTap: () => Navigator.of(context).push<void>(
|
||||||
MaterialPageRoute(builder: (_) => const RoomProofScreen()),
|
appRoute<void>(context, (_) => const RoomProofScreen()),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
ListTile(
|
ListTile(
|
||||||
|
key: const Key('settings-session-tags'),
|
||||||
contentPadding: EdgeInsets.zero,
|
contentPadding: EdgeInsets.zero,
|
||||||
title: const Text('Morning session tags'),
|
leading: const Icon(
|
||||||
subtitle: const Text('Bathroom, wardrobe, desk — after the ring'),
|
Icons.checklist,
|
||||||
|
semanticLabel: 'Morning session tags',
|
||||||
|
),
|
||||||
trailing: const Icon(Icons.chevron_right),
|
trailing: const Icon(Icons.chevron_right),
|
||||||
onTap: () => Navigator.of(context).push<void>(
|
onTap: () => Navigator.of(context).push<void>(
|
||||||
MaterialPageRoute(builder: (_) => const SessionTagsScreen()),
|
appRoute<void>(context, (_) => const SessionTagsScreen()),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
ListTile(
|
ListTile(
|
||||||
|
key: const Key('settings-home'),
|
||||||
contentPadding: EdgeInsets.zero,
|
contentPadding: EdgeInsets.zero,
|
||||||
title: const Text('Home location'),
|
leading: const Icon(
|
||||||
subtitle: const Text('The Wi-Fi and place that mean you are home'),
|
Icons.home_outlined,
|
||||||
|
semanticLabel: 'Home location',
|
||||||
|
),
|
||||||
trailing: const Icon(Icons.chevron_right),
|
trailing: const Icon(Icons.chevron_right),
|
||||||
onTap: () => Navigator.of(context).push<void>(
|
onTap: () => Navigator.of(context).push<void>(
|
||||||
MaterialPageRoute(builder: (_) => const HomeLocationScreen()),
|
appRoute<void>(context, (_) => const HomeLocationScreen()),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
ListTile(
|
ListTile(
|
||||||
|
key: const Key('settings-github'),
|
||||||
contentPadding: EdgeInsets.zero,
|
contentPadding: EdgeInsets.zero,
|
||||||
title: const Text('Advanced sync (GitHub)'),
|
leading: Icon(
|
||||||
subtitle: const Text('Cutover mirror — not recommended'),
|
Icons.code,
|
||||||
trailing: const Icon(Icons.chevron_right),
|
color: colors.onSurfaceVariant.withValues(alpha: 0.6),
|
||||||
|
semanticLabel: 'Advanced sync (GitHub)',
|
||||||
|
),
|
||||||
|
trailing: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.warning_amber_rounded,
|
||||||
|
color: statusColors?.warning ?? colors.error,
|
||||||
|
semanticLabel: 'Cutover mirror, not recommended',
|
||||||
|
),
|
||||||
|
const Icon(Icons.chevron_right),
|
||||||
|
],
|
||||||
|
),
|
||||||
onTap: () => Navigator.of(context).push<void>(
|
onTap: () => Navigator.of(context).push<void>(
|
||||||
MaterialPageRoute(builder: (_) => const GitHubMirrorScreen()),
|
appRoute<void>(context, (_) => const GitHubMirrorScreen()),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
const SizedBox(height: 24),
|
||||||
|
const Center(child: KuhyCredit()),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@ -1,9 +1,11 @@
|
|||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/services/free_day_pool.dart';
|
import 'package:wake_alarm_sync/services/free_day_pool.dart';
|
||||||
import 'package:wake_alarm_sync/services/sick_day_keep.dart';
|
import 'package:wake_alarm_sync/services/sick_day_keep.dart';
|
||||||
import 'package:wake_alarm_sync/services/sick_day_pool.dart';
|
import 'package:wake_alarm_sync/services/sick_day_pool.dart';
|
||||||
|
|
||||||
|
export 'package:wake_alarm_sync/screens/sick_day_sheet.dart';
|
||||||
|
|
||||||
/// What each locker is called on screen, in `sickdays.LOCKERS` order.
|
/// What each locker is called on screen, in `sickdays.LOCKERS` order.
|
||||||
const sickLockerLabels = <String, String>{
|
const sickLockerLabels = <String, String>{
|
||||||
SickLocker.workout: 'Workout lock',
|
SickLocker.workout: 'Workout lock',
|
||||||
@ -13,6 +15,15 @@ const sickLockerLabels = <String, String>{
|
|||||||
SickLocker.alarm: 'Wake alarm',
|
SickLocker.alarm: 'Wake alarm',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// Icons for each locker, matching [sickLockerLabels] order.
|
||||||
|
const sickLockerIcons = <String, IconData>{
|
||||||
|
SickLocker.workout: Icons.fitness_center,
|
||||||
|
SickLocker.leetcode: Icons.code,
|
||||||
|
SickLocker.book: Icons.menu_book,
|
||||||
|
SickLocker.diet: Icons.restaurant,
|
||||||
|
SickLocker.alarm: Icons.alarm,
|
||||||
|
};
|
||||||
|
|
||||||
/// The kept lockers of a day as one line, in [sickLockerLabels] order.
|
/// The kept lockers of a day as one line, in [sickLockerLabels] order.
|
||||||
String keptLabel(Set<String> kept) => [
|
String keptLabel(Set<String> kept) => [
|
||||||
for (final MapEntry(:key, :value) in sickLockerLabels.entries)
|
for (final MapEntry(:key, :value) in sickLockerLabels.entries)
|
||||||
@ -116,7 +127,11 @@ class SickDaySheet extends StatefulWidget {
|
|||||||
class _SickDaySheetState extends State<SickDaySheet> {
|
class _SickDaySheetState extends State<SickDaySheet> {
|
||||||
late final Set<String> _keep = {...widget.kept};
|
late final Set<String> _keep = {...widget.kept};
|
||||||
|
|
||||||
static const _weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
|
String _toDdMmYyyy(DateTime day) {
|
||||||
|
final d = day.day.toString().padLeft(2, '0');
|
||||||
|
final m = day.month.toString().padLeft(2, '0');
|
||||||
|
return '$d.$m.${day.year}';
|
||||||
|
}
|
||||||
|
|
||||||
void _close(SickSheetAction action) => Navigator.of(
|
void _close(SickSheetAction action) => Navigator.of(
|
||||||
context,
|
context,
|
||||||
@ -132,26 +147,19 @@ class _SickDaySheetState extends State<SickDaySheet> {
|
|||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
Text(
|
Row(
|
||||||
'${widget.isSick ? 'Sick day' : 'Mark sick'}: '
|
children: [
|
||||||
'${_weekdays[day.weekday - 1]} ${FreeDayPool.toIso(day)}',
|
const Icon(Icons.sick_outlined),
|
||||||
style: theme.textTheme.titleMedium,
|
const SizedBox(width: 8),
|
||||||
),
|
Text(_toDdMmYyyy(day), style: theme.textTheme.titleMedium),
|
||||||
const SizedBox(height: 8),
|
],
|
||||||
Text(
|
|
||||||
'Off = stands down for the day. Switch on any locker that '
|
|
||||||
'should still apply; it then behaves exactly as on a normal '
|
|
||||||
'day.',
|
|
||||||
style: theme.textTheme.bodySmall?.copyWith(
|
|
||||||
color: theme.colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
for (final MapEntry(:key, :value) in sickLockerLabels.entries)
|
for (final MapEntry(:key, :value) in sickLockerLabels.entries)
|
||||||
SwitchListTile(
|
SwitchListTile(
|
||||||
key: ValueKey<String>('keep-$key'),
|
key: ValueKey<String>('keep-$key'),
|
||||||
contentPadding: EdgeInsets.zero,
|
contentPadding: EdgeInsets.zero,
|
||||||
title: Text(value),
|
title: Icon(sickLockerIcons[key], semanticLabel: value),
|
||||||
value: _keep.contains(key),
|
value: _keep.contains(key),
|
||||||
onChanged: (on) =>
|
onChanged: (on) =>
|
||||||
setState(() => on ? _keep.add(key) : _keep.remove(key)),
|
setState(() => on ? _keep.add(key) : _keep.remove(key)),
|
||||||
@ -159,21 +167,27 @@ class _SickDaySheetState extends State<SickDaySheet> {
|
|||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
if (widget.isSick) ...[
|
if (widget.isSick) ...[
|
||||||
FilledButton(
|
FilledButton(
|
||||||
|
key: const ValueKey<String>('sick-save'),
|
||||||
onPressed: () => _close(SickSheetAction.save),
|
onPressed: () => _close(SickSheetAction.save),
|
||||||
child: const Text('Save'),
|
child: const Icon(Icons.check, semanticLabel: 'Save'),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
TextButton(
|
TextButton(
|
||||||
style: TextButton.styleFrom(
|
style: TextButton.styleFrom(
|
||||||
foregroundColor: theme.colorScheme.error,
|
foregroundColor: theme.colorScheme.error,
|
||||||
),
|
),
|
||||||
|
key: const ValueKey<String>('sick-clear'),
|
||||||
onPressed: () => _close(SickSheetAction.clear),
|
onPressed: () => _close(SickSheetAction.clear),
|
||||||
child: const Text('Clear sick day'),
|
child: const Icon(
|
||||||
|
Icons.delete_outline,
|
||||||
|
semanticLabel: 'Clear sick day',
|
||||||
|
),
|
||||||
),
|
),
|
||||||
] else
|
] else
|
||||||
FilledButton(
|
FilledButton(
|
||||||
|
key: const ValueKey<String>('sick-mark'),
|
||||||
onPressed: () => _close(SickSheetAction.mark),
|
onPressed: () => _close(SickSheetAction.mark),
|
||||||
child: const Text('Mark sick'),
|
child: const Icon(Icons.sick, semanticLabel: 'Mark sick'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|||||||
@ -1,8 +1,9 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/screens/day_calendar.dart';
|
import 'package:wake_alarm_sync/screens/day_calendar.dart';
|
||||||
import 'package:wake_alarm_sync/screens/sick_day_sheet.dart';
|
import 'package:wake_alarm_sync/screens/sick_day_sheet.dart';
|
||||||
import 'package:wake_alarm_sync/services/free_day_pool.dart';
|
import 'package:wake_alarm_sync/services/sick_day_keep.dart';
|
||||||
import 'package:wake_alarm_sync/ui/theme.dart';
|
import 'package:wake_alarm_sync/ui/cues.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/dashed_slot.dart';
|
||||||
|
|
||||||
/// The sick-day picker's body: what a sick day does, the status line, the
|
/// The sick-day picker's body: what a sick day does, the status line, the
|
||||||
/// month calendar and the sick days still ahead.
|
/// month calendar and the sick days still ahead.
|
||||||
@ -16,6 +17,7 @@ class SickDaysBody extends StatelessWidget {
|
|||||||
required this.upcoming,
|
required this.upcoming,
|
||||||
required this.status,
|
required this.status,
|
||||||
required this.cache,
|
required this.cache,
|
||||||
|
required this.cacheRead,
|
||||||
required this.refused,
|
required this.refused,
|
||||||
required this.calendar,
|
required this.calendar,
|
||||||
required this.keptOf,
|
required this.keptOf,
|
||||||
@ -34,74 +36,112 @@ class SickDaysBody extends StatelessWidget {
|
|||||||
/// The status line; may be a raw `Error: …`.
|
/// The status line; may be a raw `Error: …`.
|
||||||
final String status;
|
final String status;
|
||||||
|
|
||||||
/// The native ring-path cache, read back (`Alarm cache: …`).
|
/// The native ring-path cache, read back (list of ISO
|
||||||
final String cache;
|
/// dates or null for unreadable).
|
||||||
|
final List<String>? cache;
|
||||||
|
|
||||||
|
/// Whether the cache has been read at least once.
|
||||||
|
final bool cacheRead;
|
||||||
|
|
||||||
/// Whether [status] is a refused tap, drawn like an error.
|
/// Whether [status] is a refused tap, drawn like an error.
|
||||||
final bool refused;
|
final bool refused;
|
||||||
|
|
||||||
static const _weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
|
String _toDdMmYyyy(DateTime day) {
|
||||||
|
final d = day.day.toString().padLeft(2, '0');
|
||||||
String _label(DateTime day) =>
|
final m = day.month.toString().padLeft(2, '0');
|
||||||
'${_weekdays[day.weekday - 1]} ${FreeDayPool.toIso(day)}';
|
return '$d.$m.${day.year}';
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
final muted = theme.colorScheme.onSurfaceVariant;
|
|
||||||
final statusColors = theme.extension<AppStatusColors>()!;
|
|
||||||
final failed = refused || status.contains('Error');
|
final failed = refused || status.contains('Error');
|
||||||
return SafeArea(
|
return SafeArea(
|
||||||
child: ListView(
|
child: ListView(
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(16),
|
||||||
children: [
|
children: [
|
||||||
Text(
|
|
||||||
'Tap a day to mark it sick and choose which lockers still '
|
|
||||||
'apply; tap a sick day to change them or clear it. Today or '
|
|
||||||
'later only. No limit and no reason needed.',
|
|
||||||
style: theme.textTheme.bodyMedium,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Text(
|
|
||||||
'On a sick day every locker left off stands down: no alarm, no '
|
|
||||||
'lock, and work left undone is dropped rather than carried '
|
|
||||||
'forward. A locker switched on behaves as on a normal day; a dot '
|
|
||||||
'marks a sick day that keeps one.',
|
|
||||||
style: theme.textTheme.bodySmall?.copyWith(color: muted),
|
|
||||||
),
|
|
||||||
if (status.isNotEmpty) ...[
|
if (status.isNotEmpty) ...[
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Text(
|
StatusCue(
|
||||||
status,
|
semanticLabel: status,
|
||||||
maxLines: 4,
|
kind: failed ? CueKind.error : null,
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
style: TextStyle(
|
|
||||||
color: failed ? theme.colorScheme.error : statusColors.success,
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
if (cache.isNotEmpty) ...[
|
if (cacheRead) ...[
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Text(cache, style: TextStyle(color: muted)),
|
Row(
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.memory,
|
||||||
|
size: 16,
|
||||||
|
semanticLabel: _cacheSemanticLabel,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
_buildCacheContent(theme),
|
||||||
|
],
|
||||||
|
),
|
||||||
],
|
],
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
calendar,
|
calendar,
|
||||||
const SizedBox(height: 24),
|
const SizedBox(height: 24),
|
||||||
Text('Marked sick', style: theme.textTheme.titleMedium),
|
const Row(
|
||||||
|
children: [Icon(Icons.sick_outlined, semanticLabel: 'Marked sick')],
|
||||||
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
if (upcoming.isEmpty)
|
if (upcoming.isEmpty)
|
||||||
Text('None ahead.', style: TextStyle(color: muted)),
|
const SpokenLabel(
|
||||||
|
semanticLabel: 'None ahead.',
|
||||||
|
child: DashedSlot(),
|
||||||
|
),
|
||||||
for (final day in upcoming)
|
for (final day in upcoming)
|
||||||
ListTile(
|
ListTile(
|
||||||
contentPadding: EdgeInsets.zero,
|
contentPadding: EdgeInsets.zero,
|
||||||
title: Text(_label(day)),
|
title: Text(_toDdMmYyyy(day)),
|
||||||
subtitle: switch (keptLabel(keptOf(day))) {
|
subtitle: _keptIcons(keptOf(day)),
|
||||||
'' => null,
|
|
||||||
final kept => Text('Kept: $kept'),
|
|
||||||
},
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String get _cacheSemanticLabel {
|
||||||
|
if (cache == null) return 'Alarm cache: unreadable';
|
||||||
|
if (cache!.isEmpty) return 'Alarm cache: none';
|
||||||
|
return 'Alarm cache: ${cache!.join(', ')}';
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildCacheContent(ThemeData theme) {
|
||||||
|
if (cache == null) {
|
||||||
|
return Icon(
|
||||||
|
Icons.error_outline,
|
||||||
|
color: theme.colorScheme.error,
|
||||||
|
size: 16,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (cache!.isEmpty) {
|
||||||
|
return Icon(
|
||||||
|
Icons.check,
|
||||||
|
size: 16,
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return Text(
|
||||||
|
cache!.join(', '),
|
||||||
|
style: TextStyle(color: theme.colorScheme.onSurfaceVariant),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget? _keptIcons(Set<String> kept) {
|
||||||
|
if (kept.isEmpty) return null;
|
||||||
|
return Row(
|
||||||
|
children: [
|
||||||
|
for (final locker in SickLocker.all)
|
||||||
|
if (kept.contains(locker))
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(right: 4),
|
||||||
|
child: Icon(sickLockerIcons[locker], size: 16),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/screens/day_calendar.dart';
|
import 'package:wake_alarm_sync/screens/day_calendar.dart';
|
||||||
import 'package:wake_alarm_sync/screens/sick_day_sheet.dart';
|
import 'package:wake_alarm_sync/screens/sick_day_sheet.dart';
|
||||||
import 'package:wake_alarm_sync/screens/sick_days_body.dart';
|
import 'package:wake_alarm_sync/screens/sick_days_body.dart';
|
||||||
@ -9,6 +9,7 @@ import 'package:wake_alarm_sync/services/free_day_pool.dart';
|
|||||||
import 'package:wake_alarm_sync/services/free_day_sync.dart';
|
import 'package:wake_alarm_sync/services/free_day_sync.dart';
|
||||||
import 'package:wake_alarm_sync/services/sick_day_pool.dart';
|
import 'package:wake_alarm_sync/services/sick_day_pool.dart';
|
||||||
import 'package:wake_alarm_sync/services/sick_day_sync.dart';
|
import 'package:wake_alarm_sync/services/sick_day_sync.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/cues.dart';
|
||||||
import 'package:wake_alarm_sync/ui/theme.dart';
|
import 'package:wake_alarm_sync/ui/theme.dart';
|
||||||
|
|
||||||
/// The phone's picker for the shared sick-day pool (`~/src/utils/sickdays`).
|
/// The phone's picker for the shared sick-day pool (`~/src/utils/sickdays`).
|
||||||
@ -68,7 +69,8 @@ class _SickDaysScreenState extends State<SickDaysScreen> {
|
|||||||
bool _refused = false;
|
bool _refused = false;
|
||||||
|
|
||||||
/// What the native ring-path cache holds, read back over the channel.
|
/// What the native ring-path cache holds, read back over the channel.
|
||||||
String _cache = '';
|
List<String>? _cache;
|
||||||
|
bool _cacheRead = false;
|
||||||
|
|
||||||
late DateTime _month = DateTime(_today.year, _today.month);
|
late DateTime _month = DateTime(_today.year, _today.month);
|
||||||
|
|
||||||
@ -112,12 +114,8 @@ class _SickDaysScreenState extends State<SickDaysScreen> {
|
|||||||
}
|
}
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() {
|
setState(() {
|
||||||
_cache =
|
_cache = dates;
|
||||||
'Alarm cache: ${switch (dates) {
|
_cacheRead = true;
|
||||||
null => 'unreadable',
|
|
||||||
[] => 'none',
|
|
||||||
final d => d.join(', '),
|
|
||||||
}}';
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -189,23 +187,20 @@ class _SickDaysScreenState extends State<SickDaysScreen> {
|
|||||||
final marks = Theme.of(context).extension<DayMarkColors>()!;
|
final marks = Theme.of(context).extension<DayMarkColors>()!;
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: const Row(
|
title: const Row(children: [Icon(Icons.sick_outlined)]),
|
||||||
children: [
|
|
||||||
Icon(Icons.sick_outlined),
|
|
||||||
SizedBox(width: 8),
|
|
||||||
Text('Sick days'),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
actions: [
|
actions: [
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: const Icon(Icons.sync),
|
icon: const Icon(Icons.sync, semanticLabel: 'Sync now'),
|
||||||
tooltip: 'Sync now',
|
|
||||||
onPressed: _busy ? null : () => unawaited(_sync()),
|
onPressed: _busy ? null : () => unawaited(_sync()),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
body: pool == null
|
body: pool == null
|
||||||
? Center(child: Text(_status.isEmpty ? 'Loading…' : _status))
|
? Center(
|
||||||
|
child: _status.isEmpty
|
||||||
|
? const CircularProgressIndicator()
|
||||||
|
: StatusCue(semanticLabel: _status),
|
||||||
|
)
|
||||||
: SickDaysBody(
|
: SickDaysBody(
|
||||||
upcoming: [
|
upcoming: [
|
||||||
for (final day in pool.sickDays())
|
for (final day in pool.sickDays())
|
||||||
@ -214,6 +209,7 @@ class _SickDaysScreenState extends State<SickDaysScreen> {
|
|||||||
keptOf: pool.keptLockers,
|
keptOf: pool.keptLockers,
|
||||||
status: _status,
|
status: _status,
|
||||||
cache: _cache,
|
cache: _cache,
|
||||||
|
cacheRead: _cacheRead,
|
||||||
refused: _refused,
|
refused: _refused,
|
||||||
calendar: DayCalendar(
|
calendar: DayCalendar(
|
||||||
month: _month,
|
month: _month,
|
||||||
|
|||||||
@ -1,13 +1,15 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/screens/escape_dialog.dart';
|
import 'package:wake_alarm_sync/screens/escape_dialog.dart';
|
||||||
|
import 'package:wake_alarm_sync/screens/stakes_marks.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/enforcement_bridge.dart';
|
import 'package:wake_alarm_sync/services/enforcement_bridge.dart';
|
||||||
import 'package:wake_alarm_sync/services/enforcement_state.dart';
|
import 'package:wake_alarm_sync/services/enforcement_state.dart';
|
||||||
import 'package:wake_alarm_sync/services/escape_hatch.dart';
|
import 'package:wake_alarm_sync/services/escape_hatch.dart';
|
||||||
import 'package:wake_alarm_sync/services/today_stakes.dart';
|
import 'package:wake_alarm_sync/services/today_stakes.dart';
|
||||||
import 'package:wake_alarm_sync/ui/theme.dart';
|
import 'package:wake_alarm_sync/ui/cues.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/dashed_slot.dart';
|
||||||
|
|
||||||
/// Today's stakes in plain words, anything already in force, the streak,
|
/// Today's stakes in plain words, anything already in force, the streak,
|
||||||
/// and the escape hatch while it lasts.
|
/// and the escape hatch while it lasts.
|
||||||
@ -25,6 +27,7 @@ class StakesCard extends StatefulWidget {
|
|||||||
this.nextAlarm,
|
this.nextAlarm,
|
||||||
this.onEscaped,
|
this.onEscaped,
|
||||||
this.busy = false,
|
this.busy = false,
|
||||||
|
this.emptyText,
|
||||||
});
|
});
|
||||||
|
|
||||||
/// Native stick reader; defaults to the real channel.
|
/// Native stick reader; defaults to the real channel.
|
||||||
@ -45,6 +48,10 @@ class StakesCard extends StatefulWidget {
|
|||||||
/// Disables the escape while the screen is syncing.
|
/// Disables the escape while the screen is syncing.
|
||||||
final bool busy;
|
final bool busy;
|
||||||
|
|
||||||
|
/// Shown once loading found no native stick, instead of nothing. The home
|
||||||
|
/// screen opens this card from a tile, so a blank sheet needs a sentence.
|
||||||
|
final String? emptyText;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<StakesCard> createState() => _StakesCardState();
|
State<StakesCard> createState() => _StakesCardState();
|
||||||
}
|
}
|
||||||
@ -56,6 +63,8 @@ class _StakesCardState extends State<StakesCard> {
|
|||||||
EnforcementState? _state;
|
EnforcementState? _state;
|
||||||
AlarmTime? _next;
|
AlarmTime? _next;
|
||||||
String _message = '';
|
String _message = '';
|
||||||
|
bool _excused = false;
|
||||||
|
bool _loaded = false;
|
||||||
|
|
||||||
DateTime _now() => (widget.now ?? DateTime.now)();
|
DateTime _now() => (widget.now ?? DateTime.now)();
|
||||||
|
|
||||||
@ -78,6 +87,7 @@ class _StakesCardState extends State<StakesCard> {
|
|||||||
setState(() {
|
setState(() {
|
||||||
_state = state;
|
_state = state;
|
||||||
_next = next;
|
_next = next;
|
||||||
|
_loaded = true;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -95,6 +105,7 @@ class _StakesCardState extends State<StakesCard> {
|
|||||||
if (reason == null) return;
|
if (reason == null) return;
|
||||||
final ok = await _hatch.use(reason);
|
final ok = await _hatch.use(reason);
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
|
_excused = ok;
|
||||||
setState(
|
setState(
|
||||||
() => _message = ok
|
() => _message = ok
|
||||||
? 'Excused — lockdown lifted, publishing to the PC.'
|
? 'Excused — lockdown lifted, publishing to the PC.'
|
||||||
@ -107,11 +118,14 @@ class _StakesCardState extends State<StakesCard> {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final state = _state;
|
final state = _state;
|
||||||
if (state == null) return const SizedBox.shrink();
|
final empty = widget.emptyText;
|
||||||
|
if (state == null) {
|
||||||
|
return _loaded && empty != null
|
||||||
|
? SpokenLabel(semanticLabel: empty, child: const DashedSlot())
|
||||||
|
: const SizedBox.shrink();
|
||||||
|
}
|
||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
final warning = theme.extension<AppStatusColors>()?.warning;
|
|
||||||
final view = describeStakes(now: _now(), state: state, nextAlarm: _next);
|
final view = describeStakes(now: _now(), state: state, nextAlarm: _next);
|
||||||
final body = theme.textTheme.bodyMedium;
|
|
||||||
return Card(
|
return Card(
|
||||||
color: theme.colorScheme.surfaceContainerHigh,
|
color: theme.colorScheme.surfaceContainerHigh,
|
||||||
margin: EdgeInsets.zero,
|
margin: EdgeInsets.zero,
|
||||||
@ -120,37 +134,25 @@ class _StakesCardState extends State<StakesCard> {
|
|||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
Text(view.title, style: theme.textTheme.titleMedium),
|
StakesMarks(view: view),
|
||||||
const SizedBox(height: 8),
|
|
||||||
for (final line in view.stakes)
|
|
||||||
Padding(
|
|
||||||
padding: const EdgeInsets.symmetric(vertical: 2),
|
|
||||||
child: Text(line, style: body),
|
|
||||||
),
|
|
||||||
for (final line in view.pending)
|
|
||||||
Padding(
|
|
||||||
padding: const EdgeInsets.symmetric(vertical: 2),
|
|
||||||
child: Text(line, style: body?.copyWith(color: warning)),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Text(
|
|
||||||
view.streak,
|
|
||||||
style: theme.textTheme.bodySmall?.copyWith(
|
|
||||||
color: theme.colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (_message.isNotEmpty) ...[
|
if (_message.isNotEmpty) ...[
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Text(_message, style: body),
|
StatusCue(
|
||||||
|
semanticLabel: _message,
|
||||||
|
kind: _excused ? CueKind.ok : CueKind.error,
|
||||||
|
),
|
||||||
],
|
],
|
||||||
if (_hatch.isOpen) ...[
|
if (_hatch.isOpen) ...[
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Align(
|
Align(
|
||||||
alignment: Alignment.centerLeft,
|
alignment: Alignment.centerLeft,
|
||||||
child: TextButton.icon(
|
child: IconButton(
|
||||||
|
key: const Key('stakes-escape'),
|
||||||
onPressed: widget.busy ? null : () => unawaited(_escape()),
|
onPressed: widget.busy ? null : () => unawaited(_escape()),
|
||||||
icon: const Icon(Icons.bug_report_outlined),
|
icon: const Icon(
|
||||||
label: const Text('That was a bug'),
|
Icons.bug_report_outlined,
|
||||||
|
semanticLabel: 'That was a bug',
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
|||||||
155
phone_app/lib/screens/stakes_marks.dart
Normal file
155
phone_app/lib/screens/stakes_marks.dart
Normal file
@ -0,0 +1,155 @@
|
|||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/today_stakes.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/spoken_label.dart';
|
||||||
|
import 'package:wake_alarm_sync/ui/theme.dart';
|
||||||
|
|
||||||
|
/// The stakes of [view] as glyph rows: times and dates are the only
|
||||||
|
/// characters painted; each row speaks its sentence from [StakesView].
|
||||||
|
class StakesMarks extends StatelessWidget {
|
||||||
|
/// Creates the rows for [view].
|
||||||
|
const StakesMarks({required this.view, super.key});
|
||||||
|
|
||||||
|
/// The stakes to draw.
|
||||||
|
final StakesView view;
|
||||||
|
|
||||||
|
static String _dm(DateTime d) =>
|
||||||
|
'${d.day.toString().padLeft(2, '0')}.'
|
||||||
|
'${d.month.toString().padLeft(2, '0')}';
|
||||||
|
|
||||||
|
static String _hm(int h, int m) =>
|
||||||
|
'${h.toString().padLeft(2, '0')}:${m.toString().padLeft(2, '0')}';
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final warning =
|
||||||
|
theme.extension<AppStatusColors>()?.warning ?? theme.colorScheme.error;
|
||||||
|
final kindIcon = switch (view.kind) {
|
||||||
|
StakesDayKind.free => Icons.event_available,
|
||||||
|
StakesDayKind.sick => Icons.sick_outlined,
|
||||||
|
StakesDayKind.stick => Icons.gavel_outlined,
|
||||||
|
StakesDayKind.carrot => Icons.emoji_events_outlined,
|
||||||
|
};
|
||||||
|
final rows = <Widget>[
|
||||||
|
_row('title', view.title, <Widget>[
|
||||||
|
Tooltip(
|
||||||
|
message: 'Stakes',
|
||||||
|
child: Icon(kindIcon, color: theme.colorScheme.primary),
|
||||||
|
),
|
||||||
|
Icon(view.isToday ? Icons.today : Icons.event, size: 18),
|
||||||
|
Text(_dm(view.day), style: theme.textTheme.titleMedium),
|
||||||
|
]),
|
||||||
|
];
|
||||||
|
final words = view.stakes;
|
||||||
|
final dismissBy = view.dismissBy;
|
||||||
|
final lock = view.lockThrough;
|
||||||
|
final finishBy = view.finishBy;
|
||||||
|
final open = view.pcOpenUntil;
|
||||||
|
final ring = view.pcRingAt;
|
||||||
|
if (dismissBy != null && lock != null) {
|
||||||
|
rows.add(
|
||||||
|
_row('stick', words.first, <Widget>[
|
||||||
|
const Tooltip(message: 'Alarm', child: Icon(Icons.alarm)),
|
||||||
|
Text(hhmm(dismissBy)),
|
||||||
|
const Icon(Icons.arrow_forward, size: 16),
|
||||||
|
const Tooltip(message: 'Lock', child: Icon(Icons.lock_outline)),
|
||||||
|
Text(_dm(lock)),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
} else if (finishBy != null && open != null) {
|
||||||
|
rows.add(
|
||||||
|
_row('carrot', words.first, <Widget>[
|
||||||
|
const Tooltip(message: 'Finish', child: Icon(Icons.flag_outlined)),
|
||||||
|
Text(hhmm(finishBy)),
|
||||||
|
const Icon(Icons.arrow_forward, size: 16),
|
||||||
|
const Tooltip(message: 'PC', child: Icon(Icons.computer)),
|
||||||
|
Text(_hm(open.hour, open.minute)),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
} else if (view.kind != StakesDayKind.free &&
|
||||||
|
view.kind != StakesDayKind.sick) {
|
||||||
|
rows.add(
|
||||||
|
_row('unarmed', words.first, const <Widget>[
|
||||||
|
Tooltip(message: 'Off', child: Icon(Icons.alarm_off)),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (ring != null) {
|
||||||
|
rows.add(
|
||||||
|
_row('pc-ring', words.last, <Widget>[
|
||||||
|
const Tooltip(message: 'PC', child: Icon(Icons.computer)),
|
||||||
|
const Tooltip(
|
||||||
|
message: 'Ring',
|
||||||
|
child: Icon(Icons.notifications_active_outlined),
|
||||||
|
),
|
||||||
|
Text(hhmm(ring)),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
rows
|
||||||
|
..addAll(_pending(warning))
|
||||||
|
..add(
|
||||||
|
_row('streak', view.streak, <Widget>[
|
||||||
|
Icon(
|
||||||
|
Icons.local_fire_department_outlined,
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
Text('${view.streakCount}'),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: rows,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The rows for what is already in force, in `view.pending`'s order.
|
||||||
|
List<Widget> _pending(Color warning) {
|
||||||
|
final spoken = view.pending.iterator;
|
||||||
|
String next() => spoken.moveNext() ? spoken.current : '';
|
||||||
|
final locked = view.lockedThrough;
|
||||||
|
final style = TextStyle(color: warning);
|
||||||
|
return <Widget>[
|
||||||
|
if (view.escapedToday)
|
||||||
|
_row('escaped', next(), <Widget>[
|
||||||
|
Tooltip(
|
||||||
|
message: 'Escaped',
|
||||||
|
child: Icon(Icons.bug_report_outlined, color: warning),
|
||||||
|
),
|
||||||
|
Icon(Icons.check, color: warning),
|
||||||
|
]),
|
||||||
|
if (locked != null)
|
||||||
|
_row('locked', next(), <Widget>[
|
||||||
|
Tooltip(
|
||||||
|
message: 'Lock',
|
||||||
|
child: Icon(Icons.lock_outline, color: warning),
|
||||||
|
),
|
||||||
|
Text(_dm(locked), style: style),
|
||||||
|
]),
|
||||||
|
if (view.missedToday)
|
||||||
|
_row('missed', next(), <Widget>[
|
||||||
|
Tooltip(
|
||||||
|
message: 'Missed',
|
||||||
|
child: Icon(Icons.close, color: warning),
|
||||||
|
),
|
||||||
|
Tooltip(
|
||||||
|
message: 'PC',
|
||||||
|
child: Icon(Icons.computer, color: warning),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
static Widget _row(String what, String words, List<Widget> marks) => Padding(
|
||||||
|
key: ValueKey<String>('stakes-$what'),
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||||
|
child: SpokenLabel(
|
||||||
|
semanticLabel: words,
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
for (final mark in marks) ...<Widget>[mark, const SizedBox(width: 8)],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -37,7 +37,9 @@ class AlarmArming {
|
|||||||
///
|
///
|
||||||
/// android_intent_plus v5 uses startActivityForResult and the Clock app
|
/// android_intent_plus v5 uses startActivityForResult and the Clock app
|
||||||
/// never sends a result, so this times out after 3s rather than hang.
|
/// never sends a result, so this times out after 3s rather than hang.
|
||||||
Future<void> registerWithClockApp(int hour, int minute) async {
|
///
|
||||||
|
/// Returns true only if the launch completed before the timeout.
|
||||||
|
Future<bool> registerWithClockApp(int hour, int minute) async {
|
||||||
final intent = AndroidIntent(
|
final intent = AndroidIntent(
|
||||||
action: 'android.intent.action.SET_ALARM',
|
action: 'android.intent.action.SET_ALARM',
|
||||||
arguments: <String, Object>{
|
arguments: <String, Object>{
|
||||||
@ -47,6 +49,11 @@ class AlarmArming {
|
|||||||
'android.intent.extra.alarm.MESSAGE': 'Wake Alarm',
|
'android.intent.extra.alarm.MESSAGE': 'Wake Alarm',
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
await intent.launch().timeout(const Duration(seconds: 3), onTimeout: () {});
|
var completed = true;
|
||||||
|
await intent.launch().timeout(
|
||||||
|
const Duration(seconds: 3),
|
||||||
|
onTimeout: () => completed = false,
|
||||||
|
);
|
||||||
|
return completed;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -53,10 +53,21 @@ class AlarmPublisher {
|
|||||||
await applySyncedSettings(service);
|
await applySyncedSettings(service);
|
||||||
final problem = await arming.arm(hour, minute);
|
final problem = await arming.arm(hour, minute);
|
||||||
if (problem != null) return problem;
|
if (problem != null) return problem;
|
||||||
await arming.registerWithClockApp(hour, minute);
|
final inClock = await arming.registerWithClockApp(hour, minute);
|
||||||
return 'Synced to PC ✓';
|
return syncedStatus(hour, minute, inClock: inClock);
|
||||||
} on Exception catch (e) {
|
} on Exception catch (e) {
|
||||||
return 'Error: $e';
|
return 'Error: $e';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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
|
||||||
|
/// never claims it. Only reached after `arm()` succeeded.
|
||||||
|
String syncedStatus(int hour, int minute, {required bool inClock}) {
|
||||||
|
final time =
|
||||||
|
'${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;
|
||||||
|
}
|
||||||
|
|||||||
@ -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`.
|
||||||
///
|
///
|
||||||
|
|||||||
59
phone_app/lib/services/alarm_sync_e2e.dart
Normal file
59
phone_app/lib/services/alarm_sync_e2e.dart
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
/// End-to-end encryption of the alarm record this app publishes.
|
||||||
|
///
|
||||||
|
/// The record (alarm time, tags, home location, morning sessions, weigh-ins,
|
||||||
|
/// enforcement fields) is sealed with a key derived from the shared
|
||||||
|
/// crdt-sync passphrase in the OS keystore, under
|
||||||
|
/// `wake-alarm-sync/devices-e2e`; Firebase and the GitHub mirror only see
|
||||||
|
/// the record id and clocks. The PC (`wake_alarm/_sync_transport.py`) and
|
||||||
|
/// diet_guard (its weigh-in ingest) read the same layout.
|
||||||
|
///
|
||||||
|
/// Fail closed: without a usable key nothing is pulled or pushed. The old
|
||||||
|
/// plaintext prefix is copied over on open and never written or deleted.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
|
||||||
|
show openEncryptedStoreFromKeystore;
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
|
||||||
|
/// The plaintext prefix every pre-E2E build wrote; only the copy reads it.
|
||||||
|
const legacyAlarmPrefix = 'wake-alarm-sync/devices';
|
||||||
|
|
||||||
|
/// Where the alarm record now lives, and where its revisions go.
|
||||||
|
final E2eLayout alarmLayout = E2eLayout.of(legacyAlarmPrefix);
|
||||||
|
|
||||||
|
/// Argon2id cost for a header this device creates; only tests lower it.
|
||||||
|
@visibleForTesting
|
||||||
|
Argon2Params e2eArgon2Params = Argon2Params.recommended;
|
||||||
|
|
||||||
|
/// Whether the last open found no usable key, for the lock button.
|
||||||
|
final ValueNotifier<bool> alarmSyncLocked = ValueNotifier<bool>(false);
|
||||||
|
|
||||||
|
/// Thrown instead of syncing when end-to-end encryption has no usable key.
|
||||||
|
class SyncLockedException implements Exception {
|
||||||
|
/// Creates the exception for [reason].
|
||||||
|
const SyncLockedException(this.reason);
|
||||||
|
|
||||||
|
/// Why the store is locked.
|
||||||
|
final E2eLockReason reason;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => 'sync locked (${reason.name})';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The encrypted view of [backend], the outermost store (above the mirror).
|
||||||
|
///
|
||||||
|
/// Throws [SyncLockedException] when locked, so no caller can fall through
|
||||||
|
/// to a plaintext push.
|
||||||
|
Future<RemoteStore> openAlarmStore(RemoteStore backend) async {
|
||||||
|
final state = await openEncryptedStoreFromKeystore(
|
||||||
|
store: backend,
|
||||||
|
oldPrefix: legacyAlarmPrefix,
|
||||||
|
params: e2eArgon2Params,
|
||||||
|
);
|
||||||
|
alarmSyncLocked.value = state is! E2eReady;
|
||||||
|
if (state is E2eReady) return state.store;
|
||||||
|
throw SyncLockedException(
|
||||||
|
state is E2eLocked ? state.reason : E2eLockReason.badHeader,
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -7,6 +7,7 @@ import 'package:path/path.dart' as p;
|
|||||||
import 'package:path_provider/path_provider.dart';
|
import 'package:path_provider/path_provider.dart';
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
import 'package:uuid/uuid.dart';
|
import 'package:uuid/uuid.dart';
|
||||||
|
import 'package:wake_alarm_sync/services/alarm_sync_e2e.dart';
|
||||||
import 'package:wake_alarm_sync/services/firebase_backend.dart';
|
import 'package:wake_alarm_sync/services/firebase_backend.dart';
|
||||||
|
|
||||||
/// The alarm time this device holds, as read from or written to the store.
|
/// The alarm time this device holds, as read from or written to the store.
|
||||||
@ -17,7 +18,8 @@ typedef Alarm = ({int hour, int minute});
|
|||||||
///
|
///
|
||||||
/// The phone is the **sole writer**: it stores the chosen alarm locally in a
|
/// The phone is the **sole writer**: it stores the chosen alarm locally in a
|
||||||
/// [LogStore] (one HLC-stamped [Record], id [_recordId]) and pushes that log
|
/// [LogStore] (one HLC-stamped [Record], id [_recordId]) and pushes that log
|
||||||
/// to `wake-alarm-sync/devices/<deviceId>/alarm.json` — Firebase first,
|
/// to `wake-alarm-sync/devices-e2e/<deviceId>/alarm.json`, end-to-end
|
||||||
|
/// encrypted (`alarm_sync_e2e.dart`) — Firebase first,
|
||||||
/// mirrored to the private `kuhyx/syncs` repo during the cutover (see
|
/// mirrored to the private `kuhyx/syncs` repo during the cutover (see
|
||||||
/// [syncBackend]). The path is deliberately identical on both backends, so
|
/// [syncBackend]). The path is deliberately identical on both backends, so
|
||||||
/// only the transport differs.
|
/// only the transport differs.
|
||||||
@ -162,11 +164,17 @@ class AlarmSyncService {
|
|||||||
/// The pull is what brings the tags and home location back to a fresh
|
/// The pull is what brings the tags and home location back to a fresh
|
||||||
/// install. The alarm time itself is unaffected: [setLocal] runs first on
|
/// install. The alarm time itself is unaffected: [setLocal] runs first on
|
||||||
/// every publish, so the local time is always the newest and wins.
|
/// every publish, so the local time is always the newest and wins.
|
||||||
|
///
|
||||||
|
/// Everything goes through the end-to-end encrypted view of [client]
|
||||||
|
/// (`alarm_sync_e2e.dart`); a locked device throws [SyncLockedException]
|
||||||
|
/// before reading or writing anything.
|
||||||
Future<void> pushWith(RemoteStore client) async {
|
Future<void> pushWith(RemoteStore client) async {
|
||||||
|
final sealed = await openAlarmStore(client);
|
||||||
final merged = await syncLog(
|
final merged = await syncLog(
|
||||||
client: client,
|
client: sealed,
|
||||||
deviceId: deviceId,
|
deviceId: deviceId,
|
||||||
pathPrefix: 'wake-alarm-sync/devices',
|
pathPrefix: alarmLayout.prefix,
|
||||||
|
revsPath: alarmLayout.revsPath,
|
||||||
filename: 'alarm.json',
|
filename: 'alarm.json',
|
||||||
localLog: _store.snapshot(),
|
localLog: _store.snapshot(),
|
||||||
encode: logToJson,
|
encode: logToJson,
|
||||||
|
|||||||
@ -178,7 +178,7 @@ class ChallengeGenerator {
|
|||||||
final backwards = word.split('').reversed.join();
|
final backwards = word.split('').reversed.join();
|
||||||
return Challenge(
|
return Challenge(
|
||||||
kind: ChallengeKind.reverse,
|
kind: ChallengeKind.reverse,
|
||||||
display: 'Type this word backwards:\n$word',
|
display: word,
|
||||||
answer: backwards,
|
answer: backwards,
|
||||||
hint: 'Type the word backwards',
|
hint: 'Type the word backwards',
|
||||||
);
|
);
|
||||||
|
|||||||
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,11 +0,0 @@
|
|||||||
/// Platform gate for the programmatic Google sign-in flow.
|
|
||||||
///
|
|
||||||
/// Conditional export because the answer differs per platform *and* because
|
|
||||||
/// asking the plugin directly is unsafe: `supportsAuthenticate()` throws
|
|
||||||
/// `UnimplementedError` where no implementation is registered -- an `Error`,
|
|
||||||
/// not an `Exception`, so it escapes an ordinary catch and would take down
|
|
||||||
/// the settings screen's `build()`.
|
|
||||||
library;
|
|
||||||
|
|
||||||
export 'google_platform_io.dart'
|
|
||||||
if (dart.library.js_interop) 'google_platform_web.dart';
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user