mirror of
https://github.com/kuhyx/wake-alarm.git
synced 2026-11-29 11:23:25 +01:00
Compare commits
No commits in common. "main" and "v1.0.0-build.291" have entirely different histories.
main
...
v1.0.0-bui
@ -1,2 +0,0 @@
|
|||||||
# 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
Normal file
62
.github/workflows/dependency-freshness.yml
vendored
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
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
|
||||||
8
.github/workflows/pre-commit.yml
vendored
8
.github/workflows/pre-commit.yml
vendored
@ -16,12 +16,18 @@ jobs:
|
|||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
|
- group: mypy
|
||||||
|
hooks: mypy
|
||||||
|
skip: ""
|
||||||
|
- group: pylint
|
||||||
|
hooks: pylint
|
||||||
|
skip: ""
|
||||||
# free-days-interop needs Flutter and the freedays venv; it runs as
|
# free-days-interop needs Flutter and the freedays venv; it runs as
|
||||||
# its own job in python-tests.yml, so skipping it here is not
|
# its own job in python-tests.yml, so skipping it here is not
|
||||||
# fail-open.
|
# fail-open.
|
||||||
- group: rest
|
- group: rest
|
||||||
hooks: ""
|
hooks: ""
|
||||||
skip: "free-days-interop,dependency-freshness"
|
skip: mypy,pylint,free-days-interop
|
||||||
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.50.1
|
flutter-version: 3.50.0
|
||||||
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.50.1
|
flutter-version: 3.50.0
|
||||||
channel: stable
|
channel: stable
|
||||||
cache: true
|
cache: true
|
||||||
|
|
||||||
|
|||||||
@ -24,6 +24,8 @@ repos:
|
|||||||
- id: check-merge-conflict
|
- id: check-merge-conflict
|
||||||
- id: detect-private-key
|
- id: detect-private-key
|
||||||
- id: debug-statements
|
- id: debug-statements
|
||||||
|
- id: name-tests-test
|
||||||
|
args: [--pytest-test-first]
|
||||||
- id: check-ast
|
- id: check-ast
|
||||||
- id: mixed-line-ending
|
- id: mixed-line-ending
|
||||||
args: [--fix=lf]
|
args: [--fix=lf]
|
||||||
@ -57,9 +59,74 @@ repos:
|
|||||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||||
rev: v0.15.2
|
rev: v0.15.2
|
||||||
hooks:
|
hooks:
|
||||||
|
- id: ruff
|
||||||
|
args: [--fix, --unsafe-fixes, --exit-non-zero-on-fix, --show-fixes]
|
||||||
|
types_or: [python, pyi]
|
||||||
- id: ruff-format
|
- id: ruff-format
|
||||||
types_or: [python, pyi]
|
types_or: [python, pyi]
|
||||||
|
|
||||||
|
- repo: https://github.com/pre-commit/mirrors-mypy
|
||||||
|
rev: v1.13.0
|
||||||
|
hooks:
|
||||||
|
- id: mypy
|
||||||
|
args:
|
||||||
|
- --ignore-missing-imports
|
||||||
|
- --no-error-summary
|
||||||
|
- --disable-error-code=no-untyped-def
|
||||||
|
- --disable-error-code=no-untyped-call
|
||||||
|
- --disable-error-code=var-annotated
|
||||||
|
- --disable-error-code=no-any-unimported
|
||||||
|
- --disable-error-code=type-arg
|
||||||
|
- --disable-error-code=no-any-return
|
||||||
|
- --disable-error-code=misc
|
||||||
|
- --disable-error-code=unused-ignore
|
||||||
|
- --disable-error-code=unreachable
|
||||||
|
- --disable-error-code=assignment
|
||||||
|
- --disable-error-code=no-redef
|
||||||
|
- --disable-error-code=attr-defined
|
||||||
|
- --disable-error-code=arg-type
|
||||||
|
- --disable-error-code=union-attr
|
||||||
|
- --disable-error-code=call-overload
|
||||||
|
- --disable-error-code=return-value
|
||||||
|
- --disable-error-code=redundant-cast
|
||||||
|
- --disable-error-code=empty-body
|
||||||
|
- --disable-error-code=list-item
|
||||||
|
|
||||||
|
- repo: https://github.com/pylint-dev/pylint
|
||||||
|
rev: v3.3.2
|
||||||
|
hooks:
|
||||||
|
- id: pylint
|
||||||
|
args:
|
||||||
|
- --rcfile=pyproject.toml
|
||||||
|
- --fail-under=10
|
||||||
|
- --jobs=4
|
||||||
|
additional_dependencies:
|
||||||
|
- pytest
|
||||||
|
# Kept in step with pyproject.toml: pip refuses two different
|
||||||
|
# direct URLs for one distribution, so any pin that drifts from
|
||||||
|
# the manifest becomes an unresolvable hook environment rather
|
||||||
|
# than merely an old one.
|
||||||
|
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.12.0#subdirectory=gatelock
|
||||||
|
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync
|
||||||
|
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.0#subdirectory=freedays
|
||||||
|
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.0#subdirectory=sickdays
|
||||||
|
# Test suites intentionally use patterns (protected-access, magic-value
|
||||||
|
# comparisons) that don't belong in the source-code 10/10 gate.
|
||||||
|
exclude: ^(\.venv/)|(^|/)(tests/|conftest\.py)
|
||||||
|
|
||||||
|
- repo: https://github.com/PyCQA/bandit
|
||||||
|
rev: 1.7.10
|
||||||
|
hooks:
|
||||||
|
- id: bandit
|
||||||
|
args:
|
||||||
|
- -c
|
||||||
|
- pyproject.toml
|
||||||
|
- --severity-level=high
|
||||||
|
- --confidence-level=medium
|
||||||
|
- --skip=B113
|
||||||
|
additional_dependencies: ["bandit[toml]"]
|
||||||
|
exclude: ^(tests/|.*test.*\.py$)
|
||||||
|
|
||||||
- repo: local
|
- repo: local
|
||||||
hooks:
|
hooks:
|
||||||
- id: ci-mirror
|
- id: ci-mirror
|
||||||
@ -71,6 +138,13 @@ repos:
|
|||||||
require_serial: true
|
require_serial: true
|
||||||
stages: [manual]
|
stages: [manual]
|
||||||
|
|
||||||
|
- repo: https://github.com/codespell-project/codespell
|
||||||
|
rev: v2.3.0
|
||||||
|
hooks:
|
||||||
|
- id: codespell
|
||||||
|
args:
|
||||||
|
- --skip=*.json,*.lock,.git,__pycache__,.venv
|
||||||
|
|
||||||
- repo: local
|
- repo: local
|
||||||
hooks:
|
hooks:
|
||||||
# Fails a commit that still points crdt_sync at a local path. Local
|
# Fails a commit that still points crdt_sync at a local path. Local
|
||||||
@ -90,6 +164,18 @@ repos:
|
|||||||
language: system
|
language: system
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
files: (phone_app/lib/services/free_day_pool\.dart|phone_app/test/free_day_interop_writer_test\.dart|scripts/free_days_interop/.*)$
|
files: (phone_app/lib/services/free_day_pool\.dart|phone_app/test/free_day_interop_writer_test\.dart|scripts/free_days_interop/.*)$
|
||||||
|
- id: shellcheck
|
||||||
|
name: shellcheck
|
||||||
|
entry: bash -c 'printf "%s\0" "$@" | xargs -0 -n 40 shellcheck --severity=warning' --
|
||||||
|
language: system
|
||||||
|
types: [shell]
|
||||||
|
# The shared 250-line cap. This repo used to run a local script with a
|
||||||
|
# higher limit under this same hook id, so it looked gated while letting
|
||||||
|
# through files every other repo rejects.
|
||||||
|
- id: file-length
|
||||||
|
name: file length <= 250 lines
|
||||||
|
entry: scripts/check_file_length.sh
|
||||||
|
language: system
|
||||||
|
|
||||||
# Four markdown namespaces (README / CLAUDE* / DOCS* / TODO*), plus the
|
# Four markdown namespaces (README / CLAUDE* / DOCS* / TODO*), plus the
|
||||||
# rule that a TODO carries "REMOVE ME AFTER FINISH" and nothing else may.
|
# rule that a TODO carries "REMOVE ME AFTER FINISH" and nothing else may.
|
||||||
|
|||||||
168
AGENTS.md
168
AGENTS.md
@ -15,10 +15,6 @@ 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)
|
||||||
|
|
||||||
@ -43,8 +39,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 only added two minutes of
|
shaken phone would count; on the normal path it was two minutes of ringing
|
||||||
ringing (dropped 2026-09-16).
|
nothing could shorten (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
|
||||||
@ -54,7 +50,8 @@ 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.
|
deleted, not merely unrouted: the ring screen is reached by walking in from
|
||||||
|
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
|
||||||
@ -72,10 +69,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: `AlarmReceiver` checks a native cache Dart rewrites after every
|
does not ring at all: `AlarmReceiver` checks a native cache Dart rewrites
|
||||||
mark/release/sync. Picker, cache, fail-closed contract: **`DOCS-free-days.md`**.
|
after every mark/release/sync. Picker, cache and its fail-closed contract:
|
||||||
Sick days (`~/src/utils/sickdays`, never a free day): phone + pre-alarm sync
|
**`DOCS-free-days.md`**. Sick days (`~/src/utils/sickdays`, never a free day):
|
||||||
**`DOCS-sick-days.md`**, PC **`DOCS-sick-days-pc.md`**.
|
phone + pre-alarm sync **`DOCS-sick-days.md`**, PC **`DOCS-wake-enforcement.md`**.
|
||||||
|
|
||||||
## Scheduling — a per-minute timer
|
## Scheduling — a per-minute timer
|
||||||
|
|
||||||
@ -91,69 +88,66 @@ 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. The latch replaced the alarm's own dismissal
|
relaunches it on top of the user. This latch replaced the alarm's own
|
||||||
record when `_alarm.py` was deleted; deleting one without adding the other is
|
dismissal record when `_alarm.py` was deleted — deleting one without adding the
|
||||||
a silent regression.
|
other is a silent regression, and that is exactly the trap.
|
||||||
|
|
||||||
`Persistent=true` plus the 60-minute window also replaced the deleted
|
`Persistent=true` plus the 60-minute window is also what 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_transport.py` fetches, `_sync_token.py`
|
`_sync.py` is the only reader.
|
||||||
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-e2e/<device-id>/alarm.json`, at
|
`wake-alarm-sync/devices/<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 constant
|
`devices/phone/`.** The phone's device id is migrating from the fixed
|
||||||
`phone` to a per-install uuid; a pinned reader would silently stop seeing
|
constant `phone` to a per-install uuid, and a pinned reader would silently
|
||||||
the alarm and fall back to 08:00, the wrong time. `_fetch_firebase_alarm()`
|
stop seeing the alarm and fall back to 08:00 — i.e. the wrong
|
||||||
lists `SYNC_DEVICES_PREFIX`, reads every device's `alarm.json`, and picks the
|
time. `_fetch_firebase_alarm()` lists `SYNC_DEVICES_PREFIX`, reads every
|
||||||
newest by the hour field's **HLC** (`device_id` breaks exact ties). A payload
|
device's `alarm.json`, and picks the newest by the hour field's **HLC**, with
|
||||||
that does not parse is skipped, never allowed to win. `SYNC_ALARM_PATH`
|
`device_id` breaking exact ties. A payload that does not parse is skipped
|
||||||
stays as a last-resort read for a backend that lists nothing.
|
rather than allowed to win. `SYNC_ALARM_PATH` remains as a last-resort read
|
||||||
- Payload parsing/ranking lives in `_alarm_payload.py` ("what did the phone
|
for a backend that lists nothing.
|
||||||
say"); `_sync.py` owns fetching, caching and fallback.
|
- Payload parsing/ranking lives in `_alarm_payload.py`: `_sync.py` owns
|
||||||
|
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 is
|
token is cached per app under `SYNC_APP_NAME` (`wake_alarm`). The config file
|
||||||
checked **before** anything is constructed, so an unconfigured machine never
|
is checked **before** anything is constructed, so an unconfigured machine
|
||||||
touches the network.
|
never 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's is no
|
else diet_guard's raw `~/.config/diet_guard/sync_token` (screen-locker is
|
||||||
longer read: Firebase-only since 2026-10-09). Needs `repo` scope; the repo is
|
Firebase-only since 2026-10-09; its `sync_token` is no longer read).
|
||||||
private, so a token without access returns **404, not 403**.
|
Needs `repo` scope — the repo is private, so a token without access returns
|
||||||
|
**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 cache
|
a dependency that failed to install must degrade the read to the GitHub path
|
||||||
rather than crash the per-minute trigger. Both backends need it (the GitHub
|
rather than crash the per-minute trigger. The GitHub path stays stdlib-only
|
||||||
mirror is read through `GitHubSyncClient`, encrypted too). Verify with
|
for that reason. Verify with `/usr/bin/python3 -c "import crdt_sync"`, not the
|
||||||
`/usr/bin/python3 -c "import crdt_sync"`, not the dev venv.
|
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: the cache is rewritten from the same
|
stamped it*, never on when we fetched — checking the fetch is trivially
|
||||||
stale record every few minutes, so `fetched_at` is always fresh. That is why
|
defeated, because the cache is rewritten from the same stale record every few
|
||||||
the winning HLC's instant is carried through `_alarm_payload` →
|
minutes, so `fetched_at` is always fresh however old the record behind it is.
|
||||||
|
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: the GitHub mirror has no per-field HLC, so treating "cannot tell"
|
trusted, not expired: the GitHub mirror has no per-field HLC, so treating
|
||||||
as "too old" would break that backend entirely.
|
"cannot tell" 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 loud persistent condition is 1440 journal lines a day. `_trigger` emits the
|
a persistent condition logged loudly is 1440 journal lines a day. `_trigger`
|
||||||
one WARNING that matters: firing *now* on a non-phone time.
|
emits the single 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.
|
||||||
@ -166,10 +160,11 @@ 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.** A stale path caused a month-long silent production failure
|
same commit.** Leaving it pointing at a module that no longer exists caused a
|
||||||
(2026-05-28, orchestrator still on `python_pkg.screen_locker.screen_lock` after
|
month-long silent production failure once already (2026-05-28, orchestrator
|
||||||
screen-locker's extraction): the alarm fired and dismissed correctly while the
|
still on `python_pkg.screen_locker.screen_lock` after screen-locker's
|
||||||
workout lock crashed with `ModuleNotFoundError` on every run.
|
extraction): the alarm fired and dismissed correctly while the workout lock
|
||||||
|
crashed with `ModuleNotFoundError` on every run.
|
||||||
|
|
||||||
## Production dependency installation
|
## Production dependency installation
|
||||||
|
|
||||||
@ -181,53 +176,57 @@ 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**
|
**Run `install.sh` (or `pip install -e`) from a durable clone**, not a scratch
|
||||||
(`~/src/wake-alarm`, mirroring `~/src/screen-locker`), not a scratch directory:
|
directory — it is editable, so a later `git pull` in that clone updates the
|
||||||
it is editable, so a later `git pull` there updates the running production
|
running production code. From `/tmp` or via `pip install "wake_alarm @ git+..."`
|
||||||
code. From `/tmp` or via `pip install "wake_alarm @ git+..."` you get a
|
you get a snapshot frozen at that commit, and the next push silently does not
|
||||||
snapshot frozen at that commit, and the next push silently does not reach the
|
reach the running service. Convention: `~/src/wake-alarm`, mirroring
|
||||||
service.
|
`~/src/screen-locker`.
|
||||||
|
|
||||||
A dependency installed only into a dev venv makes the service fail with
|
If you add a dependency and only install it into a dev venv, the service fails
|
||||||
`ModuleNotFoundError` on its next run (this gap caused a 3-day diet_guard
|
with `ModuleNotFoundError` on its next run — this exact gap caused a 3-day
|
||||||
outage). Verify against `/usr/bin/python3 -c "import <dep>"`.
|
diet_guard 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
|
old `/usr/local/bin/shutdown` wrapper wherever one survives. `install.sh` calls `uninstall.sh --retired-only` as its last step, so
|
||||||
`uninstall.sh --retired-only` last, so **`uninstall.sh` is load-bearing for
|
**`uninstall.sh` is load-bearing for installing**, not just for removing —
|
||||||
installing** — renaming or deleting it breaks a fresh install. That call is
|
renaming or deleting it breaks a fresh install. That call is non-fatal and
|
||||||
non-fatal and gated on `sudo -n`: the cleanup needs root, and a hard failure
|
gated on `sudo -n`: the cleanup needs root, and a hard failure there would
|
||||||
would abort an install that had already placed the package and the timer.
|
abort an install that had already placed the package and enabled the timer.
|
||||||
**`/etc/sudoers.d/wake-alarm` stays even after a full uninstall:** the RTC
|
|
||||||
self-wake's `rtcwake` and the root ring unit's `systemctl` lines live there.
|
**`/etc/sudoers.d/wake-alarm` is deliberately left in place** even by a full
|
||||||
|
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** (the HMAC-signed
|
- **`wake_state.json` is runtime state, not tracked.** It holds the
|
||||||
once-per-day latch). It was once committed in the monorepo; keep it ignored.
|
HMAC-signed once-per-day latch. It was accidentally committed in the
|
||||||
- **`WAKE_STATE_FILE` is redirected in `tests/conftest.py`, not per-file.** A
|
monorepo and must stay gitignored here.
|
||||||
per-file redirect gets forgotten when a new writer appears (`_trigger` was
|
- **`WAKE_STATE_FILE` is redirected in `tests/conftest.py`, not per-file.**
|
||||||
one), and the failure is silent: a green suite that stamped the live file.
|
`_trigger` writes it now, and the trigger tests never redirected it — a
|
||||||
|
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
|
||||||
|
|
||||||
- run: n/a: no single entry point; systemd timers (`install.sh`) drive it, inspect with `python -m wake_alarm._sync --show`, `python -m wake_alarm._session --show`, `python -m wake_alarm._trigger --dry-run`
|
- run: n/a: no single entry point; systemd timers (`install.sh`) drive it, inspect with `python -m wake_alarm._sync --show`, `python -m wake_alarm._session --show`, `python -m wake_alarm._trigger --dry-run`
|
||||||
- test: `python -m pytest -q wake_alarm/tests/ && cd phone_app && flutter test --reporter=compact`
|
- test: `python -m pytest -q wake_alarm/tests/ && cd phone_app && flutter test --reporter=compact`
|
||||||
- test-changed: `scripts/test_changed.sh`
|
- test-changed: `scripts/test_changed.sh`
|
||||||
- lint: n/a: dropped (kuhy, 2026-11-27)
|
- lint: `pre-commit run ruff --all-files && cd phone_app && flutter analyze --fatal-infos --fatal-warnings`
|
||||||
- coverage: n/a: dropped (kuhy, 2026-11-27)
|
- coverage: `python -m pytest -q wake_alarm/tests/ --cov=wake_alarm --cov-branch --cov-report=xml --cov-fail-under=100`
|
||||||
- coverage-gaps: n/a: dropped (kuhy, 2026-11-27)
|
- 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`; live log
|
Other: full lint gate `pre-commit run --all-files`; watch live
|
||||||
`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`.
|
||||||
|
|
||||||
@ -240,7 +239,8 @@ 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 or add a challenge that hides its prompt.
|
- Don't let the bypass skip the walk, and don't add a challenge kind that
|
||||||
|
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
245
DOCS-bypass.md
@ -1,245 +0,0 @@
|
|||||||
# Bypasses of the alarm (2026-11-22)
|
|
||||||
|
|
||||||
On 2026-11-20 and 11-22 kuhy long-pressed WakeAlarm on the home screen and
|
|
||||||
tapped "Wstrzymaj aplikację" (Digital Wellbeing's *Pause app*). The pause
|
|
||||||
suspended the app, the ring stopped, and he went back to sleep. This file
|
|
||||||
covers the three layers that now stop that, what counts as a bypass when
|
|
||||||
one gets through anyway, and what a bypass costs.
|
|
||||||
|
|
||||||
## Layer 1: the pause is refused (focus-owner, `~/src/phone-focus-mode`)
|
|
||||||
|
|
||||||
Every focus-owner pass, for the eight enforcement apps in
|
|
||||||
`focus_policy/packages.py` `ENFORCEMENT_PACKAGES` (wake_alarm_sync,
|
|
||||||
workout_app, diet_guard_app, leetcode_guard, book_guard_app, home_guard,
|
|
||||||
daily_limits, habit_stack):
|
|
||||||
|
|
||||||
- `setUserControlDisabledPackages`: Android refuses to suspend them
|
|
||||||
(`Cannot suspend package ...: protected package`), and Settings' Force stop
|
|
||||||
and Clear storage are greyed out. `am force-stop` and `pm clear` are refused
|
|
||||||
too; `adb install -r` still works, so deploys are unaffected.
|
|
||||||
- `setUninstallBlocked`.
|
|
||||||
- `setPermissionGrantState(POST_NOTIFICATIONS, GRANTED)`. The full-screen
|
|
||||||
intent is an app-op and cannot be pinned (`setPermissionGrantState`
|
|
||||||
returns false), so revoking it is a bypass instead (below).
|
|
||||||
- A suspension found anyway is lifted. Measured on the emulator: a pause
|
|
||||||
made before the pins were applied was lifted 4.3 s later, by the pass that
|
|
||||||
wake_alarm's `UNSUSPEND` signal started.
|
|
||||||
|
|
||||||
Digital Wellbeing itself is hidden in every state (`ALWAYS_BLOCKED_PACKAGES`),
|
|
||||||
so the Pause button is gone as well.
|
|
||||||
|
|
||||||
## Layer 2: WakeAlarm is a device admin
|
|
||||||
|
|
||||||
`WakeAdminReceiver` (`res/xml/wake_admin.xml`, no policies). Android refuses
|
|
||||||
to suspend an active admin. It is activated over adb, never by a tap:
|
|
||||||
|
|
||||||
adb shell dpm set-active-admin com.kuhy.wake_alarm_sync/.WakeAdminReceiver
|
|
||||||
|
|
||||||
Deactivating it in Settings cannot be prevented, so it is a bypass.
|
|
||||||
|
|
||||||
## Layer 3: what counts as a bypass (`Bypass.kt`)
|
|
||||||
|
|
||||||
A bypass counts only on a ringing day (an alarm is stored, not a free or sick
|
|
||||||
day, the ring did not stand down) while the ring or the morning session is
|
|
||||||
live. Causes (`bypass` phone event, `data.cause`):
|
|
||||||
|
|
||||||
| cause | seen by |
|
|
||||||
|---|---|
|
|
||||||
| `suspended` | `SuspendReceiver` on `MY_PACKAGE_SUSPENDED`; also sends focus-owner `UNSUSPEND` |
|
|
||||||
| `admin_removed` | `WakeAdminReceiver.onDisabled` |
|
|
||||||
| `notifications_off` | ring start and every launch (`Bypass.checkOnLaunch`) |
|
|
||||||
| `fsi_revoked` | the same; uid app-op `USE_FULL_SCREEN_INTENT` denied |
|
|
||||||
| `ring_killed` | every launch and boot: today's ring fired, was never dismissed, and is not sounding |
|
|
||||||
| `uninstalled` | focus-owner, every pass, any day: `com.kuhy.wake_alarm_sync` not installed for user 0 (see below) |
|
|
||||||
|
|
||||||
`ring_killed` reads `watched_fired_date`, a stamp only builds with `Bypass`
|
|
||||||
write, so a ring fired by an older build (11-22, paused, never dismissed) does
|
|
||||||
not count the first time the new build starts. The same cause twice within
|
|
||||||
a minute is recorded once (both activities run the launch check).
|
|
||||||
|
|
||||||
## What a bypass costs
|
|
||||||
|
|
||||||
- **A miss** (`StickCheck`), on any weekday, at once, whatever the dismiss
|
|
||||||
does afterwards: a lockdown through the next day, stacking. The streak
|
|
||||||
links penalty days, stick days (Tue–Thu) plus bypass days; free and sick
|
|
||||||
days are skipped. A plain late dismiss on Fri–Mon still changes nothing.
|
|
||||||
A later check or bypass on the day already penalised sends the stored
|
|
||||||
lockdown (`locked_through`, if today or later) again, same date and
|
|
||||||
streak, so a signal focus-owner missed (not running, not yet Device
|
|
||||||
Owner) still lands.
|
|
||||||
- **The phone rings again** (`Bypass.ringAgain`). During a session it is a
|
|
||||||
re-ring: only the full dismiss sequence silences it and `re_rings` goes up
|
|
||||||
by one when it does (`SessionHandoff.afterDismiss`). It is recorded as
|
|
||||||
`bypass:<cause>` in `re_ring_reasons` (`bypass:fsi_revoked`,
|
|
||||||
`bypass:suspended`, ...): `Bypass.record` stamps the cause
|
|
||||||
(`BypassReRing`, dated) before it restarts the ring, and the session takes
|
|
||||||
it once over `takeBypassReRing`, on the screen's tick or on the dismiss. A
|
|
||||||
bypass while a deadline re-ring already sounds stamps nothing: one sound,
|
|
||||||
one re-ring, reason `deadline:<leg>`; the `bypass` event, its publish and
|
|
||||||
the lockdown still happen.
|
|
||||||
- **The PC rings** (`_fallback_policy`, reason `bypass`). The phone pushes
|
|
||||||
the event at once through the headless `publishNowMain` engine. The PC
|
|
||||||
rings from the bypass for up to 30 min (`FALLBACK_RING_CAP` from the
|
|
||||||
bypass, not the day's cap), outside the window, after a session started
|
|
||||||
and after the day's own ring was used. It stops on a `dismissed` newer
|
|
||||||
than the bypass, which the phone also pushes at once. Free and sick days
|
|
||||||
and an escape stand it down. The tick reads the phone until `A + 4 h`
|
|
||||||
(`BYPASS_WATCH`); the fallback timer ticks 04:00-11:59 (and 21:xx, below).
|
|
||||||
To see these answers without a backend, `_fallback --dry-run --at <instant>
|
|
||||||
--published <file>` reads the phone's logs from a JSON list of
|
|
||||||
`[device_id, alarm.json]` pairs instead of Firebase (`_published_file`).
|
|
||||||
|
|
||||||
## An uninstall that gets through (focus-owner, 2026-11-23)
|
|
||||||
|
|
||||||
WakeAlarm cannot be uninstalled: focus-owner holds `setUninstallBlocked`
|
|
||||||
and `setUserControlDisabledPackages` on it every pass. The Pixel's
|
|
||||||
`dumpsys device_policy` shows `packageUninstallBlocked` for it (2026-11-23).
|
|
||||||
On the AVD, `adb uninstall`, `pm uninstall --user 0` and `-k --user 0` all
|
|
||||||
fail with `DELETE_FAILED_INTERNAL_ERROR` ("Attempted to delete protected
|
|
||||||
package"): the user-control pin refuses it before the uninstall block is
|
|
||||||
asked. Deploys use `adb install -r`, which both allow.
|
|
||||||
|
|
||||||
If WakeAlarm is gone anyway, WakeAlarm cannot record a bypass, so
|
|
||||||
focus-owner does (`phone-focus-mode` `focus-owner/.../UninstallLockdown.kt`,
|
|
||||||
`UninstallEvents.kt`, `lib/sync/`):
|
|
||||||
|
|
||||||
- **Missing** means not found, or found with `FLAG_INSTALLED` clear. A
|
|
||||||
hidden app is installed.
|
|
||||||
- **Lockdown**, every day including free and sick days: the lockdown
|
|
||||||
allowlist while the app is missing and through the day after it returns.
|
|
||||||
Its own prefs, so wake_alarm's `LIFT_LOCKDOWN` does not clear it (a
|
|
||||||
reinstalled WakeAlarm would send one at once). No day cap.
|
|
||||||
- **Event**: `bypass` with `cause: uninstalled` and the phone-local `date`,
|
|
||||||
under device `focus-owner`, record `alarm`, field `phone_events`. One at
|
|
||||||
once when the app goes missing (it rings the PC only inside a tick
|
|
||||||
window), then one per later day at the first pass at or after the alarm
|
|
||||||
time focus-owner read from the sync (08:00 if none). The PC rings every
|
|
||||||
morning until a full dismiss logs `dismissed`; on a free or sick day it
|
|
||||||
stays silent while the phone stays locked.
|
|
||||||
- **Queue**: the lockdown never waits on the push. An unsent event is
|
|
||||||
retried every pass, a failure is logged once a day, nothing is dropped.
|
|
||||||
- **Push-only**: focus-owner writes its own file and never merges a peer's
|
|
||||||
log into it (a pulled list would replace its events, field by field).
|
|
||||||
Its `phone_events` HLC is the newest event's own `at`, so a late retry
|
|
||||||
never out-ranks a list the reinstalled phone published.
|
|
||||||
- `newest_push` skips device `focus-owner`: its write is not the phone's.
|
|
||||||
- Set up once per install: Google sign-in plus the passphrase (the cloud
|
|
||||||
and lock icons in focus-owner's app bar). Each success pushes a harmless
|
|
||||||
`install_check` field that no PC policy reads.
|
|
||||||
|
|
||||||
## Testing against a backend: the RTDB emulator
|
|
||||||
|
|
||||||
The AVD never signs in to prod. A probe build with
|
|
||||||
`--dart-define=WAKE_SYNC_EMULATOR=http://10.0.2.2:9000` syncs to the
|
|
||||||
Firebase RTDB emulator on the PC instead of prod Firebase *and* the GitHub
|
|
||||||
mirror (`sync_emulator.dart`; plain HTTP is allowed to `10.0.2.2` in the
|
|
||||||
debug manifest only). Release builds never set the define.
|
|
||||||
|
|
||||||
1. `systemd-run --user --collect --unit=wa-rtdb-emu /usr/bin/java -jar
|
|
||||||
~/.cache/firebase/emulators/firebase-database-emulator-v4.11.2.jar --host
|
|
||||||
127.0.0.1 --port 9000` (one default namespace; `auth=owner` is admin).
|
|
||||||
2. Write a dummy passphrase to `files/passphrase` under the app's
|
|
||||||
`Android/data/<pkg>/` dir; the probe moves it into the keystore on launch
|
|
||||||
(`probe_passphrase.dart`). Without one every push is `sync locked`.
|
|
||||||
A probe's `-t` file must re-export the headless entrypoints
|
|
||||||
(`publishNowMain`, ...): Kotlin resolves them by name in the root library,
|
|
||||||
and without them the bypass publish never ran.
|
|
||||||
3. After the bypass: `HOME=<scratch with .config/crdt-sync/password>
|
|
||||||
PYTHONUSERBASE=~/.local /usr/bin/python3 scripts/emu_published.py
|
|
||||||
http://127.0.0.1:9000 out.json`, then `_fallback --dry-run --at <instant>
|
|
||||||
--published out.json`.
|
|
||||||
|
|
||||||
Traps on the shared AVD:
|
|
||||||
|
|
||||||
- It can boot `RUNNING_LOCKED` with PIN 1234, and then `/sdcard` is missing.
|
|
||||||
Unlock it before you write the passphrase.
|
|
||||||
- `dpm remove-active-admin` refuses the admin ("non-test admin"). Use
|
|
||||||
Settings → Device admin apps → WakeAlarm → Deactivate.
|
|
||||||
- An active admin makes `cmd package suspend` fail, so suspend first, then
|
|
||||||
activate the admin.
|
|
||||||
- The probe's `ringNow` does not mark the ring as fired, so `Bypass.record`
|
|
||||||
logs "no ring or session live". Set the AVD clock (`adb root`,
|
|
||||||
`settings put global auto_time 0`, `date`) to just before the armed
|
|
||||||
`AlarmReceiver` time and let the alarm fire. Afterwards set `auto_time`
|
|
||||||
back to 1.
|
|
||||||
|
|
||||||
### Live check 2026-11-22: bypass events on the RTDB emulator
|
|
||||||
|
|
||||||
C5 and C6 were checked on emulator-5556 with the `main_session_probe.dart`
|
|
||||||
build (`WAKE_SYNC_EMULATOR`), with the clock moved to Mon 2026-11-23 07:56
|
|
||||||
so the 07:57 alarm rang through `AlarmReceiver`. With the alarm still
|
|
||||||
ringing: `cmd package suspend` at 07:57:34 logged `bypass: suspended`,
|
|
||||||
and deactivating the admin in Settings at 07:58:04 logged
|
|
||||||
`bypass: admin_removed`. Each one logged "signalling focus-owner lockdown
|
|
||||||
through 2026-11-24". `emu_published.py` then read both from the RTDB emulator:
|
|
||||||
`{"kind":"bypass","data":{"cause":"suspended","date":"2026-11-23"}}` and
|
|
||||||
`{"kind":"bypass","data":{"cause":"admin_removed","date":"2026-11-23"}}`
|
|
||||||
(a `notifications_off` bypass from 07:57:11 was also there, because the AVD
|
|
||||||
has the app's notifications off). Then
|
|
||||||
`_fallback --dry-run --at 2026-11-23T08:03 --published out.json` answered
|
|
||||||
`WOULD RING: bypass` (`bypass_at=07:58:04`). focus-owner is not on that AVD:
|
|
||||||
its unsuspend and its applied lockdown are the earlier C6 check at 83e1e15.
|
|
||||||
|
|
||||||
## The 21:00 notifications check
|
|
||||||
|
|
||||||
Android lets nothing lock "All WakeAlarm notifications", and with them off
|
|
||||||
the ring has no screen. The ring-time check above still counts it as a
|
|
||||||
bypass; this one catches it the evening before, while kuhy can still fix it.
|
|
||||||
|
|
||||||
- **Phone.** `NotifState` (the same rule `Bypass.checkPermissions` uses: app
|
|
||||||
notifications off, or the ring channel at `IMPORTANCE_NONE`) logs a
|
|
||||||
`notifications` event, data `enabled` (bool) and `trigger`, and pushes it
|
|
||||||
at once through `publishNowMain`. Triggers: an exact alarm at 21:00
|
|
||||||
(`NotifAlarm`, request code 1007, `evening`; re-armed by its receiver, by
|
|
||||||
every `AlarmScheduler.schedule`, boot and the watchdog, always the next
|
|
||||||
future 21:00) and `NotifBlockReceiver` on `APP_BLOCK_STATE_CHANGED` /
|
|
||||||
`NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED` for the ring channel
|
|
||||||
(`app_block`, `channel_block`). Both receivers hold the broadcast open
|
|
||||||
(`NotifRules.holdMs`: 8 s for a foreground broadcast, whose ANR budget is
|
|
||||||
10 s, else 25 s) so the headless engine is not frozen mid-push.
|
|
||||||
- **PC** (`_fallback_evening`, rule in `_evening_policy`). The fallback
|
|
||||||
timer also ticks 21:00-21:59; those ticks skip the morning code. When
|
|
||||||
today's newest `notifications` event says off, the PC rings
|
|
||||||
(`notifications_off`) until a newer one says on, or 30 min
|
|
||||||
(`FALLBACK_RING_CAP`) from the evening's first ring. The cap has its own
|
|
||||||
latch, `evening_ring.json`, so it never eats the morning's or a bypass's.
|
|
||||||
The hour gates only *starting*; a ring started at 21:50 runs its 30 min.
|
|
||||||
- **No ring** when tomorrow is a free or sick day (`free_tomorrow`,
|
|
||||||
`sick_tomorrow`), when no event was published today (phone off), or when
|
|
||||||
Firebase does not answer at the tick. An unreachable poll mid-ring keeps
|
|
||||||
ringing. Events: `evening_tick`, `evening_ring_start`, `evening_ring_stop`
|
|
||||||
(never the morning's names, so the audit does not count them).
|
|
||||||
|
|
||||||
## The monitors ring too
|
|
||||||
|
|
||||||
kuhy turns the speakers off at the knob for the night, so the 11-22 fallback
|
|
||||||
ring played 30 min into silence. Both rings now also play to every connected
|
|
||||||
monitor (ELD name in `aplay -l`: `G27Q` on HDMI, `VG28UQL1A` on DP, both on
|
|
||||||
the NVidia card):
|
|
||||||
|
|
||||||
- root path: `ring_alsa.sh` starts one `aplay` loop per monitor, IEC958
|
|
||||||
unmuted;
|
|
||||||
- PipeWire path: `_ring_monitors.MonitorLoops` runs
|
|
||||||
`ring_alsa.sh --monitors` as the user beside `pw-play` (PipeWire does not
|
|
||||||
expose the NVidia outputs).
|
|
||||||
|
|
||||||
Each monitor logs one `ring_sink sink=<name> ... result=ok|error` line.
|
|
||||||
|
|
||||||
**Silent probe.** `ring_alsa.sh --probe` writes two seconds of digital
|
|
||||||
silence to each monitor with IEC958 muted (restored afterwards) and logs one
|
|
||||||
`ring_probe` line per monitor. `_ring_probe.maybe_probe` starts
|
|
||||||
`wake-alarm-ring-probe.service` once, at `A − 5` on the first morning with no
|
|
||||||
graphical session (the state a fallback ring meets), and writes
|
|
||||||
`ring_probe_done`. "No graphical session" means greeter only: lightdm is
|
|
||||||
masked only before 05:00, when no ring can happen. A morning kuhy is already
|
|
||||||
logged in at `A − 5` logs one `ring_probe: waiting_for_no_session` event a
|
|
||||||
day instead. Read it with `journalctl -u wake-alarm-ring-probe` and
|
|
||||||
`grep ring_probe ~/.local/state/wake_alarm/events.jsonl`.
|
|
||||||
vmbox gate: `ring-alsa-monitor-sinks`, `ring-alsa-monitor-probe`
|
|
||||||
(`scripts/vmbox/guest_cases_monitors.sh`).
|
|
||||||
|
|
||||||
## Found on the way: lockdown signals never arrived
|
|
||||||
|
|
||||||
focus-owner defined `SIGNAL_LOCKDOWN` but did not request it, and wake_alarm
|
|
||||||
sends with it as the receiver permission, so every `LOCKDOWN_UNTIL_EOD` and
|
|
||||||
`LIFT_LOCKDOWN` was dropped. focus-owner now holds it (eeb0def).
|
|
||||||
@ -61,9 +61,7 @@ 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`. `re_ring_reasons`
|
session for today and resumes it with `reRings + 1`.
|
||||||
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
|
||||||
@ -184,24 +182,3 @@ 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`.
|
|
||||||
|
|||||||
@ -1,72 +0,0 @@
|
|||||||
# 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; PC side: `DOCS-sick-days-pc.md`). It is **not** a free day: separate pool,
|
self-wake, missed-alarm penalty / stick, morning routine). 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; a ring skipped for a sick day stays `sick_day` after a later clear (`RingWatch.markSkipped`) |
|
| Stick | `StickCheck.kt`: verdict `sick_day`; the streak skips sick days like free days |
|
||||||
| 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
|
||||||
|
|||||||
@ -30,37 +30,16 @@ 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 (kuhy is not in `audio`) → root system unit `wake-alarm-ring-alsa.service` playing straight
|
- Otherwise (night lockdown: lightdm masked, nobody logged in; kuhy is not in
|
||||||
|
`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)
|
||||||
|
|
||||||
@ -75,13 +54,7 @@ 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.
|
||||||
vmbox only, 2026-11-15 (`vm new --uefi`, OVMF): `rtcwake -m no -s 120`
|
Unverified until the host S5 test runs.
|
||||||
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)
|
||||||
|
|
||||||
@ -105,8 +78,56 @@ 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 stands down the fallback ring, RTC self-wake, trigger, workday
|
A sick day (that does not keep `alarm`, see below) is a date in the shared `sickdays` pool (`~/src/utils/sickdays`):
|
||||||
penalty and audit: **`DOCS-sick-days-pc.md`**.
|
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.
|
||||||
|
|
||||||
### Escape hatch (until 2026-10-15 inclusive)
|
### Escape hatch (until 2026-10-15 inclusive)
|
||||||
|
|
||||||
@ -140,7 +161,6 @@ 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/`)
|
||||||
|
|
||||||
@ -157,11 +177,8 @@ 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`), `bypass` (data: `cause`, `date`, `session`; `DOCS-bypass.md`),
|
`exact`|`boot`|`watchdog`, `date` judged, `verdict`, incl. `free_day`|`sick_day`), `lockdown_sent` (data:
|
||||||
`bypass_ignored`, `notifications` (data: `enabled`, `trigger` =
|
`until`, `streak`), `lift_sent`, `escape_used`, `boot`.
|
||||||
`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
|
||||||
@ -171,29 +188,10 @@ 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`, `evening_tick`,
|
`fallback_ring_start`, `fallback_ring_stop`, `ring_backend`, `rtc_armed`,
|
||||||
`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,
|
||||||
@ -204,15 +202,8 @@ its 11:00 deferral were fine; only the desktop was missing.
|
|||||||
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. **Decided 2026-11-15:** on the *first* busy open (no retries)
|
keep it busy. **Open:** what the root ring does about a held card is
|
||||||
`ring_alsa.sh` rings through the user's PipeWire (`runuser`, then
|
kuhy's call (killing the holder was refused by the auto-mode classifier).
|
||||||
`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.
|
||||||
@ -223,11 +214,8 @@ its 11:00 deferral were fine; only the desktop was missing.
|
|||||||
|
|
||||||
## Evidence for Claude
|
## Evidence for Claude
|
||||||
|
|
||||||
`python -m wake_alarm._audit [YYYY-MM-DD] [--stdout | --force]` and the 11:05 timer write
|
`python -m wake_alarm._audit [YYYY-MM-DD]` and the 11:05 timer write
|
||||||
`~/data/wake-alarm/incidents/<date>.md` (outside the repo: personal data): a merged
|
`~/data/wake-alarm/incidents/<date>.md`: a merged phone + PC timeline, then
|
||||||
phone + PC timeline, then expected-vs-observed checks (alarm known, RTC armed, PC up
|
expected-vs-observed checks (alarm known, RTC armed the night before, PC up
|
||||||
by `A`, ring/fallback, penalty, lockdown, phone pushed within `PHONE_PUSH_STALE_SECONDS`
|
by `A`, ring/fallback, penalty, lockdown), mismatches and escape uses first.
|
||||||
= 24 h by newest dated HLC; n/a when Firebase is unreachable), mismatches and escapes first.
|
Outside the repo on purpose: it holds personal data.
|
||||||
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`.
|
|
||||||
|
|||||||
17
install.sh
17
install.sh
@ -57,8 +57,6 @@ 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)"
|
||||||
@ -66,7 +64,6 @@ 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=""
|
||||||
@ -78,18 +75,14 @@ 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"
|
||||||
sed "s/@USER@/$INSTALL_USER/" "$PC_DIR/$ALSA_UNIT" >"$TEMP_DIR/$ALSA_UNIT"
|
sudo install -m 0644 "$PC_DIR/$ALSA_UNIT" "/etc/systemd/system/$ALSA_UNIT"
|
||||||
sudo install -m 0644 "$TEMP_DIR/$ALSA_UNIT" "/etc/systemd/system/$ALSA_UNIT"
|
|
||||||
sudo install -m 0644 "$PC_DIR/$PROBE_UNIT" "/etc/systemd/system/$PROBE_UNIT"
|
|
||||||
sudo systemctl daemon-reload
|
sudo systemctl daemon-reload
|
||||||
echo " Ring WAVs, $RING_SCRIPT_DST, $ALSA_UNIT and $PROBE_UNIT installed."
|
echo " Ring WAVs, $RING_SCRIPT_DST and $ALSA_UNIT installed."
|
||||||
}
|
}
|
||||||
|
|
||||||
install_sudoers() {
|
install_sudoers() {
|
||||||
@ -106,7 +99,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, start $PROBE_UNIT (validated)."
|
echo " $SUDOERS_FILE: rtcwake + start/stop $ALSA_UNIT (validated)."
|
||||||
}
|
}
|
||||||
|
|
||||||
install_powerkey_dropin() {
|
install_powerkey_dropin() {
|
||||||
@ -139,10 +132,6 @@ 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"
|
||||||
|
|||||||
1
phone_app/android/.gitignore
vendored
1
phone_app/android/.gitignore
vendored
@ -12,4 +12,3 @@ GeneratedPluginRegistrant.java
|
|||||||
key.properties
|
key.properties
|
||||||
**/*.keystore
|
**/*.keystore
|
||||||
**/*.jks
|
**/*.jks
|
||||||
.kotlin/
|
|
||||||
|
|||||||
@ -84,30 +84,3 @@ 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,5 +4,4 @@
|
|||||||
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>
|
||||||
|
|||||||
@ -1,9 +0,0 @@
|
|||||||
<?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,47 +94,10 @@
|
|||||||
<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,8 +47,6 @@ 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,8 +145,6 @@ 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,15 +27,13 @@ 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 and no ring_started for the PC. Only the
|
// recorded: no markFired (the stick's own check skips the day too)
|
||||||
// skip itself is latched, so the stick still stands the day down if
|
// and no ring_started for the PC. Re-arm for tomorrow (the armed
|
||||||
// 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
|
||||||
@ -49,9 +47,6 @@ 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,8 +67,6 @@ 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 = NotifState.RING_CHANNEL_ID
|
private const val CHANNEL_ID = "wake_alarm_ring"
|
||||||
private const val NOTIFICATION_ID = 42
|
private const val NOTIFICATION_ID = 42
|
||||||
|
|
||||||
/** Vibration: 1s buzz, 1s gap, repeating from index 0. */
|
/** Vibration: 1s buzz, 1s gap, repeating from index 0. */
|
||||||
|
|||||||
@ -54,8 +54,6 @@ object AlarmWatchdog {
|
|||||||
fun verify(context: Context) {
|
fun verify(context: Context) {
|
||||||
val rearmed = AlarmScheduler.rearmFromStorage(context)
|
val rearmed = AlarmScheduler.rearmFromStorage(context)
|
||||||
Log.i(TAG, "daily check: rearmed=$rearmed")
|
Log.i(TAG, "daily check: rearmed=$rearmed")
|
||||||
// rearmFromStorage arms it too, but only with an alarm stored.
|
|
||||||
NotifAlarm.schedule(context)
|
|
||||||
// Third net behind the exact check and boot: within a day, whatever
|
// Third net behind the exact check and boot: within a day, whatever
|
||||||
// dropped the other two, today's miss is still caught here.
|
// dropped the other two, today's miss is still caught here.
|
||||||
StickRunner.run(context, "watchdog")
|
StickRunner.run(context, "watchdog")
|
||||||
|
|||||||
@ -25,14 +25,10 @@ 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 {
|
||||||
|
|||||||
@ -1,147 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
@ -1,35 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
@ -1,51 +0,0 @@
|
|||||||
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,14 +52,12 @@ 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),
|
||||||
@ -69,9 +67,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, bypassOn).lockedThrough?.toString(),
|
StickCheck.afterMiss(today, stick, standsDown).lockedThrough?.toString(),
|
||||||
"lockIfMissTomorrow" to
|
"lockIfMissTomorrow" to
|
||||||
StickCheck.afterMiss(tomorrow, stick, standsDown, bypassOn).lockedThrough?.toString(),
|
StickCheck.afterMiss(tomorrow, stick, standsDown).lockedThrough?.toString(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -30,27 +30,14 @@ 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
|
||||||
|
|
||||||
/** A publish asked for while an engine ran; started when that one stops. */
|
/** Starts the engine unless one is already running. Main thread only. */
|
||||||
private var pending: Pair<Context, String>? = null
|
fun start(context: Context) {
|
||||||
|
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)
|
||||||
@ -65,7 +52,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")
|
||||||
@ -80,9 +67,5 @@ 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,9 +20,6 @@ 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()
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,99 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,77 +0,0 @@
|
|||||||
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,19 +32,9 @@ 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()
|
prefs(context).edit().putString(KEY_FIRED_DATE, today()).apply()
|
||||||
.putString(KEY_FIRED_DATE, today())
|
|
||||||
.putString(KEY_WATCHED_FIRED_DATE, today())
|
|
||||||
.apply()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun markDismissed(context: Context) {
|
fun markDismissed(context: Context) {
|
||||||
@ -52,34 +42,6 @@ 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
|
||||||
|
|||||||
@ -38,20 +38,6 @@ 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. */
|
||||||
@ -67,19 +53,14 @@ data class StickRun(
|
|||||||
val state: StickState,
|
val state: StickState,
|
||||||
val checkedThrough: LocalDate,
|
val checkedThrough: LocalDate,
|
||||||
val signalUntil: LocalDate?,
|
val signalUntil: LocalDate?,
|
||||||
/** [signalUntil] repeats a lockdown already bought, not a new miss's. */
|
|
||||||
val resend: Boolean = false,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The stick's decision, as pure functions -- no Context, no clock, no I/O,
|
* The stick's decision, as pure functions -- no Context, no clock, no I/O,
|
||||||
* so every rule here is checkable in isolation.
|
* so every rule here is checkable in isolation.
|
||||||
*
|
*
|
||||||
* A **bypass** ([StickInputs.bypassOn]) is a miss on any day that is neither
|
|
||||||
* free nor sick, at once and whatever the dismiss did afterwards.
|
|
||||||
*
|
|
||||||
* A **miss** is a stick day (Tue/Wed/Thu, [WorkdayStick.STICK_DAYS]) that is
|
* A **miss** is a stick day (Tue/Wed/Thu, [WorkdayStick.STICK_DAYS]) that is
|
||||||
* neither a free day nor a sick day (now, or when its ring stood down), whose alarm passed by at least [Stakes.STICK_GRACE_MINUTES]
|
* neither a free day nor a sick day, 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).
|
||||||
@ -95,9 +76,6 @@ 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)
|
||||||
@ -109,7 +87,6 @@ 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
|
||||||
@ -123,22 +100,12 @@ 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, resend)
|
return StickRun(verdicts, state, maxOf(settled, checked ?: settled), signal)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 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. */
|
||||||
@ -149,28 +116,19 @@ 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) && !inputs.bypassOn(day)) return StickVerdict.NOT_STICK_DAY to state
|
if (!isStickDay(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, inputs.bypassOn)
|
return StickVerdict.MISS to afterMiss(day, state, inputs.standsDown)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -180,31 +138,20 @@ 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(
|
fun afterMiss(day: LocalDate, state: StickState, standsDown: (LocalDate) -> Boolean): StickState {
|
||||||
day: LocalDate,
|
val streak = streakAfterMiss(day, state, standsDown)
|
||||||
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 misses including one on [day]: the chain continues only
|
* Consecutive stick-day misses including one on [day]: the chain
|
||||||
* when the previous penalty day -- a stick day, or any day with a
|
* continues only when the previous stick day (free and sick days
|
||||||
* bypass; free and sick days skipped, per [standsDown] -- is exactly
|
* skipped, per [standsDown]) is exactly the last miss.
|
||||||
* the last miss.
|
|
||||||
*/
|
*/
|
||||||
fun streakAfterMiss(
|
fun streakAfterMiss(day: LocalDate, state: StickState, standsDown: (LocalDate) -> Boolean): Int {
|
||||||
day: LocalDate,
|
val previous = previousStickDay(day, standsDown)
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -212,16 +159,12 @@ 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 penalty day (stick or bypass) that does not [standsDown], or null. */
|
/** The nearest earlier stick day that does not [standsDown], or null. */
|
||||||
fun previousStickDay(
|
fun previousStickDay(day: LocalDate, standsDown: (LocalDate) -> Boolean): LocalDate? {
|
||||||
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) || bypassOn(step)) && !standsDown(step)) return step
|
if (isStickDay(step) && !standsDown(step)) return step
|
||||||
step = step.minusDays(1)
|
step = step.minusDays(1)
|
||||||
}
|
}
|
||||||
return null
|
return null
|
||||||
@ -230,6 +173,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, now or at ring time. */
|
/** A day the stick skips entirely: free or sick. */
|
||||||
val StickInputs.standsDown: (LocalDate) -> Boolean
|
val StickInputs.standsDown: (LocalDate) -> Boolean
|
||||||
get() = { isFree(it) || isSick(it) || ringSkippedOn(it) != null }
|
get() = { isFree(it) || isSick(it) }
|
||||||
|
|||||||
@ -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,
|
||||||
* for the streak (it only re-sends the same lockdown), which matters because Android replays BOOT_COMPLETED to a force-stopped
|
* 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,8 +35,6 @@ 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) {
|
||||||
@ -50,18 +48,13 @@ 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. A day
|
// still counts toward the streak, but nothing is sent for it.
|
||||||
// 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(
|
mapOf("until" to until.toString(), "streak" to run.state.streak),
|
||||||
"until" to until.toString(),
|
|
||||||
"streak" to run.state.streak,
|
|
||||||
"resend" to run.resend,
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
return run.verdicts.last().verdict
|
return run.verdicts.last().verdict
|
||||||
@ -76,7 +69,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) || RingWatch.skippedOn(context, today) != null
|
SickDays.isSick(context, today)
|
||||||
) {
|
) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@ -23,7 +23,6 @@ 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"
|
||||||
@ -49,13 +48,4 @@ 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,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,5 +0,0 @@
|
|||||||
<?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>
|
|
||||||
@ -1,37 +0,0 @@
|
|||||||
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"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,63 +0,0 @@
|
|||||||
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))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,117 +0,0 @@
|
|||||||
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,7 +20,6 @@ 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),
|
||||||
@ -30,7 +29,6 @@ class StickCheckSickTest {
|
|||||||
isSick = { it in sick },
|
isSick = { it in sick },
|
||||||
state = state,
|
state = state,
|
||||||
checkedThrough = checkedThrough,
|
checkedThrough = checkedThrough,
|
||||||
ringSkippedOn = { skipped[it] },
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -60,7 +58,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, standsDown = { it == wed })
|
val after = StickCheck.afterMiss(thu, before) { it == wed }
|
||||||
assertEquals(2, after.streak)
|
assertEquals(2, after.streak)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -75,40 +73,6 @@ 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)))
|
||||||
|
|||||||
@ -1,87 +0,0 @@
|
|||||||
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,8 +1,4 @@
|
|||||||
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.9.2-all.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-all.zip
|
||||||
|
|||||||
@ -1,8 +1,3 @@
|
|||||||
// 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:material_ui/material_ui.dart';
|
||||||
|
|
||||||
import 'package:wake_alarm_sync/screens/home_screen.dart';
|
import 'package:wake_alarm_sync/screens/home_screen.dart';
|
||||||
@ -11,7 +6,6 @@ import 'package:wake_alarm_sync/screens/session_screen.dart';
|
|||||||
import 'package:wake_alarm_sync/services/alarm_policy.dart';
|
import 'package:wake_alarm_sync/services/alarm_policy.dart';
|
||||||
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
||||||
import 'package:wake_alarm_sync/services/day_pool_refresh.dart';
|
import 'package:wake_alarm_sync/services/day_pool_refresh.dart';
|
||||||
import 'package:wake_alarm_sync/services/enforcement_publish.dart';
|
|
||||||
import 'package:wake_alarm_sync/services/headless_ring_start.dart';
|
import 'package:wake_alarm_sync/services/headless_ring_start.dart';
|
||||||
import 'package:wake_alarm_sync/ui/app_name.dart';
|
import 'package:wake_alarm_sync/ui/app_name.dart';
|
||||||
import 'package:wake_alarm_sync/ui/theme.dart';
|
import 'package:wake_alarm_sync/ui/theme.dart';
|
||||||
@ -46,10 +40,6 @@ 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.
|
||||||
@ -77,10 +67,6 @@ class WakeAlarmSyncApp extends StatelessWidget {
|
|||||||
title: kAppName,
|
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,8 +1,7 @@
|
|||||||
import 'package:material_ui/material_ui.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
import 'package:wake_alarm_sync/main.dart' as app;
|
import 'package:wake_alarm_sync/main.dart';
|
||||||
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';
|
||||||
@ -25,7 +24,6 @@ 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');
|
||||||
@ -33,22 +31,5 @@ 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 app.WakeAlarmSyncApp(newScheduler: FileDrivenScheduler.new));
|
runApp(const 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,22 +0,0 @@
|
|||||||
// phone-slot: not-shared-storage (path is per-package: Android/data/<package>/files)
|
|
||||||
import 'dart:io';
|
|
||||||
|
|
||||||
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart';
|
|
||||||
import 'package:path/path.dart' as p;
|
|
||||||
import 'package:path_provider/path_provider.dart';
|
|
||||||
|
|
||||||
/// Moves an adb-written `files/passphrase` into the keystore, then deletes it.
|
|
||||||
///
|
|
||||||
/// The emulator syncs to the PC's RTDB emulator (`sync_emulator.dart`), and
|
|
||||||
/// every push is end-to-end encrypted: with no passphrase in the keystore it
|
|
||||||
/// throws `SyncLockedException` and nothing is published. The live checks
|
|
||||||
/// give the AVD a dummy test passphrase this way, never the real one, and
|
|
||||||
/// the file does not outlive the first launch. Probe-only.
|
|
||||||
Future<void> plantProbePassphrase() async {
|
|
||||||
final dir = await getExternalStorageDirectory();
|
|
||||||
if (dir == null) return;
|
|
||||||
final file = File(p.join(dir.path, 'passphrase'));
|
|
||||||
if (!file.existsSync()) return;
|
|
||||||
await saveE2ePassphrase((await file.readAsString()).trim());
|
|
||||||
await file.delete();
|
|
||||||
}
|
|
||||||
@ -176,13 +176,10 @@ class _FreeDaysScreenState extends State<FreeDaysScreen> {
|
|||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
// title removed
|
// title removed
|
||||||
actions: [
|
actions: [
|
||||||
Tooltip(
|
IconButton(
|
||||||
message: 'Sync',
|
|
||||||
child: IconButton(
|
|
||||||
icon: const Icon(Icons.sync, semanticLabel: 'Sync now'),
|
icon: const Icon(Icons.sync, semanticLabel: 'Sync now'),
|
||||||
onPressed: _busy ? null : () => unawaited(_sync()),
|
onPressed: _busy ? null : () => unawaited(_sync()),
|
||||||
),
|
),
|
||||||
),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
body: pool == null
|
body: pool == null
|
||||||
|
|||||||
@ -94,9 +94,7 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
|
|||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
Tooltip(
|
Icon(
|
||||||
message: isConnected ? 'Connected' : 'Disconnected',
|
|
||||||
child: Icon(
|
|
||||||
isConnected ? Icons.link : Icons.link_off,
|
isConnected ? Icons.link : Icons.link_off,
|
||||||
color: isConnected
|
color: isConnected
|
||||||
? Theme.of(context).colorScheme.tertiary
|
? Theme.of(context).colorScheme.tertiary
|
||||||
@ -106,24 +104,18 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
|
|||||||
? 'Connected to GitHub.'
|
? 'Connected to GitHub.'
|
||||||
: 'Not connected to GitHub.',
|
: 'Not connected to GitHub.',
|
||||||
),
|
),
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
if (!isConnected)
|
if (!isConnected)
|
||||||
Tooltip(
|
ElevatedButton(
|
||||||
message: 'Connect',
|
|
||||||
child: ElevatedButton(
|
|
||||||
key: const ValueKey<String>('github-connect'),
|
key: const ValueKey<String>('github-connect'),
|
||||||
onPressed: _busy ? null : _connectGitHub,
|
onPressed: _busy ? null : _connectGitHub,
|
||||||
child: const Icon(
|
child: const Icon(
|
||||||
Icons.link,
|
Icons.link,
|
||||||
semanticLabel: 'Connect GitHub',
|
semanticLabel: 'Connect GitHub',
|
||||||
),
|
),
|
||||||
),
|
|
||||||
)
|
)
|
||||||
else
|
else
|
||||||
Tooltip(
|
OutlinedButton(
|
||||||
message: 'Disconnect',
|
|
||||||
child: OutlinedButton(
|
|
||||||
key: const ValueKey<String>('github-disconnect'),
|
key: const ValueKey<String>('github-disconnect'),
|
||||||
onPressed: _busy ? null : _disconnect,
|
onPressed: _busy ? null : _disconnect,
|
||||||
child: const Icon(
|
child: const Icon(
|
||||||
@ -131,7 +123,6 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
|
|||||||
semanticLabel: 'Disconnect GitHub',
|
semanticLabel: 'Disconnect GitHub',
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
StatusCue(semanticLabel: _status),
|
StatusCue(semanticLabel: _status),
|
||||||
],
|
],
|
||||||
|
|||||||
@ -55,10 +55,8 @@ class HomeBody extends StatelessWidget {
|
|||||||
final VoidCallback? onEscaped;
|
final VoidCallback? onEscaped;
|
||||||
|
|
||||||
IconData? _statusIcon(String status) {
|
IconData? _statusIcon(String status) {
|
||||||
if (status.contains('Connect a sync backend')) return Icons.cloud_off;
|
if (status.startsWith('Connect a sync backend')) return Icons.cloud_off;
|
||||||
if (status.contains('Sync store unavailable')) return Icons.sync_problem;
|
if (status.startsWith('Sync store unavailable')) return Icons.sync_problem;
|
||||||
// Saved and armed offline; the push rides the next sync.
|
|
||||||
if (status.contains('Saved locally')) return Icons.cloud_upload;
|
|
||||||
if (status.contains('✓')) return Icons.cloud_done;
|
if (status.contains('✓')) return Icons.cloud_done;
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -79,15 +77,12 @@ class HomeBody extends StatelessWidget {
|
|||||||
child: Column(
|
child: Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
Tooltip(
|
Icon(
|
||||||
message: 'Armed',
|
|
||||||
child: Icon(
|
|
||||||
Icons.alarm_on,
|
Icons.alarm_on,
|
||||||
size: 32,
|
size: 32,
|
||||||
color: theme.colorScheme.primary,
|
color: theme.colorScheme.primary,
|
||||||
semanticLabel: 'Alarm is armed for',
|
semanticLabel: 'Alarm is armed for',
|
||||||
),
|
),
|
||||||
),
|
|
||||||
HomePresenceLine(key: ValueKey<int>(syncEpoch)),
|
HomePresenceLine(key: ValueKey<int>(syncEpoch)),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Text(
|
Text(
|
||||||
@ -101,29 +96,23 @@ class HomeBody extends StatelessWidget {
|
|||||||
Row(
|
Row(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
Tooltip(
|
Icon(
|
||||||
message: 'Oneshot',
|
|
||||||
child: Icon(
|
|
||||||
Icons.restore,
|
Icons.restore,
|
||||||
size: 18,
|
size: 18,
|
||||||
semanticLabel:
|
semanticLabel:
|
||||||
'One-shot early start, back to $baseline '
|
'One-shot early start, back to $baseline '
|
||||||
'after it rings',
|
'after it rings',
|
||||||
),
|
),
|
||||||
),
|
|
||||||
Text(baseline),
|
Text(baseline),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
else
|
else
|
||||||
Tooltip(
|
Icon(
|
||||||
message: 'Daily',
|
|
||||||
child: Icon(
|
|
||||||
Icons.all_inclusive,
|
Icons.all_inclusive,
|
||||||
size: 18,
|
size: 18,
|
||||||
color: theme.colorScheme.onSurfaceVariant,
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
semanticLabel: 'Every day. It cannot be turned off.',
|
semanticLabel: 'Every day. It cannot be turned off.',
|
||||||
),
|
),
|
||||||
),
|
|
||||||
const SizedBox(height: 32),
|
const SizedBox(height: 32),
|
||||||
SizedBox(
|
SizedBox(
|
||||||
width: double.infinity,
|
width: double.infinity,
|
||||||
@ -150,15 +139,12 @@ class HomeBody extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
if (!configured) ...[
|
if (!configured) ...[
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Tooltip(
|
Icon(
|
||||||
message: 'Offline',
|
|
||||||
child: Icon(
|
|
||||||
Icons.cloud_off,
|
Icons.cloud_off,
|
||||||
size: 28,
|
size: 28,
|
||||||
color: theme.extension<AppStatusColors>()!.warning,
|
color: theme.extension<AppStatusColors>()!.warning,
|
||||||
semanticLabel: 'Open Settings to connect Firebase',
|
semanticLabel: 'Open Settings to connect Firebase',
|
||||||
),
|
),
|
||||||
),
|
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|||||||
@ -1,7 +1,6 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'dart:developer' as developer;
|
import 'dart:developer' as developer;
|
||||||
|
|
||||||
import 'package:flutter/services.dart';
|
|
||||||
import 'package:material_ui/material_ui.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';
|
||||||
@ -15,7 +14,6 @@ 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.
|
||||||
@ -119,12 +117,9 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
helpText: '',
|
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 '
|
||||||
@ -183,10 +178,9 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
semanticLabel: 'Free days',
|
semanticLabel: 'Free days',
|
||||||
),
|
),
|
||||||
tooltip: 'Free-days',
|
|
||||||
onPressed: () => Navigator.push<void>(
|
onPressed: () => Navigator.push<void>(
|
||||||
context,
|
context,
|
||||||
appRoute<void>(context, (_) => const FreeDaysScreen()),
|
MaterialPageRoute<void>(builder: (_) => const FreeDaysScreen()),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
@ -195,10 +189,9 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
semanticLabel: 'Sick days',
|
semanticLabel: 'Sick days',
|
||||||
),
|
),
|
||||||
tooltip: 'Sick-days',
|
|
||||||
onPressed: () => Navigator.push<void>(
|
onPressed: () => Navigator.push<void>(
|
||||||
context,
|
context,
|
||||||
appRoute<void>(context, (_) => const SickDaysScreen()),
|
MaterialPageRoute<void>(builder: (_) => const SickDaysScreen()),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
@ -211,9 +204,8 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
onPressed: () async {
|
onPressed: () async {
|
||||||
await Navigator.push<void>(
|
await Navigator.push<void>(
|
||||||
context,
|
context,
|
||||||
appRoute<void>(
|
MaterialPageRoute<void>(
|
||||||
context,
|
builder: (_) => SettingsScreen(alarmService: _service),
|
||||||
(_) => SettingsScreen(alarmService: _service),
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
// Publish too, not just reload: a tag registered in Settings
|
// Publish too, not just reload: a tag registered in Settings
|
||||||
|
|||||||
@ -62,19 +62,13 @@ class _RingStakesLineState extends State<RingStakesLine> {
|
|||||||
child: Row(
|
child: Row(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
Tooltip(
|
Icon(Icons.gavel_outlined, color: warningColor),
|
||||||
message: 'Deadline',
|
|
||||||
child: Icon(Icons.gavel_outlined, color: warningColor),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 4),
|
const SizedBox(width: 4),
|
||||||
Text(hhmm(stakes.by), style: TextStyle(color: warningColor)),
|
Text(hhmm(stakes.by), style: TextStyle(color: warningColor)),
|
||||||
const SizedBox(width: 4),
|
const SizedBox(width: 4),
|
||||||
const Icon(Icons.arrow_forward, size: 16),
|
const Icon(Icons.arrow_forward, size: 16),
|
||||||
const SizedBox(width: 4),
|
const SizedBox(width: 4),
|
||||||
Tooltip(
|
Icon(Icons.lock_outline, color: warningColor),
|
||||||
message: 'Lock',
|
|
||||||
child: Icon(Icons.lock_outline, color: warningColor),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 4),
|
const SizedBox(width: 4),
|
||||||
Text(
|
Text(
|
||||||
_formatLockDate(stakes.lockThrough),
|
_formatLockDate(stakes.lockThrough),
|
||||||
|
|||||||
@ -176,7 +176,7 @@ class _SessionScreenState extends State<SessionScreen> {
|
|||||||
// The native deadline already rang (see [AlarmScheduler.isRinging]):
|
// The native deadline already rang (see [AlarmScheduler.isRinging]):
|
||||||
// the dismiss sequence belongs in front now, not after the 20 s grace.
|
// the dismiss sequence belongs in front now, not after the 20 s grace.
|
||||||
if (session.isActive && await _scheduler.isRinging()) {
|
if (session.isActive && await _scheduler.isRinging()) {
|
||||||
await _ring(await nativeRingReason(_scheduler, session), now);
|
await _ring('deadline:${session.currentLeg!.name}', now);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
|
|||||||
@ -1,8 +1,5 @@
|
|||||||
import 'dart:developer' as developer;
|
import 'dart:developer' as developer;
|
||||||
|
|
||||||
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:material_ui/material_ui.dart';
|
||||||
import 'package:sync_settings_ui/sync_settings_ui.dart';
|
import 'package:sync_settings_ui/sync_settings_ui.dart';
|
||||||
|
|
||||||
@ -10,12 +7,10 @@ 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';
|
import 'package:wake_alarm_sync/ui/theme.dart';
|
||||||
|
|
||||||
/// Settings screen: links to the two sync surfaces.
|
/// Settings screen: links to the two sync surfaces.
|
||||||
@ -84,18 +79,7 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
actions: [
|
actions: [
|
||||||
// End-to-end encryption passphrase: a closed lock while the last
|
IconButton(
|
||||||
// sync found no usable key, so nothing reaches the PC until set.
|
|
||||||
ValueListenableBuilder<bool>(
|
|
||||||
valueListenable: alarmSyncLocked,
|
|
||||||
builder: (_, locked, _) => E2ePassphraseButton(
|
|
||||||
key: const Key('settings-e2e'),
|
|
||||||
locked: locked,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Tooltip(
|
|
||||||
message: 'Export',
|
|
||||||
child: IconButton(
|
|
||||||
key: const Key('settings-export'),
|
key: const Key('settings-export'),
|
||||||
icon: const Icon(Icons.upload_file, semanticLabel: 'Export data'),
|
icon: const Icon(Icons.upload_file, semanticLabel: 'Export data'),
|
||||||
onPressed: () => _run(context, () async {
|
onPressed: () => _run(context, () async {
|
||||||
@ -103,10 +87,7 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
return true;
|
return true;
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
),
|
IconButton(
|
||||||
Tooltip(
|
|
||||||
message: 'Import',
|
|
||||||
child: IconButton(
|
|
||||||
key: const Key('settings-import'),
|
key: const Key('settings-import'),
|
||||||
icon: const Icon(Icons.download, semanticLabel: 'Import data'),
|
icon: const Icon(Icons.download, semanticLabel: 'Import data'),
|
||||||
onPressed: () => _run(
|
onPressed: () => _run(
|
||||||
@ -114,7 +95,6 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
onImport ?? () => pickAndImport(alarm: alarmService),
|
onImport ?? () => pickAndImport(alarm: alarmService),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
body: ListView(
|
body: ListView(
|
||||||
@ -129,9 +109,8 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
trailing: const Icon(Icons.chevron_right),
|
trailing: const Icon(Icons.chevron_right),
|
||||||
onTap: () => Navigator.of(context).push<void>(
|
onTap: () => Navigator.of(context).push<void>(
|
||||||
appRoute<void>(
|
MaterialPageRoute(
|
||||||
context,
|
builder: (_) => SyncSettingsScreen(
|
||||||
(_) => SyncSettingsScreen(
|
|
||||||
accountLoader: loadAccount,
|
accountLoader: loadAccount,
|
||||||
accountSaver: saveAccount,
|
accountSaver: saveAccount,
|
||||||
accountClearer: clearAccount,
|
accountClearer: clearAccount,
|
||||||
@ -149,7 +128,7 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
leading: const Icon(Icons.nfc, semanticLabel: 'Room proof'),
|
leading: const Icon(Icons.nfc, semanticLabel: 'Room proof'),
|
||||||
trailing: const Icon(Icons.chevron_right),
|
trailing: const Icon(Icons.chevron_right),
|
||||||
onTap: () => Navigator.of(context).push<void>(
|
onTap: () => Navigator.of(context).push<void>(
|
||||||
appRoute<void>(context, (_) => const RoomProofScreen()),
|
MaterialPageRoute(builder: (_) => const RoomProofScreen()),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
ListTile(
|
ListTile(
|
||||||
@ -161,7 +140,7 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
trailing: const Icon(Icons.chevron_right),
|
trailing: const Icon(Icons.chevron_right),
|
||||||
onTap: () => Navigator.of(context).push<void>(
|
onTap: () => Navigator.of(context).push<void>(
|
||||||
appRoute<void>(context, (_) => const SessionTagsScreen()),
|
MaterialPageRoute(builder: (_) => const SessionTagsScreen()),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
ListTile(
|
ListTile(
|
||||||
@ -173,7 +152,7 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
trailing: const Icon(Icons.chevron_right),
|
trailing: const Icon(Icons.chevron_right),
|
||||||
onTap: () => Navigator.of(context).push<void>(
|
onTap: () => Navigator.of(context).push<void>(
|
||||||
appRoute<void>(context, (_) => const HomeLocationScreen()),
|
MaterialPageRoute(builder: (_) => const HomeLocationScreen()),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
ListTile(
|
ListTile(
|
||||||
@ -196,11 +175,9 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
onTap: () => Navigator.of(context).push<void>(
|
onTap: () => Navigator.of(context).push<void>(
|
||||||
appRoute<void>(context, (_) => const GitHubMirrorScreen()),
|
MaterialPageRoute(builder: (_) => const GitHubMirrorScreen()),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 24),
|
|
||||||
const Center(child: KuhyCredit()),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@ -32,10 +32,7 @@ class StakesMarks extends StatelessWidget {
|
|||||||
};
|
};
|
||||||
final rows = <Widget>[
|
final rows = <Widget>[
|
||||||
_row('title', view.title, <Widget>[
|
_row('title', view.title, <Widget>[
|
||||||
Tooltip(
|
Icon(kindIcon, color: theme.colorScheme.primary),
|
||||||
message: 'Stakes',
|
|
||||||
child: Icon(kindIcon, color: theme.colorScheme.primary),
|
|
||||||
),
|
|
||||||
Icon(view.isToday ? Icons.today : Icons.event, size: 18),
|
Icon(view.isToday ? Icons.today : Icons.event, size: 18),
|
||||||
Text(_dm(view.day), style: theme.textTheme.titleMedium),
|
Text(_dm(view.day), style: theme.textTheme.titleMedium),
|
||||||
]),
|
]),
|
||||||
@ -49,39 +46,34 @@ class StakesMarks extends StatelessWidget {
|
|||||||
if (dismissBy != null && lock != null) {
|
if (dismissBy != null && lock != null) {
|
||||||
rows.add(
|
rows.add(
|
||||||
_row('stick', words.first, <Widget>[
|
_row('stick', words.first, <Widget>[
|
||||||
const Tooltip(message: 'Alarm', child: Icon(Icons.alarm)),
|
const Icon(Icons.alarm),
|
||||||
Text(hhmm(dismissBy)),
|
Text(hhmm(dismissBy)),
|
||||||
const Icon(Icons.arrow_forward, size: 16),
|
const Icon(Icons.arrow_forward, size: 16),
|
||||||
const Tooltip(message: 'Lock', child: Icon(Icons.lock_outline)),
|
const Icon(Icons.lock_outline),
|
||||||
Text(_dm(lock)),
|
Text(_dm(lock)),
|
||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
} else if (finishBy != null && open != null) {
|
} else if (finishBy != null && open != null) {
|
||||||
rows.add(
|
rows.add(
|
||||||
_row('carrot', words.first, <Widget>[
|
_row('carrot', words.first, <Widget>[
|
||||||
const Tooltip(message: 'Finish', child: Icon(Icons.flag_outlined)),
|
const Icon(Icons.flag_outlined),
|
||||||
Text(hhmm(finishBy)),
|
Text(hhmm(finishBy)),
|
||||||
const Icon(Icons.arrow_forward, size: 16),
|
const Icon(Icons.arrow_forward, size: 16),
|
||||||
const Tooltip(message: 'PC', child: Icon(Icons.computer)),
|
const Icon(Icons.computer),
|
||||||
Text(_hm(open.hour, open.minute)),
|
Text(_hm(open.hour, open.minute)),
|
||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
} else if (view.kind != StakesDayKind.free &&
|
} else if (view.kind != StakesDayKind.free &&
|
||||||
view.kind != StakesDayKind.sick) {
|
view.kind != StakesDayKind.sick) {
|
||||||
rows.add(
|
rows.add(
|
||||||
_row('unarmed', words.first, const <Widget>[
|
_row('unarmed', words.first, const <Widget>[Icon(Icons.alarm_off)]),
|
||||||
Tooltip(message: 'Off', child: Icon(Icons.alarm_off)),
|
|
||||||
]),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (ring != null) {
|
if (ring != null) {
|
||||||
rows.add(
|
rows.add(
|
||||||
_row('pc-ring', words.last, <Widget>[
|
_row('pc-ring', words.last, <Widget>[
|
||||||
const Tooltip(message: 'PC', child: Icon(Icons.computer)),
|
const Icon(Icons.computer),
|
||||||
const Tooltip(
|
const Icon(Icons.notifications_active_outlined),
|
||||||
message: 'Ring',
|
|
||||||
child: Icon(Icons.notifications_active_outlined),
|
|
||||||
),
|
|
||||||
Text(hhmm(ring)),
|
Text(hhmm(ring)),
|
||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
@ -112,30 +104,18 @@ class StakesMarks extends StatelessWidget {
|
|||||||
return <Widget>[
|
return <Widget>[
|
||||||
if (view.escapedToday)
|
if (view.escapedToday)
|
||||||
_row('escaped', next(), <Widget>[
|
_row('escaped', next(), <Widget>[
|
||||||
Tooltip(
|
Icon(Icons.bug_report_outlined, color: warning),
|
||||||
message: 'Escaped',
|
|
||||||
child: Icon(Icons.bug_report_outlined, color: warning),
|
|
||||||
),
|
|
||||||
Icon(Icons.check, color: warning),
|
Icon(Icons.check, color: warning),
|
||||||
]),
|
]),
|
||||||
if (locked != null)
|
if (locked != null)
|
||||||
_row('locked', next(), <Widget>[
|
_row('locked', next(), <Widget>[
|
||||||
Tooltip(
|
Icon(Icons.lock_outline, color: warning),
|
||||||
message: 'Lock',
|
|
||||||
child: Icon(Icons.lock_outline, color: warning),
|
|
||||||
),
|
|
||||||
Text(_dm(locked), style: style),
|
Text(_dm(locked), style: style),
|
||||||
]),
|
]),
|
||||||
if (view.missedToday)
|
if (view.missedToday)
|
||||||
_row('missed', next(), <Widget>[
|
_row('missed', next(), <Widget>[
|
||||||
Tooltip(
|
Icon(Icons.close, color: warning),
|
||||||
message: 'Missed',
|
Icon(Icons.computer, color: warning),
|
||||||
child: Icon(Icons.close, color: warning),
|
|
||||||
),
|
|
||||||
Tooltip(
|
|
||||||
message: 'PC',
|
|
||||||
child: Icon(Icons.computer, color: warning),
|
|
||||||
),
|
|
||||||
]),
|
]),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@ -37,9 +37,7 @@ 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>{
|
||||||
@ -49,11 +47,6 @@ class AlarmArming {
|
|||||||
'android.intent.extra.alarm.MESSAGE': 'Wake Alarm',
|
'android.intent.extra.alarm.MESSAGE': 'Wake Alarm',
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
var completed = true;
|
await intent.launch().timeout(const Duration(seconds: 3), onTimeout: () {});
|
||||||
await intent.launch().timeout(
|
|
||||||
const Duration(seconds: 3),
|
|
||||||
onTimeout: () => completed = false,
|
|
||||||
);
|
|
||||||
return completed;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,4 +1,3 @@
|
|||||||
import 'package:http/http.dart' as http;
|
|
||||||
import 'package:wake_alarm_sync/services/alarm_arming.dart';
|
import 'package:wake_alarm_sync/services/alarm_arming.dart';
|
||||||
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
||||||
import 'package:wake_alarm_sync/services/alarm_sync_service.dart';
|
import 'package:wake_alarm_sync/services/alarm_sync_service.dart';
|
||||||
@ -11,10 +10,6 @@ import 'package:wake_alarm_sync/services/sync_settings.dart';
|
|||||||
/// Split out of `home_screen.dart` for the 250-line gate, and because none of
|
/// Split out of `home_screen.dart` for the 250-line gate, and because none of
|
||||||
/// this is UI: it returns a message for the screen to render rather than
|
/// this is UI: it returns a message for the screen to render rather than
|
||||||
/// calling `setState` itself, which also makes it testable without a widget.
|
/// calling `setState` itself, which also makes it testable without a widget.
|
||||||
///
|
|
||||||
/// Offline-first: the local half — storing the time and arming the phone —
|
|
||||||
/// always runs. The sync half degrades to a status line, and the next
|
|
||||||
/// publish (app start, settings return, an earlier tap) retries it.
|
|
||||||
class AlarmPublisher {
|
class AlarmPublisher {
|
||||||
/// Creates a publisher; [arming] is injectable for tests.
|
/// Creates a publisher; [arming] is injectable for tests.
|
||||||
AlarmPublisher({AlarmArming? arming})
|
AlarmPublisher({AlarmArming? arming})
|
||||||
@ -26,88 +21,42 @@ class AlarmPublisher {
|
|||||||
/// Publishes [hour]:[minute] and arms the alarm, returning a status line.
|
/// Publishes [hour]:[minute] and arms the alarm, returning a status line.
|
||||||
///
|
///
|
||||||
/// Never throws: this runs unattended from the app's init seam, so a sync
|
/// Never throws: this runs unattended from the app's init seam, so a sync
|
||||||
/// failure must degrade to a message rather than take the screen down.
|
/// failure must degrade to a message rather than take the screen down. The
|
||||||
|
/// alarm itself is already armed by `main()` regardless of what happens
|
||||||
|
/// here — publishing is how the PC learns the time, not how the phone rings.
|
||||||
Future<String> publish({
|
Future<String> publish({
|
||||||
required AlarmSyncService? service,
|
required AlarmSyncService? service,
|
||||||
required int hour,
|
required int hour,
|
||||||
required int minute,
|
required int minute,
|
||||||
http.Client? httpClient,
|
|
||||||
}) async {
|
}) async {
|
||||||
// The local half first: store the time (when a store exists) and arm the
|
|
||||||
// phone. Neither depends on a backend or the network, so the alarm is set
|
|
||||||
// even on a plane — the sync status below is the only thing that cannot
|
|
||||||
// complete offline.
|
|
||||||
String? armProblem;
|
|
||||||
var inClock = false;
|
|
||||||
Exception? saveError;
|
|
||||||
if (service != null) {
|
|
||||||
try {
|
|
||||||
await service.setLocal(hour, minute);
|
|
||||||
} on Exception catch (e) {
|
|
||||||
// The log could not be written, so the PC must not be told
|
|
||||||
// "synced": pushing now would publish the previous time.
|
|
||||||
saveError = e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
armProblem = await arming.arm(hour, minute);
|
|
||||||
if (armProblem == null) {
|
|
||||||
inClock = await arming.registerWithClockApp(hour, minute);
|
|
||||||
}
|
|
||||||
} on Exception catch (e) {
|
|
||||||
armProblem ??= 'Error: $e';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (saveError != null) {
|
|
||||||
return armProblem ?? '${armedFor(hour, minute)}Error: $saveError';
|
|
||||||
}
|
|
||||||
|
|
||||||
// The sync half: stage the settings that ride on the record, push, take
|
|
||||||
// the winners back into prefs (how a fresh install gets its tags).
|
|
||||||
if (service != null) {
|
|
||||||
final settings = await SyncSettings.load();
|
final settings = await SyncSettings.load();
|
||||||
// syncBackend() falls back to GitHub alone, or pushes to Firebase alone
|
// syncBackend() falls back to GitHub alone, or pushes to Firebase alone
|
||||||
// via the mirror, so either credential is enough to proceed.
|
// via the mirror, so either credential is enough to proceed.
|
||||||
final configured = settings.isConfigured || await loadAccount() != null;
|
final hasFirebase = await loadAccount() != null;
|
||||||
if (configured) {
|
if (!settings.isConfigured && !hasFirebase) {
|
||||||
|
return 'Connect a sync backend in Settings first.';
|
||||||
|
}
|
||||||
|
// Distinct from the above on purpose. Both used to report "connect a
|
||||||
|
// backend", so a store that failed to open looked like a configuration
|
||||||
|
// the user had never done -- and the advice was to fix something that
|
||||||
|
// was not broken.
|
||||||
|
if (service == null) {
|
||||||
|
return 'Sync store unavailable — reopen the app.';
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
|
await service.setLocal(hour, minute);
|
||||||
|
// Tags and home ride on the same record: stage local edits, sync
|
||||||
|
// (pull, merge, push), then take whatever won back into prefs. That
|
||||||
|
// last step is how a fresh install gets its tags back.
|
||||||
await stageLocalSettings(service);
|
await stageLocalSettings(service);
|
||||||
await service.push(settings.token, httpClient: httpClient);
|
await service.push(settings.token);
|
||||||
await applySyncedSettings(service);
|
await applySyncedSettings(service);
|
||||||
|
final problem = await arming.arm(hour, minute);
|
||||||
|
if (problem != null) return problem;
|
||||||
|
await arming.registerWithClockApp(hour, minute);
|
||||||
|
return 'Synced to PC ✓';
|
||||||
} on Exception catch (e) {
|
} on Exception catch (e) {
|
||||||
// The local save and the arming are already done; only the push
|
return 'Error: $e';
|
||||||
// failed. Say so — the time is not lost, it rides the next publish.
|
|
||||||
return armProblem ??
|
|
||||||
'${armedFor(hour, minute)}Saved locally — will sync to PC. '
|
|
||||||
'Error: $e';
|
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
return armProblem ??
|
|
||||||
'${armedFor(hour, minute)}'
|
|
||||||
'Connect a sync backend in Settings first.';
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Distinct from the "connect a backend" line on purpose. Both used to
|
|
||||||
// report the same thing, so a store that failed to open looked like a
|
|
||||||
// configuration the user had never done.
|
|
||||||
return armProblem ??
|
|
||||||
'${armedFor(hour, minute)}Sync store unavailable — reopen the app.';
|
|
||||||
}
|
|
||||||
return armProblem ?? syncedStatus(hour, minute, inClock: inClock);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The "Armed for HH:MM." prefix every status line shares: the local arm is
|
|
||||||
/// what succeeded, whatever the sync half reports.
|
|
||||||
String armedFor(int hour, int minute) =>
|
|
||||||
'Armed for '
|
|
||||||
'${hour.toString().padLeft(2, '0')}:'
|
|
||||||
'${minute.toString().padLeft(2, '0')}. ';
|
|
||||||
|
|
||||||
/// The success line, naming the armed time; names the Clock app only when
|
|
||||||
/// the handoff to it completed before its timeout, so a silent timeout
|
|
||||||
/// never claims it.
|
|
||||||
String syncedStatus(int hour, int minute, {required bool inClock}) {
|
|
||||||
final synced = '${armedFor(hour, minute)}Synced to PC ✓';
|
|
||||||
return inClock ? '$synced Clock app set ✓' : synced;
|
|
||||||
}
|
|
||||||
|
|||||||
@ -207,16 +207,6 @@ 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`.
|
||||||
///
|
///
|
||||||
|
|||||||
@ -1,59 +0,0 @@
|
|||||||
/// 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,7 +7,6 @@ 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.
|
||||||
@ -18,8 +17,7 @@ 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-e2e/<deviceId>/alarm.json`, end-to-end
|
/// to `wake-alarm-sync/devices/<deviceId>/alarm.json` — Firebase first,
|
||||||
/// 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.
|
||||||
@ -164,17 +162,11 @@ 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: sealed,
|
client: client,
|
||||||
deviceId: deviceId,
|
deviceId: deviceId,
|
||||||
pathPrefix: alarmLayout.prefix,
|
pathPrefix: 'wake-alarm-sync/devices',
|
||||||
revsPath: alarmLayout.revsPath,
|
|
||||||
filename: 'alarm.json',
|
filename: 'alarm.json',
|
||||||
localLog: _store.snapshot(),
|
localLog: _store.snapshot(),
|
||||||
encode: logToJson,
|
encode: logToJson,
|
||||||
|
|||||||
@ -1,64 +0,0 @@
|
|||||||
/// 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,7 +17,6 @@ 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.
|
||||||
///
|
///
|
||||||
@ -49,7 +48,6 @@ 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),
|
||||||
@ -84,7 +82,6 @@ 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
|
||||||
@ -116,7 +113,6 @@ 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,
|
||||||
@ -218,8 +214,6 @@ 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,6 +1,5 @@
|
|||||||
import 'dart:developer' as developer;
|
import 'dart:developer' as developer;
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart' show debugPrint;
|
|
||||||
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/enforcement_bridge.dart';
|
import 'package:wake_alarm_sync/services/enforcement_bridge.dart';
|
||||||
import 'package:wake_alarm_sync/services/enforcement_sync.dart';
|
import 'package:wake_alarm_sync/services/enforcement_sync.dart';
|
||||||
@ -61,10 +60,7 @@ class RingStartRecorder {
|
|||||||
if (await RingStartedStore.publishedOn(entry['date'])) return true;
|
if (await RingStartedStore.publishedOn(entry['date'])) return true;
|
||||||
final settings = await SyncSettings.load();
|
final settings = await SyncSettings.load();
|
||||||
final hasFirebase = await loadAccount() != null;
|
final hasFirebase = await loadAccount() != null;
|
||||||
if (!settings.isConfigured && !hasFirebase) {
|
if (!settings.isConfigured && !hasFirebase) return false;
|
||||||
_log('ring_started not published: no sync backend');
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
final service = await _open();
|
final service = await _open();
|
||||||
// Only the enforcement fields: the ring is no time to restage tags
|
// Only the enforcement fields: the ring is no time to restage tags
|
||||||
// and history, and the push carries the whole log regardless.
|
// and history, and the push carries the whole log regardless.
|
||||||
@ -83,9 +79,5 @@ class RingStartRecorder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// developer.log is invisible in a release build; logcat needs debugPrint.
|
void _log(String message) => developer.log(message, name: 'WakeAlarmRing');
|
||||||
void _log(String message) {
|
|
||||||
debugPrint('WakeAlarmRing: $message');
|
|
||||||
developer.log(message, name: 'WakeAlarmRing');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +1,4 @@
|
|||||||
import 'dart:async';
|
|
||||||
|
|
||||||
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
||||||
import 'package:wake_alarm_sync/services/enforcement_publish.dart';
|
|
||||||
import 'package:wake_alarm_sync/services/morning_session.dart';
|
import 'package:wake_alarm_sync/services/morning_session.dart';
|
||||||
import 'package:wake_alarm_sync/services/session_rules.dart';
|
import 'package:wake_alarm_sync/services/session_rules.dart';
|
||||||
import 'package:wake_alarm_sync/services/session_store.dart';
|
import 'package:wake_alarm_sync/services/session_store.dart';
|
||||||
@ -19,10 +16,8 @@ class SessionHandoff {
|
|||||||
required this.scheduler,
|
required this.scheduler,
|
||||||
SessionStore? store,
|
SessionStore? store,
|
||||||
DateTime Function()? now,
|
DateTime Function()? now,
|
||||||
Future<bool> Function()? publishNow,
|
|
||||||
}) : store = store ?? SessionStore(),
|
}) : store = store ?? SessionStore(),
|
||||||
_now = now ?? DateTime.now,
|
_now = now ?? DateTime.now;
|
||||||
_publishNow = publishNow ?? publishEnforcementNow;
|
|
||||||
|
|
||||||
/// Platform bridge, for the NFC availability check.
|
/// Platform bridge, for the NFC availability check.
|
||||||
final AlarmScheduler scheduler;
|
final AlarmScheduler scheduler;
|
||||||
@ -32,10 +27,6 @@ class SessionHandoff {
|
|||||||
|
|
||||||
final DateTime Function() _now;
|
final DateTime Function() _now;
|
||||||
|
|
||||||
/// Pushes the `dismissed` event at once: the PC rings for a bypass until
|
|
||||||
/// it reads one newer than the bypass.
|
|
||||||
final Future<bool> Function() _publishNow;
|
|
||||||
|
|
||||||
/// Starts or resumes today's session; false when the ring should just end.
|
/// Starts or resumes today's session; false when the ring should just end.
|
||||||
///
|
///
|
||||||
/// [away] is the ring's verdict that the phone is not at home: no scale,
|
/// [away] is the ring's verdict that the phone is not at home: no scale,
|
||||||
@ -47,16 +38,12 @@ class SessionHandoff {
|
|||||||
// recorded before anything else so an interrupted await below still
|
// recorded before anything else so an interrupted await below still
|
||||||
// leaves the native side knowing the ring was answered.
|
// leaves the native side knowing the ring was answered.
|
||||||
await scheduler.markRingDismissed();
|
await scheduler.markRingDismissed();
|
||||||
// Not awaited: the session must not wait on the network.
|
|
||||||
unawaited(_publishNow());
|
|
||||||
final now = _now();
|
final now = _now();
|
||||||
final today = SessionRules.dateKey(now);
|
final today = SessionRules.dateKey(now);
|
||||||
final current = await store.loadCurrent();
|
final current = await store.loadCurrent();
|
||||||
if (current != null && current.date == today) {
|
if (current != null && current.date == today) {
|
||||||
if (!current.isActive) return false;
|
if (!current.isActive) return false;
|
||||||
current
|
current.recordReRing(now);
|
||||||
..adoptBypassReRing(await scheduler.takeBypassReRing())
|
|
||||||
..recordReRing(now);
|
|
||||||
await store.save(current);
|
await store.save(current);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -34,13 +34,6 @@ Future<void> pointNativeAtLeg(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Why the sound the session screen just found is ringing: the bypass
|
|
||||||
/// `Bypass.kt` stamped for it, else the live leg's deadline.
|
|
||||||
Future<String> nativeRingReason(
|
|
||||||
AlarmScheduler scheduler,
|
|
||||||
MorningSession session,
|
|
||||||
) async => session.reRingReasonFor(await scheduler.peekBypassReRing());
|
|
||||||
|
|
||||||
/// The notification's one line: glyph + position count, with a running-clock
|
/// The notification's one line: glyph + position count, with a running-clock
|
||||||
/// marker when the re-ring was spent.
|
/// marker when the re-ring was spent.
|
||||||
String noticeLabel(MorningSession session) {
|
String noticeLabel(MorningSession session) {
|
||||||
|
|||||||
@ -1,6 +1,5 @@
|
|||||||
import 'dart:developer' as developer;
|
import 'dart:developer' as developer;
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart' show debugPrint;
|
|
||||||
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/firebase_backend.dart';
|
import 'package:wake_alarm_sync/services/firebase_backend.dart';
|
||||||
import 'package:wake_alarm_sync/services/settings_sync.dart';
|
import 'package:wake_alarm_sync/services/settings_sync.dart';
|
||||||
@ -33,8 +32,6 @@ class SessionPublisher {
|
|||||||
await applySyncedSettings(service);
|
await applySyncedSettings(service);
|
||||||
return 'Session synced to PC ✓';
|
return 'Session synced to PC ✓';
|
||||||
} on Exception catch (e, stack) {
|
} on Exception catch (e, stack) {
|
||||||
// developer.log is invisible in a release build; logcat needs print.
|
|
||||||
debugPrint('WakeAlarmSession: session publish failed: $e');
|
|
||||||
developer.log(
|
developer.log(
|
||||||
'session publish failed: $e',
|
'session publish failed: $e',
|
||||||
name: 'WakeAlarmSession',
|
name: 'WakeAlarmSession',
|
||||||
|
|||||||
@ -162,18 +162,6 @@ extension SessionRules on MorningSession {
|
|||||||
updatedAt = now;
|
updatedAt = now;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Names the re-ring a bypass started natively (`Bypass.kt` stamps
|
|
||||||
/// [cause] only when nothing was ringing yet), overriding a deadline mark:
|
|
||||||
/// the screen saw the sound before it saw why. Null leaves the mark.
|
|
||||||
void adoptBypassReRing(String? cause) {
|
|
||||||
if (cause != null) pendingReRingReason = reRingReasonFor(cause);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `bypass:<cause>` for a bypass's re-ring, else the live leg's deadline.
|
|
||||||
String reRingReasonFor(String? cause) => cause == null
|
|
||||||
? 'deadline:${currentLeg?.name ?? 'none'}'
|
|
||||||
: 'bypass:$cause';
|
|
||||||
|
|
||||||
/// Records that a re-ring was dismissed; the session resumes here.
|
/// Records that a re-ring was dismissed; the session resumes here.
|
||||||
///
|
///
|
||||||
/// A leg whose deadline has already passed is marked as rung whatever the
|
/// A leg whose deadline has already passed is marked as rung whatever the
|
||||||
@ -182,7 +170,7 @@ extension SessionRules on MorningSession {
|
|||||||
void recordReRing(DateTime now) {
|
void recordReRing(DateTime now) {
|
||||||
final leg = currentLeg;
|
final leg = currentLeg;
|
||||||
reRings++;
|
reRings++;
|
||||||
reRingReasons.add(pendingReRingReason ?? reRingReasonFor(null));
|
reRingReasons.add(pendingReRingReason ?? 'deadline:${leg?.name ?? 'none'}');
|
||||||
pendingReRingReason = null;
|
pendingReRingReason = null;
|
||||||
if (leg != null && !now.isBefore(deadline(leg))) deadlineRung.add(leg);
|
if (leg != null && !now.isBefore(deadline(leg))) deadlineRung.add(leg);
|
||||||
updatedAt = now;
|
updatedAt = now;
|
||||||
|
|||||||
@ -1,51 +0,0 @@
|
|||||||
/// A debug-only sync backend: the Firebase RTDB emulator on the PC.
|
|
||||||
///
|
|
||||||
/// The emulator checks (a bypass reaching "the test backend") need a
|
|
||||||
/// backend, and the AVD must never sign in to prod: a probe's per-date
|
|
||||||
/// merge would overwrite the phone's real morning. So the probe build
|
|
||||||
/// passes `--dart-define=WAKE_SYNC_EMULATOR=http://10.0.2.2:9000` (the AVD's
|
|
||||||
/// name for the PC's loopback), and every sync open then returns this client
|
|
||||||
/// *instead of* prod Firebase and the GitHub mirror, never beside them.
|
|
||||||
///
|
|
||||||
/// The define is a compile-time constant: release and `deploy.sh` builds
|
|
||||||
/// never set it, so there the branch is dead code. The emulator answers
|
|
||||||
/// `auth=owner` as admin, so no Google sign-in is involved.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
|
||||||
import 'package:http/http.dart' as http;
|
|
||||||
|
|
||||||
/// The emulator's origin, or empty (every release build).
|
|
||||||
const String kSyncEmulatorUrl = String.fromEnvironment('WAKE_SYNC_EMULATOR');
|
|
||||||
|
|
||||||
/// Whether this build syncs to the emulator only.
|
|
||||||
bool get syncEmulatorOn => kSyncEmulatorUrl.isNotEmpty;
|
|
||||||
|
|
||||||
/// The account marker the sync gates look for; carries no credential.
|
|
||||||
const FirebaseAccount emulatorAccount = FirebaseAccount(
|
|
||||||
email: 'emulator',
|
|
||||||
password: '',
|
|
||||||
);
|
|
||||||
|
|
||||||
/// Signs every request `auth=owner`, the emulator's admin token.
|
|
||||||
class EmulatorTokenProvider extends FirebaseTokenProvider {
|
|
||||||
/// Creates a provider that never talks to Google.
|
|
||||||
EmulatorTokenProvider()
|
|
||||||
: super(apiKey: 'emulator', store: InMemoryCredentialStore());
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<String> idToken() async => 'owner';
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<bool> hasSession() async => true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A client for the emulator at [url].
|
|
||||||
FirebaseRestClient emulatorClient({
|
|
||||||
String url = kSyncEmulatorUrl,
|
|
||||||
http.Client? httpClient,
|
|
||||||
}) => FirebaseRestClient(
|
|
||||||
databaseUrl: url,
|
|
||||||
auth: EmulatorTokenProvider(),
|
|
||||||
httpClient: httpClient,
|
|
||||||
);
|
|
||||||
@ -7,8 +7,7 @@ import 'dart:math' show pi, sin;
|
|||||||
|
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
import 'package:material_ui/material_ui.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/ui/theme.dart'
|
import 'package:wake_alarm_sync/ui/theme.dart' show AppStatusColors;
|
||||||
show AppStatusColors, MotionDuration;
|
|
||||||
|
|
||||||
export 'package:wake_alarm_sync/ui/spoken_label.dart';
|
export 'package:wake_alarm_sync/ui/spoken_label.dart';
|
||||||
|
|
||||||
@ -37,15 +36,6 @@ enum CueKind {
|
|||||||
CueKind? cueKindOf(String status) {
|
CueKind? cueKindOf(String status) {
|
||||||
if (status.isEmpty) return null;
|
if (status.isEmpty) return null;
|
||||||
if (status.endsWith('…') || status.endsWith('...')) return CueKind.busy;
|
if (status.endsWith('…') || status.endsWith('...')) return CueKind.busy;
|
||||||
// Checked before the error/ok keywords: an offline-first publish prefixes
|
|
||||||
// every line with "Armed for HH:MM." (the local half succeeded), so a
|
|
||||||
// pending sync must not read as a plain success, nor a dead network as a
|
|
||||||
// failure — the time is saved and rides the next sync.
|
|
||||||
if (status.contains('Saved locally') ||
|
|
||||||
status.contains('Connect a sync backend') ||
|
|
||||||
status.contains('Open Settings')) {
|
|
||||||
return CueKind.warning;
|
|
||||||
}
|
|
||||||
|
|
||||||
const errorKeywords = [
|
const errorKeywords = [
|
||||||
'Error',
|
'Error',
|
||||||
@ -81,6 +71,10 @@ CueKind? cueKindOf(String status) {
|
|||||||
if (status.contains(kw)) return CueKind.ok;
|
if (status.contains(kw)) return CueKind.ok;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (status.contains('Connect a sync backend') ||
|
||||||
|
status.contains('Open Settings')) {
|
||||||
|
return CueKind.warning;
|
||||||
|
}
|
||||||
return CueKind.info;
|
return CueKind.info;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -133,7 +127,7 @@ class _StatusCueState extends State<StatusCue>
|
|||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
_shakeCtrl = AnimationController(
|
_shakeCtrl = AnimationController(
|
||||||
duration: MotionDuration.slow,
|
duration: const Duration(milliseconds: 300),
|
||||||
vsync: this,
|
vsync: this,
|
||||||
);
|
);
|
||||||
_shakeAnim = Tween<double>(
|
_shakeAnim = Tween<double>(
|
||||||
|
|||||||
@ -1,27 +0,0 @@
|
|||||||
/// The app's one page route: slow slide, decelerate in, accelerate out.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:material_ui/material_ui.dart';
|
|
||||||
import 'package:wake_alarm_sync/ui/theme.dart';
|
|
||||||
|
|
||||||
/// A route to [builder]'s page using the shared motion tokens; instant under
|
|
||||||
/// the OS "Remove animations" setting.
|
|
||||||
PageRoute<T> appRoute<T>(BuildContext context, WidgetBuilder builder) {
|
|
||||||
final duration = motionDuration(context, MotionDuration.slow);
|
|
||||||
return PageRouteBuilder<T>(
|
|
||||||
transitionDuration: duration,
|
|
||||||
reverseTransitionDuration: duration,
|
|
||||||
pageBuilder: (context, _, _) => builder(context),
|
|
||||||
transitionsBuilder: (context, animation, secondary, child) {
|
|
||||||
final slide = Tween<Offset>(begin: const Offset(1, 0), end: Offset.zero)
|
|
||||||
.animate(
|
|
||||||
CurvedAnimation(
|
|
||||||
parent: animation,
|
|
||||||
curve: MotionCurve.decelerate,
|
|
||||||
reverseCurve: MotionCurve.accelerate,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return SlideTransition(position: slide, child: child);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -121,36 +121,3 @@ class DayMarkColors extends ThemeExtension<DayMarkColors> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Motion durations, hand-copied from the shared `DOCS-motion.md`.
|
|
||||||
abstract final class MotionDuration {
|
|
||||||
/// No animation; the reduced-motion target.
|
|
||||||
static const Duration instant = Duration.zero;
|
|
||||||
|
|
||||||
/// State on an element already under the finger.
|
|
||||||
static const fast = Duration(milliseconds: 120);
|
|
||||||
|
|
||||||
/// Default: anything entering or leaving within the current view.
|
|
||||||
static const base = Duration(milliseconds: 200);
|
|
||||||
|
|
||||||
/// Full-surface change: page transitions. The ceiling.
|
|
||||||
static const slow = Duration(milliseconds: 320);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Motion curves, hand-copied from the shared `DOCS-motion.md`.
|
|
||||||
abstract final class MotionCurve {
|
|
||||||
/// Default start-and-end-on-screen curve.
|
|
||||||
static const standard = Cubic(0.2, 0, 0, 1);
|
|
||||||
|
|
||||||
/// Entering the screen.
|
|
||||||
static const decelerate = Cubic(0, 0, 0, 1);
|
|
||||||
|
|
||||||
/// Leaving the screen.
|
|
||||||
static const accelerate = Cubic(0.3, 0, 1, 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// [token], or zero when the OS "Remove animations" setting is on.
|
|
||||||
Duration motionDuration(BuildContext context, Duration token) =>
|
|
||||||
(MediaQuery.maybeDisableAnimationsOf(context) ?? false)
|
|
||||||
? MotionDuration.instant
|
|
||||||
: token;
|
|
||||||
|
|||||||
@ -5,10 +5,10 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: android_file_picker
|
name: android_file_picker
|
||||||
sha256: ec3cf2a2c7a9b2bd56747e85f80efdd994e563049dfb0981a23903acfdd58cb5
|
sha256: "04c1306eda42c23ecbf449c909f4fa05c5e66fc48cf5f994d8d08b9d45e5396b"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.2.0"
|
version: "2.1.5"
|
||||||
android_intent_plus:
|
android_intent_plus:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
@ -101,20 +101,11 @@ packages:
|
|||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
path: crdt_sync_dart
|
path: crdt_sync_dart
|
||||||
ref: "crdt_sync_dart-v0.14.2"
|
ref: "crdt_sync_dart-v0.13.1"
|
||||||
resolved-ref: "171a7f8ae34cec78df17a680e42878ca0b97c137"
|
resolved-ref: eebeb0b51053f160f163140141aba10a447ba1e8
|
||||||
url: "https://github.com/kuhyx/utils"
|
url: "https://github.com/kuhyx/utils"
|
||||||
source: git
|
source: git
|
||||||
version: "0.14.2"
|
version: "0.13.1"
|
||||||
crdt_sync_flutter:
|
|
||||||
dependency: "direct main"
|
|
||||||
description:
|
|
||||||
path: crdt_sync_flutter
|
|
||||||
ref: "crdt_sync_flutter-v0.9.2"
|
|
||||||
resolved-ref: "41af57870207f80a5bf571f15544a08fddcbe7bf"
|
|
||||||
url: "https://github.com/kuhyx/utils"
|
|
||||||
source: git
|
|
||||||
version: "0.9.2"
|
|
||||||
cross_file:
|
cross_file:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -159,11 +150,11 @@ packages:
|
|||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
path: data_transfer_flutter
|
path: data_transfer_flutter
|
||||||
ref: "data_transfer_flutter-v0.2.4"
|
ref: "data_transfer_flutter-v0.2.2"
|
||||||
resolved-ref: "5c2effe7d1148830c9e273e47a272791dc17509e"
|
resolved-ref: eef7af4c86837ee82891493587ff3456297e5dea
|
||||||
url: "https://github.com/kuhyx/utils"
|
url: "https://github.com/kuhyx/utils"
|
||||||
source: git
|
source: git
|
||||||
version: "0.2.4"
|
version: "0.2.2"
|
||||||
dbus:
|
dbus:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -208,10 +199,10 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: file_picker
|
name: file_picker
|
||||||
sha256: "5b99250437a4d34ee2cdc0686924452103540eaa1c248094b63f07f9d7216f6c"
|
sha256: "079dc46b753abbddb7f77cd87e6ed9ecc62902580707514568321bdf8e050a86"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "13.4.1"
|
version: "13.3.3"
|
||||||
file_picker_darwin:
|
file_picker_darwin:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -224,18 +215,18 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: file_picker_linux
|
name: file_picker_linux
|
||||||
sha256: cf3889644e8e54551f5c3a4f98b6b6ef5f0ef85c07d2a0c1a969538983be2f9b
|
sha256: "9215ee8c672508cdd9a325202669f849e1baac883658626b3abed5d7777e6a4b"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.0.5"
|
version: "2.0.4"
|
||||||
file_picker_platform_interface:
|
file_picker_platform_interface:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: file_picker_platform_interface
|
name: file_picker_platform_interface
|
||||||
sha256: a2ef71c4628f92a4471d424576e3bf7042b40a2683c9f9a0e3033a7fc7f7763c
|
sha256: "336e7168306834a2b68e6168ed768e00d3fabeac23154d5793e277ca9f97cf20"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "4.3.0"
|
version: "4.2.0"
|
||||||
file_picker_web:
|
file_picker_web:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -396,11 +387,11 @@ packages:
|
|||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
path: github_device_auth
|
path: github_device_auth
|
||||||
ref: "github_device_auth-v0.5.1"
|
ref: "github_device_auth-v0.5.0"
|
||||||
resolved-ref: da1d7c0692e2e402ae4944f2425b36a55ad43e9c
|
resolved-ref: "0ef5461805e8f574de5174c940775e5245d675b3"
|
||||||
url: "https://github.com/kuhyx/utils"
|
url: "https://github.com/kuhyx/utils"
|
||||||
source: git
|
source: git
|
||||||
version: "0.5.1"
|
version: "0.5.0"
|
||||||
google_account_token:
|
google_account_token:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
@ -474,15 +465,6 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "4.12.0"
|
version: "4.12.0"
|
||||||
kuhy_credit:
|
|
||||||
dependency: "direct main"
|
|
||||||
description:
|
|
||||||
path: "kuhy_credit/flutter"
|
|
||||||
ref: "kuhy-credit-v0.3.2"
|
|
||||||
resolved-ref: adeb40f68e1d6c701da43e396fc46bffa3ef10c7
|
|
||||||
url: "https://github.com/kuhyx/utils"
|
|
||||||
source: git
|
|
||||||
version: "0.3.2"
|
|
||||||
leak_tracker:
|
leak_tracker:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -543,10 +525,10 @@ packages:
|
|||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
name: material_ui
|
name: material_ui
|
||||||
sha256: a6b19012df437a356cbc01f8ea22a105e07194c47c9a6009da0032a0ce35c4ab
|
sha256: "474c135fd46b56ff1d35ca982155e8863d28fbc6464d1192acf4ee53a738680e"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.11.1"
|
version: "1.11.0"
|
||||||
meta:
|
meta:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -579,22 +561,6 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.2.0"
|
version: "2.2.0"
|
||||||
package_info_plus:
|
|
||||||
dependency: transitive
|
|
||||||
description:
|
|
||||||
name: package_info_plus
|
|
||||||
sha256: "73ef2cd5c11a7548f9b7f6fc2a4f6113de2e64aa2a70de63feede95548822908"
|
|
||||||
url: "https://pub.dev"
|
|
||||||
source: hosted
|
|
||||||
version: "10.2.2"
|
|
||||||
package_info_plus_platform_interface:
|
|
||||||
dependency: transitive
|
|
||||||
description:
|
|
||||||
name: package_info_plus_platform_interface
|
|
||||||
sha256: db762cb2f4f25ee60fb6359773861b0f199e00b90d237bd85a76a1e806b46ef4
|
|
||||||
url: "https://pub.dev"
|
|
||||||
source: hosted
|
|
||||||
version: "4.1.0"
|
|
||||||
path:
|
path:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
@ -812,11 +778,11 @@ packages:
|
|||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
path: sync_settings_ui
|
path: sync_settings_ui
|
||||||
ref: "sync_settings_ui-v0.8.6"
|
ref: "sync_settings_ui-v0.8.0"
|
||||||
resolved-ref: "41af57870207f80a5bf571f15544a08fddcbe7bf"
|
resolved-ref: "0ef5461805e8f574de5174c940775e5245d675b3"
|
||||||
url: "https://github.com/kuhyx/utils"
|
url: "https://github.com/kuhyx/utils"
|
||||||
source: git
|
source: git
|
||||||
version: "0.8.6"
|
version: "0.8.0"
|
||||||
term_glyph:
|
term_glyph:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
|||||||
@ -12,21 +12,15 @@ dependencies:
|
|||||||
crdt_sync:
|
crdt_sync:
|
||||||
git:
|
git:
|
||||||
url: https://github.com/kuhyx/utils
|
url: https://github.com/kuhyx/utils
|
||||||
ref: crdt_sync_dart-v0.14.2
|
ref: crdt_sync_dart-v0.13.1
|
||||||
path: crdt_sync_dart
|
path: crdt_sync_dart
|
||||||
# Keystore-backed end-to-end encryption open + the passphrase lock button.
|
|
||||||
crdt_sync_flutter:
|
|
||||||
git:
|
|
||||||
url: https://github.com/kuhyx/utils
|
|
||||||
ref: crdt_sync_flutter-v0.9.2
|
|
||||||
path: crdt_sync_flutter
|
|
||||||
cupertino_icons: 2.0.0
|
cupertino_icons: 2.0.0
|
||||||
|
|
||||||
# Shared JSON export/import plumbing (Save-as, picker, envelope).
|
# Shared JSON export/import plumbing (Save-as, picker, envelope).
|
||||||
data_transfer_flutter:
|
data_transfer_flutter:
|
||||||
git:
|
git:
|
||||||
url: https://github.com/kuhyx/utils
|
url: https://github.com/kuhyx/utils
|
||||||
ref: data_transfer_flutter-v0.2.4
|
ref: data_transfer_flutter-v0.2.2
|
||||||
path: data_transfer_flutter
|
path: data_transfer_flutter
|
||||||
flutter:
|
flutter:
|
||||||
sdk: flutter
|
sdk: flutter
|
||||||
@ -37,7 +31,7 @@ dependencies:
|
|||||||
github_device_auth:
|
github_device_auth:
|
||||||
git:
|
git:
|
||||||
url: https://github.com/kuhyx/utils
|
url: https://github.com/kuhyx/utils
|
||||||
ref: github_device_auth-v0.5.1
|
ref: github_device_auth-v0.5.0
|
||||||
path: github_device_auth
|
path: github_device_auth
|
||||||
google_account_token:
|
google_account_token:
|
||||||
git:
|
git:
|
||||||
@ -45,12 +39,7 @@ dependencies:
|
|||||||
ref: google_account_token-v0.1.0
|
ref: google_account_token-v0.1.0
|
||||||
path: google_account_token
|
path: google_account_token
|
||||||
http: 1.6.0
|
http: 1.6.0
|
||||||
kuhy_credit:
|
material_ui: 1.11.0
|
||||||
git:
|
|
||||||
url: https://github.com/kuhyx/utils
|
|
||||||
ref: kuhy-credit-v0.3.2
|
|
||||||
path: kuhy_credit/flutter
|
|
||||||
material_ui: 1.11.1
|
|
||||||
path: 1.9.1
|
path: 1.9.1
|
||||||
path_provider: 2.1.6
|
path_provider: 2.1.6
|
||||||
shared_preferences: 2.5.6
|
shared_preferences: 2.5.6
|
||||||
@ -61,7 +50,7 @@ dependencies:
|
|||||||
sync_settings_ui:
|
sync_settings_ui:
|
||||||
git:
|
git:
|
||||||
url: https://github.com/kuhyx/utils
|
url: https://github.com/kuhyx/utils
|
||||||
ref: sync_settings_ui-v0.8.6
|
ref: sync_settings_ui-v0.8.0
|
||||||
path: sync_settings_ui
|
path: sync_settings_ui
|
||||||
url_launcher: 6.3.3
|
url_launcher: 6.3.3
|
||||||
uuid: 4.6.0
|
uuid: 4.6.0
|
||||||
|
|||||||
@ -1,26 +0,0 @@
|
|||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
import 'package:material_ui/material_ui.dart';
|
|
||||||
import 'package:wake_alarm_sync/main.dart';
|
|
||||||
import 'package:wake_alarm_sync/screens/settings_screen.dart';
|
|
||||||
|
|
||||||
/// crdt_sync_flutter's passphrase dialog (0.8.2 imports material_ui, so it is
|
|
||||||
/// material_ui's `AlertDialog`) must open from the settings lock icon without
|
|
||||||
/// a localization exception.
|
|
||||||
void main() {
|
|
||||||
testWidgets('the settings lock icon opens the passphrase dialog', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await tester.pumpWidget(const WakeAlarmSyncApp());
|
|
||||||
navigatorKey.currentState!.push(
|
|
||||||
MaterialPageRoute<void>(builder: (_) => const SettingsScreen()),
|
|
||||||
);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
await tester.tap(find.byKey(const Key('settings-e2e')));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
expect(tester.takeException(), isNull);
|
|
||||||
expect(find.byType(AlertDialog), findsOneWidget);
|
|
||||||
expect(find.byType(EditableText), findsOneWidget);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@ -1,92 +0,0 @@
|
|||||||
/// Shared end-to-end encryption plumbing for the sync tests.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'dart:convert';
|
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
|
||||||
import 'package:http/http.dart' as http;
|
|
||||||
import 'package:http/testing.dart' as http_testing;
|
|
||||||
import 'package:wake_alarm_sync/services/alarm_sync_e2e.dart';
|
|
||||||
|
|
||||||
import 'fake_secure_storage.dart';
|
|
||||||
|
|
||||||
/// The passphrase every test device shares.
|
|
||||||
const testPassphrase = 'test-passphrase';
|
|
||||||
|
|
||||||
/// A keystore holding [testPassphrase], cheap Argon2id, a fresh copy memo.
|
|
||||||
void installE2eTestStorage({Map<String, String>? initial}) {
|
|
||||||
e2eArgon2Params = const Argon2Params(
|
|
||||||
memoryKiB: 8,
|
|
||||||
iterations: 1,
|
|
||||||
parallelism: 1,
|
|
||||||
);
|
|
||||||
resetE2eCopyMemo();
|
|
||||||
installFakeSecureStorage(
|
|
||||||
initial: {'crdt_sync_e2e_passphrase': testPassphrase, ...?initial},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A GitHub Contents API stand-in that stores what is PUT and lists
|
|
||||||
/// directories from it, so the encryption header reads back.
|
|
||||||
class MemGitHub {
|
|
||||||
/// Starts holding [files] (repo path -> text).
|
|
||||||
MemGitHub([Map<String, String>? files]) : files = {...?files};
|
|
||||||
|
|
||||||
/// Repo path -> text.
|
|
||||||
final Map<String, String> files;
|
|
||||||
|
|
||||||
/// Every PUT path, in order.
|
|
||||||
final List<String> putPaths = [];
|
|
||||||
|
|
||||||
/// The mock HTTP client.
|
|
||||||
late final http.Client httpClient = http_testing.MockClient(_handle);
|
|
||||||
|
|
||||||
/// A [GitHubClient] over [httpClient].
|
|
||||||
GitHubClient client() =>
|
|
||||||
GitHubClient(owner: 'o', repo: 'r', token: 't', httpClient: httpClient);
|
|
||||||
|
|
||||||
/// The decrypted text at [path], read like another device would.
|
|
||||||
Future<String?> opened(String path) async {
|
|
||||||
final state = await openEncryptedStore(
|
|
||||||
store: client(),
|
|
||||||
oldPrefix: legacyAlarmPrefix,
|
|
||||||
readPassphrase: () async => testPassphrase,
|
|
||||||
);
|
|
||||||
return await (state as E2eReady).store.getFileText(path);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<http.Response> _handle(http.Request request) async {
|
|
||||||
final path = request.url.path;
|
|
||||||
if (!path.contains('/contents/')) return http.Response('{}', 200);
|
|
||||||
final key = path.split('/contents/').last;
|
|
||||||
if (request.method == 'PUT') {
|
|
||||||
final body = jsonDecode(request.body) as Map<String, dynamic>;
|
|
||||||
files[key] = utf8.decode(base64.decode(body['content'] as String));
|
|
||||||
putPaths.add(key);
|
|
||||||
return http.Response('{}', 200);
|
|
||||||
}
|
|
||||||
final text = files[key];
|
|
||||||
if (text != null) {
|
|
||||||
return http.Response(
|
|
||||||
jsonEncode({'content': base64.encode(utf8.encode(text)), 'sha': 's'}),
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
final names = {
|
|
||||||
for (final k in files.keys)
|
|
||||||
if (k.startsWith('$key/')) k.substring(key.length + 1).split('/')[0],
|
|
||||||
};
|
|
||||||
if (names.isEmpty) return http.Response('{}', 404);
|
|
||||||
return http.Response(
|
|
||||||
jsonEncode([
|
|
||||||
for (final n in names)
|
|
||||||
{
|
|
||||||
'type': files.containsKey('$key/$n') ? 'file' : 'dir',
|
|
||||||
'name': n,
|
|
||||||
'path': '$key/$n',
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,65 +1,9 @@
|
|||||||
import 'dart:io';
|
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
|
||||||
import 'package:flutter/services.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
import 'package:http/http.dart' as http;
|
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
import 'package:wake_alarm_sync/services/alarm_arming.dart';
|
|
||||||
import 'package:wake_alarm_sync/services/alarm_publisher.dart';
|
import 'package:wake_alarm_sync/services/alarm_publisher.dart';
|
||||||
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
|
||||||
import 'package:wake_alarm_sync/services/alarm_sync_service.dart';
|
|
||||||
|
|
||||||
import '../e2e_support.dart';
|
|
||||||
import '../fake_day_pool_store.dart';
|
|
||||||
import '../fake_secure_storage.dart';
|
import '../fake_secure_storage.dart';
|
||||||
|
|
||||||
/// Persistence whose writes start failing once [failing] is set.
|
|
||||||
class _FailingWrites extends MemPersistence {
|
|
||||||
bool failing = false;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> write(String value) async {
|
|
||||||
if (failing) throw const FileSystemException('disk gone');
|
|
||||||
await super.write(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Records the platform arms instead of touching the real channel.
|
|
||||||
class _RecordingScheduler extends AlarmScheduler {
|
|
||||||
_RecordingScheduler() : super(channel: const MethodChannel('test/alarm'));
|
|
||||||
|
|
||||||
final List<String> calls = [];
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<bool> canUseFullScreenIntent() async => true;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> schedule(int hour, int minute) async {
|
|
||||||
calls.add('schedule $hour:$minute');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Completes the Clock handoff without launching an intent.
|
|
||||||
class _RecordingArming extends AlarmArming {
|
|
||||||
_RecordingArming(super.scheduler);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<bool> registerWithClockApp(int hour, int minute) async => true;
|
|
||||||
}
|
|
||||||
|
|
||||||
class _OfflineClient extends http.BaseClient {
|
|
||||||
@override
|
|
||||||
Future<http.StreamedResponse> send(http.BaseRequest request) =>
|
|
||||||
throw http.ClientException('offline');
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<AlarmSyncService> _service({LogPersistence? persistence}) =>
|
|
||||||
AlarmSyncService.open(
|
|
||||||
persistence: persistence ?? MemPersistence(),
|
|
||||||
deviceId: 'test-device',
|
|
||||||
);
|
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
TestWidgetsFlutterBinding.ensureInitialized();
|
TestWidgetsFlutterBinding.ensureInitialized();
|
||||||
|
|
||||||
@ -69,17 +13,12 @@ void main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('an unconfigured install is told to connect a backend', () async {
|
test('an unconfigured install is told to connect a backend', () async {
|
||||||
final scheduler = _RecordingScheduler();
|
final message = await AlarmPublisher().publish(
|
||||||
final service = await _service();
|
service: null,
|
||||||
final message = await AlarmPublisher(
|
hour: 8,
|
||||||
arming: _RecordingArming(scheduler),
|
minute: 0,
|
||||||
).publish(service: service, hour: 8, minute: 0);
|
);
|
||||||
// Offline-first: the time is stored locally and the phone is armed even
|
|
||||||
// though nothing can be pushed yet.
|
|
||||||
expect(service.currentAlarm, (hour: 8, minute: 0));
|
|
||||||
expect(message, contains('Armed for 08:00'));
|
|
||||||
expect(message, contains('Connect a sync backend'));
|
expect(message, contains('Connect a sync backend'));
|
||||||
expect(scheduler.calls, ['schedule 8:0']);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('a missing store is not reported as a missing backend', () async {
|
test('a missing store is not reported as a missing backend', () async {
|
||||||
@ -91,88 +30,12 @@ void main() {
|
|||||||
SharedPreferences.setMockInitialValues(<String, Object>{
|
SharedPreferences.setMockInitialValues(<String, Object>{
|
||||||
'github_token': 'ghp_configured',
|
'github_token': 'ghp_configured',
|
||||||
});
|
});
|
||||||
final scheduler = _RecordingScheduler();
|
final message = await AlarmPublisher().publish(
|
||||||
final message = await AlarmPublisher(
|
service: null,
|
||||||
arming: _RecordingArming(scheduler),
|
hour: 8,
|
||||||
).publish(service: null, hour: 8, minute: 0);
|
minute: 0,
|
||||||
expect(message, contains('Armed for 08:00'));
|
);
|
||||||
expect(message, isNot(contains('Connect a sync backend')));
|
expect(message, isNot(contains('Connect a sync backend')));
|
||||||
expect(message, contains('Sync store unavailable'));
|
expect(message, contains('Sync store unavailable'));
|
||||||
expect(scheduler.calls, ['schedule 8:0']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a failed push keeps the phone armed and says it will sync', () async {
|
|
||||||
installE2eTestStorage();
|
|
||||||
SharedPreferences.setMockInitialValues(<String, Object>{
|
|
||||||
'github_token': 'ghp_configured',
|
|
||||||
});
|
|
||||||
final scheduler = _RecordingScheduler();
|
|
||||||
final service = await _service();
|
|
||||||
final message = await AlarmPublisher(arming: _RecordingArming(scheduler))
|
|
||||||
.publish(
|
|
||||||
service: service,
|
|
||||||
hour: 7,
|
|
||||||
minute: 30,
|
|
||||||
httpClient: _OfflineClient(),
|
|
||||||
);
|
|
||||||
expect(service.currentAlarm, (hour: 7, minute: 30));
|
|
||||||
expect(message, contains('Armed for 07:30'));
|
|
||||||
expect(message, contains('Saved locally'));
|
|
||||||
expect(message, contains('Error'));
|
|
||||||
expect(scheduler.calls, ['schedule 7:30']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a failed local save is reported, never "synced"', () async {
|
|
||||||
installE2eTestStorage();
|
|
||||||
SharedPreferences.setMockInitialValues(<String, Object>{
|
|
||||||
'github_token': 'ghp_configured',
|
|
||||||
});
|
|
||||||
final github = MemGitHub();
|
|
||||||
final persistence = _FailingWrites();
|
|
||||||
final service = await _service(persistence: persistence);
|
|
||||||
persistence.failing = true;
|
|
||||||
final message =
|
|
||||||
await AlarmPublisher(
|
|
||||||
arming: _RecordingArming(_RecordingScheduler()),
|
|
||||||
).publish(
|
|
||||||
service: service,
|
|
||||||
hour: 6,
|
|
||||||
minute: 45,
|
|
||||||
httpClient: github.httpClient,
|
|
||||||
);
|
|
||||||
expect(message, contains('Armed for 06:45'));
|
|
||||||
expect(message, contains('Error'));
|
|
||||||
expect(message, isNot(contains('Synced')));
|
|
||||||
expect(github.putPaths, isEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a push on a live mirror ends with the synced line', () async {
|
|
||||||
installE2eTestStorage();
|
|
||||||
SharedPreferences.setMockInitialValues(<String, Object>{
|
|
||||||
'github_token': 'ghp_configured',
|
|
||||||
});
|
|
||||||
final github = MemGitHub();
|
|
||||||
final scheduler = _RecordingScheduler();
|
|
||||||
final message = await AlarmPublisher(arming: _RecordingArming(scheduler))
|
|
||||||
.publish(
|
|
||||||
service: await _service(),
|
|
||||||
hour: 7,
|
|
||||||
minute: 15,
|
|
||||||
httpClient: github.httpClient,
|
|
||||||
);
|
|
||||||
expect(message, 'Armed for 07:15. Synced to PC ✓ Clock app set ✓');
|
|
||||||
expect(scheduler.calls, ['schedule 7:15']);
|
|
||||||
expect(github.putPaths, isNotEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('the Clock line names the time only when the handoff completed', () {
|
|
||||||
expect(
|
|
||||||
syncedStatus(6, 5, inClock: true),
|
|
||||||
'Armed for 06:05. Synced to PC ✓ Clock app set ✓',
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
syncedStatus(6, 5, inClock: false),
|
|
||||||
'Armed for 06:05. Synced to PC ✓',
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,14 +2,13 @@ import 'dart:convert';
|
|||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart' as http_testing;
|
||||||
import 'package:wake_alarm_sync/services/alarm_sync_service.dart';
|
import 'package:wake_alarm_sync/services/alarm_sync_service.dart';
|
||||||
|
|
||||||
import '../e2e_support.dart';
|
|
||||||
|
|
||||||
const _deviceId = 'this-install';
|
const _deviceId = 'this-install';
|
||||||
const _peerId = 'previous-install';
|
const _peerId = 'previous-install';
|
||||||
const _old = 'wake-alarm-sync/devices';
|
const _prefix = 'wake-alarm-sync/devices';
|
||||||
const _prefix = 'wake-alarm-sync/devices-e2e';
|
|
||||||
|
|
||||||
class _MemPersistence implements LogPersistence {
|
class _MemPersistence implements LogPersistence {
|
||||||
String? text;
|
String? text;
|
||||||
@ -21,6 +20,45 @@ class _MemPersistence implements LogPersistence {
|
|||||||
Future<void> write(String value) async => text = value;
|
Future<void> write(String value) async => text = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
http.Response _json(Object body, [int status = 200]) =>
|
||||||
|
http.Response(jsonEncode(body), status);
|
||||||
|
|
||||||
|
/// Mock GitHub Contents API with one peer directory holding [peerLog].
|
||||||
|
///
|
||||||
|
/// The directory GET answers the listing `syncLog` walks, the peer's file GET
|
||||||
|
/// answers the pull, and every PUT is recorded so the merged push can be
|
||||||
|
/// inspected.
|
||||||
|
({http.Client client, List<Map<String, dynamic>> pushes}) _mockRemote({
|
||||||
|
Map<String, dynamic>? peerLog,
|
||||||
|
}) {
|
||||||
|
final pushes = <Map<String, dynamic>>[];
|
||||||
|
final client = http_testing.MockClient((request) async {
|
||||||
|
final path = request.url.path;
|
||||||
|
if (!path.contains('/contents/')) return _json({});
|
||||||
|
final key = path.split('/contents/').last;
|
||||||
|
if (request.method == 'PUT') {
|
||||||
|
final body = jsonDecode(request.body) as Map<String, dynamic>;
|
||||||
|
final text = utf8.decode(base64.decode(body['content'] as String));
|
||||||
|
pushes.add(jsonDecode(text) as Map<String, dynamic>);
|
||||||
|
return _json({});
|
||||||
|
}
|
||||||
|
if (key == _prefix) {
|
||||||
|
return _json([
|
||||||
|
if (peerLog != null) {'name': _peerId, 'type': 'dir'},
|
||||||
|
{'name': _deviceId, 'type': 'dir'},
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
if (key == '$_prefix/$_peerId/alarm.json' && peerLog != null) {
|
||||||
|
return _json({
|
||||||
|
'content': base64.encode(utf8.encode(jsonEncode(peerLog))),
|
||||||
|
'encoding': 'base64',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return _json({}, 404);
|
||||||
|
});
|
||||||
|
return (client: client, pushes: pushes);
|
||||||
|
}
|
||||||
|
|
||||||
Map<String, dynamic> _peerRecord(Map<String, Object?> fields, String hlc) => {
|
Map<String, dynamic> _peerRecord(Map<String, Object?> fields, String hlc) => {
|
||||||
'alarm': {
|
'alarm': {
|
||||||
'id': 'alarm',
|
'id': 'alarm',
|
||||||
@ -36,8 +74,6 @@ void main() {
|
|||||||
late AlarmSyncService service;
|
late AlarmSyncService service;
|
||||||
|
|
||||||
setUp(() async {
|
setUp(() async {
|
||||||
TestWidgetsFlutterBinding.ensureInitialized();
|
|
||||||
installE2eTestStorage();
|
|
||||||
service = await AlarmSyncService.open(
|
service = await AlarmSyncService.open(
|
||||||
persistence: _MemPersistence(),
|
persistence: _MemPersistence(),
|
||||||
deviceId: _deviceId,
|
deviceId: _deviceId,
|
||||||
@ -65,18 +101,20 @@ void main() {
|
|||||||
|
|
||||||
test('pushWith pulls a previous install and takes its newer field', () async {
|
test('pushWith pulls a previous install and takes its newer field', () async {
|
||||||
await service.setLocal(8, 0);
|
await service.setLocal(8, 0);
|
||||||
// The previous install never updated: its record sits in plaintext on
|
final (:client, :pushes) = _mockRemote(
|
||||||
// the old prefix and reaches this one through the one-time E2E copy.
|
peerLog: _peerRecord({
|
||||||
final remote = MemGitHub({
|
|
||||||
'$_old/$_peerId/alarm.json': jsonEncode(
|
|
||||||
_peerRecord({
|
|
||||||
'alarm_hour': 7,
|
'alarm_hour': 7,
|
||||||
'alarm_minute': 0,
|
'alarm_minute': 0,
|
||||||
'nfc_tag_ids': ['x', 'y'],
|
'nfc_tag_ids': ['x', 'y'],
|
||||||
}, '2026-09-11T10:26:18.254Z-0000-$_peerId'),
|
}, '2026-09-11T10:26:18.254Z-0000-$_peerId'),
|
||||||
),
|
);
|
||||||
});
|
final github = GitHubClient(
|
||||||
final github = remote.client();
|
owner: 'o',
|
||||||
|
repo: 'r',
|
||||||
|
token: 't',
|
||||||
|
httpClient: client,
|
||||||
|
);
|
||||||
|
|
||||||
await service.pushWith(github);
|
await service.pushWith(github);
|
||||||
|
|
||||||
// The peer's tags are merged in; the peer's older alarm loses to the
|
// The peer's tags are merged in; the peer's older alarm loses to the
|
||||||
@ -84,23 +122,25 @@ void main() {
|
|||||||
expect(service.field('nfc_tag_ids')?.$1, ['x', 'y']);
|
expect(service.field('nfc_tag_ids')?.$1, ['x', 'y']);
|
||||||
expect(service.currentAlarm, (hour: 8, minute: 0));
|
expect(service.currentAlarm, (hour: 8, minute: 0));
|
||||||
// And the merged result is what was pushed, under this install's path.
|
// And the merged result is what was pushed, under this install's path.
|
||||||
const path = '$_prefix/$_deviceId/alarm.json';
|
expect(pushes, hasLength(1));
|
||||||
expect(remote.files[path], isNot(contains('nfc_tag_ids')));
|
final fields = (pushes.single['alarm'] as Map)['fields'] as Map;
|
||||||
final pushed = jsonDecode((await remote.opened(path))!) as Map;
|
|
||||||
final fields = (pushed['alarm'] as Map)['fields'] as Map;
|
|
||||||
expect((fields['nfc_tag_ids'] as List).first, ['x', 'y']);
|
expect((fields['nfc_tag_ids'] as List).first, ['x', 'y']);
|
||||||
expect((fields['alarm_hour'] as List).first, 8);
|
expect((fields['alarm_hour'] as List).first, 8);
|
||||||
// The old plaintext node is copied, never rewritten.
|
|
||||||
expect(remote.putPaths.where((p) => p.startsWith('$_old/')), isEmpty);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('pushWith with no peers pushes the local log unchanged', () async {
|
test('pushWith with no peers pushes the local log unchanged', () async {
|
||||||
await service.setLocal(8, 0);
|
await service.setLocal(8, 0);
|
||||||
final remote = MemGitHub();
|
final (:client, :pushes) = _mockRemote();
|
||||||
|
final github = GitHubClient(
|
||||||
|
owner: 'o',
|
||||||
|
repo: 'r',
|
||||||
|
token: 't',
|
||||||
|
httpClient: client,
|
||||||
|
);
|
||||||
|
|
||||||
await service.pushWith(remote.client());
|
await service.pushWith(github);
|
||||||
|
|
||||||
expect(remote.putPaths, contains('$_prefix/$_deviceId/alarm.json'));
|
expect(pushes, hasLength(1));
|
||||||
expect(service.field('nfc_tag_ids'), isNull);
|
expect(service.field('nfc_tag_ids'), isNull);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@ -6,13 +6,13 @@ import 'package:http/http.dart' as http;
|
|||||||
import 'package:http/testing.dart' as http_testing;
|
import 'package:http/testing.dart' as http_testing;
|
||||||
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/alarm_sync_service.dart';
|
import 'package:wake_alarm_sync/services/alarm_sync_service.dart';
|
||||||
|
|
||||||
import '../e2e_support.dart';
|
|
||||||
|
|
||||||
const _deviceId = 'test-device-uuid';
|
const _deviceId = 'test-device-uuid';
|
||||||
const _alarmPath = 'wake-alarm-sync/devices-e2e/$_deviceId/alarm.json';
|
const _alarmPath = 'wake-alarm-sync/devices/$_deviceId/alarm.json';
|
||||||
|
|
||||||
|
http.Response _response(int statusCode, [Object? jsonBody]) =>
|
||||||
|
http.Response(jsonEncode(jsonBody ?? {}), statusCode);
|
||||||
|
|
||||||
/// In-memory persistence so the store never touches the real documents dir.
|
/// In-memory persistence so the store never touches the real documents dir.
|
||||||
class _MemPersistence implements LogPersistence {
|
class _MemPersistence implements LogPersistence {
|
||||||
@ -25,12 +25,39 @@ class _MemPersistence implements LogPersistence {
|
|||||||
Future<void> write(String value) async => text = value;
|
Future<void> write(String value) async => text = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
void main() {
|
class _PutCall {
|
||||||
setUp(() {
|
_PutCall(this.path, this.body);
|
||||||
TestWidgetsFlutterBinding.ensureInitialized();
|
final String path;
|
||||||
installE2eTestStorage();
|
final Map<String, dynamic> body;
|
||||||
});
|
}
|
||||||
|
|
||||||
|
/// Mock GitHub Contents API: GET `.../contents/<key>` returns
|
||||||
|
/// [contentResponses]`[key]` (404 if absent), the bare repo-existence GET
|
||||||
|
/// always succeeds, and every PUT is recorded. Mirrors the workout_app test.
|
||||||
|
({http.Client httpClient, List<_PutCall> putCalls}) _mockGitHub({
|
||||||
|
Map<String, http.Response> contentResponses = const {},
|
||||||
|
}) {
|
||||||
|
final putCalls = <_PutCall>[];
|
||||||
|
final client = http_testing.MockClient((request) async {
|
||||||
|
final path = request.url.path;
|
||||||
|
if (!path.contains('/contents/')) return _response(200);
|
||||||
|
final key = path.split('/contents/').last;
|
||||||
|
if (request.method == 'PUT') {
|
||||||
|
putCalls.add(
|
||||||
|
_PutCall(key, jsonDecode(request.body) as Map<String, dynamic>),
|
||||||
|
);
|
||||||
|
return _response(200);
|
||||||
|
}
|
||||||
|
return contentResponses[key] ?? _response(404);
|
||||||
|
});
|
||||||
|
return (httpClient: client, putCalls: putCalls);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> _decodePush(_PutCall call) =>
|
||||||
|
jsonDecode(utf8.decode(base64.decode(call.body['content'] as String)))
|
||||||
|
as Map<String, dynamic>;
|
||||||
|
|
||||||
|
void main() {
|
||||||
test('currentAlarm is null before anything is set', () async {
|
test('currentAlarm is null before anything is set', () async {
|
||||||
final service = await AlarmSyncService.open(
|
final service = await AlarmSyncService.open(
|
||||||
persistence: _MemPersistence(),
|
persistence: _MemPersistence(),
|
||||||
@ -62,14 +89,13 @@ void main() {
|
|||||||
deviceId: _deviceId,
|
deviceId: _deviceId,
|
||||||
);
|
);
|
||||||
await service.setLocal(7, 15);
|
await service.setLocal(7, 15);
|
||||||
final remote = MemGitHub();
|
final (:httpClient, :putCalls) = _mockGitHub();
|
||||||
|
|
||||||
await service.push('tok', httpClient: remote.httpClient);
|
await service.push('tok', httpClient: httpClient);
|
||||||
|
|
||||||
expect(remote.putPaths, contains(_alarmPath));
|
expect(putCalls, hasLength(1));
|
||||||
expect(remote.files[_alarmPath], isNot(contains('alarm_hour')));
|
expect(putCalls.single.path, _alarmPath);
|
||||||
final pushed =
|
final pushed = _decodePush(putCalls.single);
|
||||||
jsonDecode((await remote.opened(_alarmPath))!) as Map<String, dynamic>;
|
|
||||||
final fields =
|
final fields =
|
||||||
(pushed['alarm'] as Map<String, dynamic>)['fields']
|
(pushed['alarm'] as Map<String, dynamic>)['fields']
|
||||||
as Map<String, dynamic>;
|
as Map<String, dynamic>;
|
||||||
@ -77,27 +103,6 @@ void main() {
|
|||||||
expect((fields['alarm_minute'] as List).first, 15);
|
expect((fields['alarm_minute'] as List).first, 15);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('a device with no passphrase pushes nothing', () async {
|
|
||||||
installE2eTestStorage(initial: {'crdt_sync_e2e_passphrase': ''});
|
|
||||||
final service = await AlarmSyncService.open(
|
|
||||||
persistence: _MemPersistence(),
|
|
||||||
deviceId: _deviceId,
|
|
||||||
);
|
|
||||||
await service.setLocal(7, 15);
|
|
||||||
final remote = MemGitHub();
|
|
||||||
|
|
||||||
await expectLater(
|
|
||||||
service.push('tok', httpClient: remote.httpClient),
|
|
||||||
throwsA(isA<SyncLockedException>()),
|
|
||||||
);
|
|
||||||
expect(remote.putPaths, isEmpty);
|
|
||||||
expect(alarmSyncLocked.value, isTrue);
|
|
||||||
expect(
|
|
||||||
const SyncLockedException(E2eLockReason.wrongKey).toString(),
|
|
||||||
contains('wrongKey'),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('push is a network round-trip that swallows a server error', () async {
|
test('push is a network round-trip that swallows a server error', () async {
|
||||||
final service = await AlarmSyncService.open(
|
final service = await AlarmSyncService.open(
|
||||||
persistence: _MemPersistence(),
|
persistence: _MemPersistence(),
|
||||||
@ -156,18 +161,19 @@ void main() {
|
|||||||
deviceId: 'uuid-abc',
|
deviceId: 'uuid-abc',
|
||||||
);
|
);
|
||||||
await service.setLocal(6, 30);
|
await service.setLocal(6, 30);
|
||||||
final remote = MemGitHub();
|
final paths = <String>[];
|
||||||
|
final client = http_testing.MockClient((request) async {
|
||||||
|
paths.add(request.url.path);
|
||||||
|
return _response(200);
|
||||||
|
});
|
||||||
|
|
||||||
await service.push('tok', httpClient: remote.httpClient);
|
await service.push('tok', httpClient: client);
|
||||||
|
|
||||||
final paths = remote.putPaths;
|
expect(paths.any((path) => path.contains('devices/uuid-abc/')), isTrue);
|
||||||
expect(
|
|
||||||
paths.any((path) => path.contains('devices-e2e/uuid-abc/')),
|
|
||||||
isTrue,
|
|
||||||
);
|
|
||||||
expect(
|
expect(
|
||||||
paths.any(
|
paths.any(
|
||||||
(path) => path.contains('/${AlarmSyncService.legacyDeviceId}/'),
|
(path) =>
|
||||||
|
path.contains('devices/${AlarmSyncService.legacyDeviceId}/'),
|
||||||
),
|
),
|
||||||
isFalse,
|
isFalse,
|
||||||
);
|
);
|
||||||
|
|||||||
@ -1,67 +0,0 @@
|
|||||||
import 'package:flutter/services.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
|
||||||
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
|
||||||
import 'package:wake_alarm_sync/services/enforcement_publish.dart';
|
|
||||||
import 'package:wake_alarm_sync/services/headless_ring_start.dart';
|
|
||||||
import 'package:wake_alarm_sync/services/session_handoff.dart';
|
|
||||||
|
|
||||||
/// A bypass and a dismiss reach the PC at once, not at the next sync
|
|
||||||
/// (2026-11-22): the PC rings for a bypass until it sees a newer dismiss.
|
|
||||||
void main() {
|
|
||||||
TestWidgetsFlutterBinding.ensureInitialized();
|
|
||||||
|
|
||||||
late List<String> calls;
|
|
||||||
|
|
||||||
setUp(() {
|
|
||||||
calls = <String>[];
|
|
||||||
SharedPreferences.setMockInitialValues(<String, Object>{});
|
|
||||||
for (final name in [headlessChannelName, AlarmScheduler.channelName]) {
|
|
||||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
|
||||||
.setMockMethodCallHandler(MethodChannel(name), (call) async {
|
|
||||||
calls.add(call.method);
|
|
||||||
return null;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test('the headless publish pushes once, then says done', () async {
|
|
||||||
var published = 0;
|
|
||||||
await runHeadlessPublish(
|
|
||||||
publish: () async {
|
|
||||||
published++;
|
|
||||||
return true;
|
|
||||||
},
|
|
||||||
);
|
|
||||||
expect(published, 1);
|
|
||||||
expect(calls, ['done']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('done is sent even when the publish blows up', () async {
|
|
||||||
await expectLater(
|
|
||||||
runHeadlessPublish(publish: () async => throw StateError('boom')),
|
|
||||||
throwsStateError,
|
|
||||||
);
|
|
||||||
expect(calls, ['done']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('with no sync backend nothing is pushed', () async {
|
|
||||||
expect(await publishEnforcementNow(), isFalse);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a dismiss publishes at once, after telling native', () async {
|
|
||||||
final order = <String>[];
|
|
||||||
final handoff = SessionHandoff(
|
|
||||||
scheduler: AlarmScheduler(),
|
|
||||||
now: () => DateTime(2026, 11, 22, 7, 40),
|
|
||||||
publishNow: () async {
|
|
||||||
order
|
|
||||||
..addAll(calls)
|
|
||||||
..add('publish');
|
|
||||||
return true;
|
|
||||||
},
|
|
||||||
);
|
|
||||||
await handoff.afterDismiss(away: true);
|
|
||||||
expect(order, ['markRingDismissed', 'publish']);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@ -1,31 +0,0 @@
|
|||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
import 'package:wake_alarm_sync/services/morning_session.dart';
|
|
||||||
import 'package:wake_alarm_sync/services/session_rules.dart';
|
|
||||||
import 'package:wake_alarm_sync/services/session_tag_settings.dart';
|
|
||||||
|
|
||||||
final DateTime t0 = DateTime(2026, 9, 17, 8, 5);
|
|
||||||
|
|
||||||
MorningSession fresh() => SessionRules.start(
|
|
||||||
now: t0,
|
|
||||||
tags: const SessionTagSettings(tagIds: <String>['bath', 'ward', 'desk']),
|
|
||||||
nfcAvailable: true,
|
|
||||||
);
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
test('a bypass re-ring is named for its cause and counted once', () {
|
|
||||||
final s = fresh()
|
|
||||||
..markReRing('deadline:bathroomIn', t0)
|
|
||||||
..adoptBypassReRing('fsi_revoked')
|
|
||||||
..recordReRing(t0.add(const Duration(minutes: 3)));
|
|
||||||
expect(s.reRings, 1);
|
|
||||||
expect(s.reRingReasons, <String>['bypass:fsi_revoked']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('no bypass stamped keeps the deadline reason', () {
|
|
||||||
final s = fresh()
|
|
||||||
..markReRing('deadline:bathroomIn', t0)
|
|
||||||
..adoptBypassReRing(null)
|
|
||||||
..recordReRing(t0.add(const Duration(minutes: 3)));
|
|
||||||
expect(s.reRingReasons, <String>['deadline:bathroomIn']);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@ -13,12 +13,10 @@ void main() {
|
|||||||
|
|
||||||
final now = DateTime(2026, 9, 17, 8, 4);
|
final now = DateTime(2026, 9, 17, 8, 4);
|
||||||
var hasNfc = true;
|
var hasNfc = true;
|
||||||
String? bypassCause;
|
|
||||||
late List<String> calls;
|
late List<String> calls;
|
||||||
|
|
||||||
setUp(() {
|
setUp(() {
|
||||||
hasNfc = true;
|
hasNfc = true;
|
||||||
bypassCause = null;
|
|
||||||
calls = <String>[];
|
calls = <String>[];
|
||||||
SharedPreferences.setMockInitialValues(<String, Object>{});
|
SharedPreferences.setMockInitialValues(<String, Object>{});
|
||||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||||
@ -26,7 +24,6 @@ void main() {
|
|||||||
const MethodChannel(AlarmScheduler.channelName),
|
const MethodChannel(AlarmScheduler.channelName),
|
||||||
(call) async {
|
(call) async {
|
||||||
calls.add(call.method);
|
calls.add(call.method);
|
||||||
if (call.method == 'takeBypassReRing') return bypassCause;
|
|
||||||
return call.method == 'hasNfc' ? hasNfc : null;
|
return call.method == 'hasNfc' ? hasNfc : null;
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@ -66,23 +63,6 @@ void main() {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
test('a bypass that rang during a live session names the re-ring', () async {
|
|
||||||
final store = SessionStore();
|
|
||||||
await store.save(
|
|
||||||
SessionRules.start(
|
|
||||||
now: now.subtract(const Duration(minutes: 2)),
|
|
||||||
tags: const SessionTagSettings(tagIds: <String>['b', 'w', 'd']),
|
|
||||||
nfcAvailable: true,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
bypassCause = 'fsi_revoked';
|
|
||||||
expect(await handoff().afterDismiss(away: false), isTrue);
|
|
||||||
final session = (await store.loadCurrent())!;
|
|
||||||
expect(session.reRings, 1);
|
|
||||||
expect(session.reRingReasons, <String>['bypass:fsi_revoked']);
|
|
||||||
expect(calls, contains('takeBypassReRing'));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a dismiss during a live session is a re-ring', () async {
|
test('a dismiss during a live session is a re-ring', () async {
|
||||||
final store = SessionStore();
|
final store = SessionStore();
|
||||||
await store.save(
|
await store.save(
|
||||||
|
|||||||
@ -1,28 +0,0 @@
|
|||||||
import 'package:flutter/foundation.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
|
||||||
import 'package:wake_alarm_sync/services/session_publisher.dart';
|
|
||||||
|
|
||||||
import '../fake_secure_storage.dart';
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
TestWidgetsFlutterBinding.ensureInitialized();
|
|
||||||
test('a failed publish reaches debugPrint, not only developer.log', () async {
|
|
||||||
SharedPreferences.setMockInitialValues({});
|
|
||||||
installFakeSecureStorage(initial: {'github_token': 'tok'});
|
|
||||||
final lines = <String>[];
|
|
||||||
final saved = debugPrint;
|
|
||||||
debugPrint = (message, {wrapWidth}) => lines.add('$message');
|
|
||||||
addTearDown(() => debugPrint = saved);
|
|
||||||
|
|
||||||
final status = await SessionPublisher(
|
|
||||||
open: () async => throw Exception('boom'),
|
|
||||||
).publish();
|
|
||||||
|
|
||||||
expect(status, 'Session kept locally (sync failed)');
|
|
||||||
expect(
|
|
||||||
lines.join('\n'),
|
|
||||||
contains('session publish failed: Exception: boom'),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@ -1,39 +0,0 @@
|
|||||||
import 'package:crdt_sync/crdt_sync.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
import 'package:http/http.dart' as http;
|
|
||||||
import 'package:http/testing.dart';
|
|
||||||
import 'package:wake_alarm_sync/services/firebase_backend.dart';
|
|
||||||
import 'package:wake_alarm_sync/services/sync_emulator.dart';
|
|
||||||
|
|
||||||
/// A [RemoteStore] that is only ever compared by identity.
|
|
||||||
class _Github extends Fake implements RemoteStore {}
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
test(
|
|
||||||
'a build without the define syncs to prod, never the emulator',
|
|
||||||
() async {
|
|
||||||
expect(kSyncEmulatorUrl, isEmpty);
|
|
||||||
expect(syncEmulatorOn, isFalse);
|
|
||||||
expect(kProject.databaseUrl, contains('kuhy-syncs'));
|
|
||||||
final github = _Github();
|
|
||||||
// No Firebase session in tests: prod's rollback path, GitHub alone.
|
|
||||||
expect(await syncBackend(github), same(github));
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
test('the emulator client signs as owner against the given origin', () async {
|
|
||||||
final seen = <Uri>[];
|
|
||||||
final client = emulatorClient(
|
|
||||||
url: 'http://10.0.2.2:9000',
|
|
||||||
httpClient: MockClient((request) async {
|
|
||||||
seen.add(request.url);
|
|
||||||
return http.Response('null', 200);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
await client.listDirectory('wake-alarm-sync/devices-e2e');
|
|
||||||
expect(seen.single.origin, 'http://10.0.2.2:9000');
|
|
||||||
expect(seen.single.queryParameters['auth'], 'owner');
|
|
||||||
expect(await EmulatorTokenProvider().hasSession(), isTrue);
|
|
||||||
expect(emulatorAccount.email, 'emulator');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@ -1,70 +0,0 @@
|
|||||||
import 'package:flutter/services.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
import 'package:material_ui/material_ui.dart';
|
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
|
||||||
import 'package:wake_alarm_sync/screens/session_screen.dart';
|
|
||||||
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
|
||||||
import 'package:wake_alarm_sync/services/session_store.dart';
|
|
||||||
import 'package:wake_alarm_sync/services/session_tag_settings.dart';
|
|
||||||
|
|
||||||
/// A bypass during a live session restarts the ring natively; the session
|
|
||||||
/// screen finds it sounding and must name the re-ring for the bypass, not
|
|
||||||
/// for the leg's deadline (C7's emulator run recorded `deadline:bathroomIn`).
|
|
||||||
void main() {
|
|
||||||
TestWidgetsFlutterBinding.ensureInitialized();
|
|
||||||
|
|
||||||
final now = DateTime(2026, 9, 17, 8, 4);
|
|
||||||
String? bypassCause;
|
|
||||||
late List<String> calls;
|
|
||||||
|
|
||||||
setUp(() async {
|
|
||||||
calls = <String>[];
|
|
||||||
bypassCause = null;
|
|
||||||
SharedPreferences.setMockInitialValues(<String, Object>{});
|
|
||||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
|
||||||
.setMockMethodCallHandler(
|
|
||||||
const MethodChannel(AlarmScheduler.channelName),
|
|
||||||
(call) async {
|
|
||||||
calls.add(call.method);
|
|
||||||
if (call.method == 'hasNfc') return true;
|
|
||||||
if (call.method == 'isRinging') return true;
|
|
||||||
if (call.method == 'peekBypassReRing') return bypassCause;
|
|
||||||
return null;
|
|
||||||
},
|
|
||||||
);
|
|
||||||
await SessionTagSettings.replaceAll(<String>['bath', 'ward', 'desk'], '');
|
|
||||||
});
|
|
||||||
|
|
||||||
Future<String?> ringReasonAfterOneTick(WidgetTester tester) async {
|
|
||||||
await tester.pumpWidget(
|
|
||||||
MaterialApp(
|
|
||||||
routes: <String, WidgetBuilder>{
|
|
||||||
'/': (_) =>
|
|
||||||
SessionScreen(clock: () => now, publish: () async => 'pushed'),
|
|
||||||
'/ring': (_) => const Scaffold(body: Text('RING')),
|
|
||||||
},
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(kSessionTick);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
expect(find.text('RING'), findsOneWidget);
|
|
||||||
return (await SessionStore().loadCurrent())!.pendingReRingReason;
|
|
||||||
}
|
|
||||||
|
|
||||||
testWidgets('a ring a bypass started is named for the bypass', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
bypassCause = 'suspended';
|
|
||||||
expect(await ringReasonAfterOneTick(tester), 'bypass:suspended');
|
|
||||||
// Only the dismiss takes the stamp: two screens can tick on one ring
|
|
||||||
// (emulator 2026-11-23), and the second must not see it gone.
|
|
||||||
expect(calls, contains('peekBypassReRing'));
|
|
||||||
expect(calls, isNot(contains('takeBypassReRing')));
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('a ring nothing stamped is the deadline', (tester) async {
|
|
||||||
expect(await ringReasonAfterOneTick(tester), 'deadline:bathroomIn');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@ -1,9 +1,7 @@
|
|||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
import 'package:kuhy_credit/kuhy_credit.dart';
|
|
||||||
import 'package:material_ui/material_ui.dart';
|
import 'package:material_ui/material_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/settings_screen.dart'
|
import 'package:wake_alarm_sync/screens/settings_screen.dart';
|
||||||
show SettingsScreen;
|
|
||||||
import 'package:wake_alarm_sync/ui/theme.dart';
|
import 'package:wake_alarm_sync/ui/theme.dart';
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
@ -106,14 +104,4 @@ void main() {
|
|||||||
expect(find.byIcon(Icons.error_outline), findsOneWidget);
|
expect(find.byIcon(Icons.error_outline), findsOneWidget);
|
||||||
expect(find.byIcon(Icons.check_circle), findsNothing);
|
expect(find.byIcon(Icons.check_circle), findsNothing);
|
||||||
});
|
});
|
||||||
|
|
||||||
testWidgets('shows exactly one KuhyCredit at the bottom', (tester) async {
|
|
||||||
await tester.pumpWidget(
|
|
||||||
MaterialApp(theme: buildAppTheme(), home: const SettingsScreen()),
|
|
||||||
);
|
|
||||||
|
|
||||||
final creditFinder = find.byType(KuhyCredit);
|
|
||||||
await tester.scrollUntilVisible(creditFinder, 500);
|
|
||||||
expect(creditFinder, findsOneWidget);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -51,14 +51,7 @@ void _collectSubtree(Element element, Set<Element> out) {
|
|||||||
void expectNoWords(WidgetTester tester, String screen) {
|
void expectNoWords(WidgetTester tester, String screen) {
|
||||||
final words = wordsOnScreen(tester);
|
final words = wordsOnScreen(tester);
|
||||||
expect(words, isEmpty, reason: 'words on $screen: $words');
|
expect(words, isEmpty, reason: 'words on $screen: $words');
|
||||||
final tooltips = tester.widgetList<Tooltip>(find.byType(Tooltip));
|
expect(find.byType(Tooltip), findsNothing, reason: 'tooltip on $screen');
|
||||||
for (final tooltip in tooltips) {
|
|
||||||
expect(
|
|
||||||
tooltip.message,
|
|
||||||
matches(RegExp(r'^[^\s.!?,;:]{1,20}$')),
|
|
||||||
reason: 'tooltip on $screen: ${tooltip.message}',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pixel 6a portrait: 1080x2400 physical at 2.625.
|
/// Pixel 6a portrait: 1080x2400 physical at 2.625.
|
||||||
|
|||||||
@ -1,32 +0,0 @@
|
|||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
import 'package:material_ui/material_ui.dart';
|
|
||||||
import 'package:wake_alarm_sync/screens/free_days_screen.dart';
|
|
||||||
import 'package:wake_alarm_sync/screens/settings_screen.dart'
|
|
||||||
show SettingsScreen;
|
|
||||||
import 'package:wake_alarm_sync/services/free_day_sync.dart';
|
|
||||||
import 'package:wake_alarm_sync/ui/theme.dart';
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
testWidgets('settings export/import have one-word tooltips', (tester) async {
|
|
||||||
await tester.pumpWidget(
|
|
||||||
MaterialApp(theme: buildAppTheme(), home: const SettingsScreen()),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(find.byTooltip('Export'), findsOneWidget);
|
|
||||||
expect(find.byTooltip('Import'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('free days sync has one-word tooltip', (tester) async {
|
|
||||||
await tester.pumpWidget(
|
|
||||||
MaterialApp(
|
|
||||||
theme: buildAppTheme(),
|
|
||||||
home: FreeDaysScreen(
|
|
||||||
openPool: () async => throw Exception('test'),
|
|
||||||
syncer: FreeDaySync(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(find.byTooltip('Sync'), findsOneWidget);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@ -3,7 +3,6 @@ library;
|
|||||||
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
import 'package:material_ui/material_ui.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:wake_alarm_sync/services/alarm_publisher.dart';
|
|
||||||
import 'package:wake_alarm_sync/ui/cues.dart';
|
import 'package:wake_alarm_sync/ui/cues.dart';
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
@ -61,24 +60,6 @@ void main() {
|
|||||||
expect(cueKindOf('Open Settings to connect'), equals(CueKind.warning));
|
expect(cueKindOf('Open Settings to connect'), equals(CueKind.warning));
|
||||||
});
|
});
|
||||||
|
|
||||||
test('every offline-first publish line keeps its own cue', () {
|
|
||||||
// Each line is built by AlarmPublisher, so a reworded prefix that
|
|
||||||
// flips a pending sync to "ok" (or a dead network to "error") fails.
|
|
||||||
expect(
|
|
||||||
cueKindOf('${armedFor(8, 0)}Connect a sync backend in Settings first.'),
|
|
||||||
equals(CueKind.warning),
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
cueKindOf('${armedFor(8, 0)}Saved locally — will sync to PC. Error: x'),
|
|
||||||
equals(CueKind.warning),
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
cueKindOf('${armedFor(8, 0)}Sync store unavailable — reopen the app.'),
|
|
||||||
equals(CueKind.error),
|
|
||||||
);
|
|
||||||
expect(cueKindOf(syncedStatus(8, 0, inClock: false)), equals(CueKind.ok));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('default info', () {
|
test('default info', () {
|
||||||
expect(cueKindOf('hello'), equals(CueKind.info));
|
expect(cueKindOf('hello'), equals(CueKind.info));
|
||||||
expect(cueKindOf('Syncing now'), equals(CueKind.info));
|
expect(cueKindOf('Syncing now'), equals(CueKind.info));
|
||||||
|
|||||||
@ -1,46 +0,0 @@
|
|||||||
/// Tests for the motion tokens and the app route.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
import 'package:material_ui/material_ui.dart';
|
|
||||||
import 'package:wake_alarm_sync/ui/motion_route.dart';
|
|
||||||
import 'package:wake_alarm_sync/ui/theme.dart';
|
|
||||||
|
|
||||||
Future<Duration> _routeDuration(WidgetTester t, {required bool off}) async {
|
|
||||||
late Duration d;
|
|
||||||
await t.pumpWidget(
|
|
||||||
MediaQuery(
|
|
||||||
data: MediaQueryData(disableAnimations: off),
|
|
||||||
child: Builder(
|
|
||||||
builder: (context) {
|
|
||||||
d = appRoute<void>(
|
|
||||||
context,
|
|
||||||
(_) => const SizedBox(),
|
|
||||||
).transitionDuration;
|
|
||||||
return const SizedBox();
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return d;
|
|
||||||
}
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
test('duration tokens match DOCS-motion', () {
|
|
||||||
expect(MotionDuration.instant, Duration.zero);
|
|
||||||
expect(MotionDuration.fast, const Duration(milliseconds: 120));
|
|
||||||
expect(MotionDuration.base, const Duration(milliseconds: 200));
|
|
||||||
expect(MotionDuration.slow, const Duration(milliseconds: 320));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('curves match DOCS-motion', () {
|
|
||||||
expect(MotionCurve.decelerate, const Cubic(0, 0, 0, 1));
|
|
||||||
expect(MotionCurve.accelerate, const Cubic(0.3, 0, 1, 1));
|
|
||||||
expect(MotionCurve.standard, const Cubic(0.2, 0, 0, 1));
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('route is slow, instant under disableAnimations', (t) async {
|
|
||||||
expect(await _routeDuration(t, off: false), MotionDuration.slow);
|
|
||||||
expect(await _routeDuration(t, off: true), Duration.zero);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@ -8,16 +8,15 @@ version = "1.0.0"
|
|||||||
description = "Trigger that starts the morning routine at the phone's alarm time"
|
description = "Trigger that starts the morning routine at the phone's alarm time"
|
||||||
requires-python = ">=3.14"
|
requires-python = ">=3.14"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.2#subdirectory=gatelock",
|
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.13.0#subdirectory=gatelock",
|
||||||
# Firebase transport for the alarm read. _sync.py imports it lazily and
|
# Firebase transport for the alarm read. _sync.py imports it lazily and
|
||||||
# falls back to its stdlib GitHub path if the import fails, so a broken
|
# falls back to its stdlib GitHub path if the import fails, so a broken
|
||||||
# install degrades the read instead of killing the per-minute trigger.
|
# install degrades the read instead of killing the per-minute trigger.
|
||||||
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync",
|
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync",
|
||||||
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays",
|
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.0#subdirectory=freedays",
|
||||||
# Sick days stand the PC's enforcement down (_sick.py). Imported behind
|
# Sick days stand the PC's enforcement down (_sick.py). Imported behind
|
||||||
# a guard: missing means "not sick", never a crashed tick.
|
# a guard: missing means "not sick", never a crashed tick.
|
||||||
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays",
|
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.0#subdirectory=sickdays",
|
||||||
"kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
# Package discovery must be explicit: phone_app/ is a Flutter app, not a Python
|
# Package discovery must be explicit: phone_app/ is a Flutter app, not a Python
|
||||||
@ -169,6 +168,10 @@ addopts = [
|
|||||||
"--strict-markers",
|
"--strict-markers",
|
||||||
"--strict-config",
|
"--strict-config",
|
||||||
"-ra",
|
"-ra",
|
||||||
|
"--cov=wake_alarm",
|
||||||
|
"--cov-branch",
|
||||||
|
"--cov-report=term-missing",
|
||||||
|
"--cov-report=lcov",
|
||||||
]
|
]
|
||||||
filterwarnings = [
|
filterwarnings = [
|
||||||
"error",
|
"error",
|
||||||
@ -186,6 +189,7 @@ omit = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[tool.coverage.report]
|
[tool.coverage.report]
|
||||||
|
fail_under = 100
|
||||||
show_missing = true
|
show_missing = true
|
||||||
skip_covered = false
|
skip_covered = false
|
||||||
exclude_lines = [
|
exclude_lines = [
|
||||||
|
|||||||
@ -4,18 +4,17 @@
|
|||||||
# it is missing — but it is required here for mypy/pylint/tests.
|
# it is missing — but it is required here for mypy/pylint/tests.
|
||||||
bandit==1.9.4
|
bandit==1.9.4
|
||||||
codespell==2.4.3
|
codespell==2.4.3
|
||||||
coverage==7.17.5
|
coverage==7.17.2
|
||||||
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
|
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync
|
||||||
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
|
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.0#subdirectory=freedays
|
||||||
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.2#subdirectory=gatelock
|
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.13.0#subdirectory=gatelock
|
||||||
kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
|
|
||||||
mypy==2.4.1
|
mypy==2.4.1
|
||||||
pre-commit==4.7.0
|
pre-commit==4.7.0
|
||||||
pylint==4.1.4
|
pylint==4.1.3
|
||||||
pytest==9.2.0
|
pytest==9.2.0
|
||||||
pytest-cov==7.1.0
|
pytest-cov==7.1.0
|
||||||
pytest-randomly==5.1.0
|
pytest-randomly==5.1.0
|
||||||
pytest-sugar==1.1.1
|
pytest-sugar==1.1.1
|
||||||
pytest-xdist==3.8.0
|
pytest-xdist==3.8.0
|
||||||
ruff==0.17.6
|
ruff==0.17.4
|
||||||
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays
|
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.0#subdirectory=sickdays
|
||||||
|
|||||||
@ -11,7 +11,7 @@
|
|||||||
#
|
#
|
||||||
# Usage:
|
# Usage:
|
||||||
# scripts/check_dependency_freshness.sh <file> [<file> ...] # pre-commit
|
# scripts/check_dependency_freshness.sh <file> [<file> ...] # pre-commit
|
||||||
# scripts/check_dependency_freshness.sh --all --strict # full local sweep
|
# scripts/check_dependency_freshness.sh --all --strict # CI
|
||||||
#
|
#
|
||||||
# Exit: 0 current | 1 behind | 2 allowlist wrong | 3 undeterminable (offline)
|
# Exit: 0 current | 1 behind | 2 allowlist wrong | 3 undeterminable (offline)
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
|
|||||||
@ -1,10 +1,10 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
# Fail if `textgate scan` reports any text item not covered by DOCS-textgate-keep.md.
|
# Fail if `textgate scan` reports any text item not covered by keep.md.
|
||||||
#
|
#
|
||||||
# textgate has no path exclusion and its config is a gate control, so the
|
# textgate has no path exclusion and its config is a gate control, so the
|
||||||
# repo's deliberate exceptions live in DOCS-textgate-keep.md instead. This script reads the
|
# repo's deliberate exceptions live in keep.md instead. This script reads the
|
||||||
# "## Scan exceptions" table there (first cell: a backticked file, or a
|
# "## Scan exceptions" table there (first cell: a backticked file, or a
|
||||||
# directory ending in "/"; second cell: the backticked exact text, or * for
|
# directory ending in "/"; second cell: the backticked exact text, or * for
|
||||||
# any text) and prints every scan hit no row covers.
|
# any text) and prints every scan hit no row covers.
|
||||||
@ -20,7 +20,7 @@ set -euo pipefail
|
|||||||
|
|
||||||
REPO_ROOT="$(git rev-parse --show-toplevel)"
|
REPO_ROOT="$(git rev-parse --show-toplevel)"
|
||||||
readonly REPO_ROOT
|
readonly REPO_ROOT
|
||||||
readonly KEEP_FILE="$REPO_ROOT/DOCS-textgate-keep.md"
|
readonly KEEP_FILE="$REPO_ROOT/keep.md"
|
||||||
readonly SECTION="## Scan exceptions"
|
readonly SECTION="## Scan exceptions"
|
||||||
|
|
||||||
die() {
|
die() {
|
||||||
@ -28,7 +28,7 @@ die() {
|
|||||||
exit 2
|
exit 2
|
||||||
}
|
}
|
||||||
|
|
||||||
# Print the exception rows of DOCS-textgate-keep.md as "path<TAB>text" (empty text = any).
|
# Print the exception rows of keep.md as "path<TAB>text" (empty text = any).
|
||||||
keep_rows() {
|
keep_rows() {
|
||||||
awk -v section="$SECTION" '/^## /{on = ($0 == section)} on && /^\| `/' "$KEEP_FILE" |
|
awk -v section="$SECTION" '/^## /{on = ($0 == section)} on && /^\| `/' "$KEEP_FILE" |
|
||||||
sed -E 's/^\| `([^`]+)` \| (`([^`]*)`|\*) \|.*$/\1\t\3/'
|
sed -E 's/^\| `([^`]+)` \| (`([^`]*)`|\*) \|.*$/\1\t\3/'
|
||||||
@ -56,10 +56,10 @@ main() {
|
|||||||
|
|
||||||
if [[ -n "$unmatched" ]]; then
|
if [[ -n "$unmatched" ]]; then
|
||||||
echo "$unmatched"
|
echo "$unmatched"
|
||||||
echo "textgate keep: $(wc -l <<<"$unmatched") hit(s) not in DOCS-textgate-keep.md" >&2
|
echo "textgate keep: $(wc -l <<<"$unmatched") hit(s) not in keep.md" >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
echo "textgate keep: all $(jq length <<<"$scan") hit(s) covered by DOCS-textgate-keep.md"
|
echo "textgate keep: all $(jq length <<<"$scan") hit(s) covered by keep.md"
|
||||||
}
|
}
|
||||||
|
|
||||||
main "$@"
|
main "$@"
|
||||||
|
|||||||
@ -1,136 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
# ============================================================================
|
|
||||||
# deploy.sh -- deploy wake-alarm everywhere it runs: the PC half (an editable
|
|
||||||
# install of ~/src/wake-alarm under the system python, driven by the user
|
|
||||||
# timers) and the phone app on the Pixel (release build via phone_deploy.sh).
|
|
||||||
#
|
|
||||||
# CLAUDE.md's deploy line pulls ~/src/wake-alarm first and then runs THIS copy
|
|
||||||
# from there, so the freshly pulled script is what executes.
|
|
||||||
#
|
|
||||||
# Deliberately does NOT run install.sh: it needs interactive sudo (ring unit,
|
|
||||||
# sudoers, logind drop-in). A unit or root-file change still means a manual
|
|
||||||
# `bash install.sh`; this script fails if the timers it relies on are not
|
|
||||||
# enabled and active, so a missing install is a red deploy, not a silent one.
|
|
||||||
#
|
|
||||||
# Idempotent: pip is skipped while the live import already resolves to the
|
|
||||||
# live checkout; the phone is skipped when the installed base.apk already
|
|
||||||
# equals the APK built from the live checkout.
|
|
||||||
#
|
|
||||||
# Usage: scripts/deploy.sh [--desktop-only | --build-only | --check]
|
|
||||||
# --desktop-only PC half only, no phone step
|
|
||||||
# --build-only PC half, then build the release APK without installing it
|
|
||||||
# (board sessions, which phone_deploy refuses to install from)
|
|
||||||
# --check health checks only: no pull, no install, no build
|
|
||||||
# Exit: 0 every health check passed, 1 a step failed (named on stderr), or
|
|
||||||
# phone_deploy.sh's own exit code is reported in the failure message.
|
|
||||||
# ============================================================================
|
|
||||||
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
|
||||||
readonly REPO_DIR
|
|
||||||
readonly LIVE_REPO="${WAKE_ALARM_LIVE_REPO:-$HOME/src/wake-alarm}"
|
|
||||||
# The trigger service runs /usr/bin/python, never a venv (CLAUDE.md).
|
|
||||||
readonly SYSTEM_PYTHON="${DEPLOY_PYTHON:-/usr/bin/python3}"
|
|
||||||
readonly PHONE_DEPLOY="${PHONE_DEPLOY:-$HOME/.claude/scripts/phone_deploy.sh}"
|
|
||||||
readonly SERIAL="${ADB_SERIAL:-23181JEGR08034}"
|
|
||||||
readonly PACKAGE="com.kuhy.wake_alarm_sync"
|
|
||||||
readonly TIMERS=("wake-alarm-trigger.timer" "wake-alarm-session.timer")
|
|
||||||
readonly APK_REL="phone_app/build/app/outputs/flutter-apk/app-release.apk"
|
|
||||||
|
|
||||||
log() { printf 'deploy: %s\n' "$1" >&2; }
|
|
||||||
fail() { printf 'deploy: FAILED [%s] -- %s\n' "$1" "$2" >&2; exit 1; }
|
|
||||||
|
|
||||||
# Run from / so a checkout in the cwd can never shadow the live install.
|
|
||||||
live_python() { (cd / && "$SYSTEM_PYTHON" "$@"); }
|
|
||||||
|
|
||||||
update_checkout() {
|
|
||||||
log "pulling $LIVE_REPO"
|
|
||||||
git -C "$LIVE_REPO" pull --ff-only --quiet || fail pull "git pull --ff-only in $LIVE_REPO"
|
|
||||||
}
|
|
||||||
|
|
||||||
install_package() {
|
|
||||||
local file
|
|
||||||
file=$(live_python -c 'import wake_alarm; print(wake_alarm.__file__)' 2>/dev/null || true)
|
|
||||||
if [[ $file == "$LIVE_REPO/wake_alarm/"* ]] \
|
|
||||||
&& live_python -c 'import gatelock, crdt_sync, sickdays, freedays' 2>/dev/null; then
|
|
||||||
log "editable install already points at $LIVE_REPO"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
log "installing $LIVE_REPO into the system python (editable)"
|
|
||||||
live_python -m pip install --quiet --user --break-system-packages -e "$LIVE_REPO" \
|
|
||||||
|| fail pip "pip install -e $LIVE_REPO"
|
|
||||||
}
|
|
||||||
|
|
||||||
check_desktop() {
|
|
||||||
local file out timer
|
|
||||||
live_python -c 'import wake_alarm, gatelock, crdt_sync, sickdays, freedays' \
|
|
||||||
|| fail imports "a runtime dependency is missing from $SYSTEM_PYTHON"
|
|
||||||
file=$(live_python -c 'import wake_alarm; print(wake_alarm.__file__)')
|
|
||||||
[[ $file == "$LIVE_REPO/wake_alarm/"* ]] || fail imports "wake_alarm resolves to $file"
|
|
||||||
for timer in "${TIMERS[@]}"; do
|
|
||||||
systemctl --user is-enabled --quiet "$timer" || fail timers "$timer not enabled (run install.sh)"
|
|
||||||
systemctl --user is-active --quiet "$timer" || fail timers "$timer not active (run install.sh)"
|
|
||||||
done
|
|
||||||
out=$(live_python -m wake_alarm._trigger --dry-run 2>&1) || fail trigger "_trigger --dry-run: $out"
|
|
||||||
log "desktop OK: $out"
|
|
||||||
}
|
|
||||||
|
|
||||||
build_apk() {
|
|
||||||
local app="$1/phone_app"
|
|
||||||
log "phone: release build of $app"
|
|
||||||
(cd "$app" && flutter build apk --release) || fail phone-build "flutter build apk --release"
|
|
||||||
[[ -s "$1/$APK_REL" ]] || fail phone-build "no APK at $1/$APK_REL"
|
|
||||||
}
|
|
||||||
|
|
||||||
# sha256 of the installed base.apk; empty when the phone or app is absent.
|
|
||||||
installed_apk_sha() {
|
|
||||||
local path
|
|
||||||
path=$(adb -s "$SERIAL" shell pm path "$PACKAGE" 2>/dev/null | tr -d '\r' | sed -n 's/^package://p' | head -1 || true)
|
|
||||||
[[ -n $path ]] || return 0
|
|
||||||
adb -s "$SERIAL" shell sha256sum "$path" 2>/dev/null | awk '{print $1}' || true
|
|
||||||
}
|
|
||||||
|
|
||||||
deploy_phone() {
|
|
||||||
local want have
|
|
||||||
build_apk "$LIVE_REPO"
|
|
||||||
want=$(sha256sum "$LIVE_REPO/$APK_REL" | awk '{print $1}')
|
|
||||||
have=$(installed_apk_sha)
|
|
||||||
if [[ $have == "$want" ]]; then
|
|
||||||
log "phone already runs this APK ($PACKAGE)"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
log "phone: installing $PACKAGE"
|
|
||||||
# phone_deploy never uninstalls or clears data; its exit code names the
|
|
||||||
# failure (30 unreachable, 32 signature change, 35 install, ...).
|
|
||||||
"$PHONE_DEPLOY" "$LIVE_REPO/phone_app" --release || fail phone "phone_deploy.sh exited $?"
|
|
||||||
# phone_deploy rebuilt the APK in place: compare against what it installed.
|
|
||||||
want=$(sha256sum "$LIVE_REPO/$APK_REL" | awk '{print $1}')
|
|
||||||
have=$(installed_apk_sha)
|
|
||||||
[[ $have == "$want" ]] || fail phone "installed APK ${have:-absent} != built $want"
|
|
||||||
log "phone OK: $PACKAGE matches the built APK"
|
|
||||||
}
|
|
||||||
|
|
||||||
main() {
|
|
||||||
local mode="${1:-all}"
|
|
||||||
case "$mode" in
|
|
||||||
all | --desktop-only | --build-only) ;;
|
|
||||||
--check)
|
|
||||||
check_desktop
|
|
||||||
log "done (check only)"
|
|
||||||
return
|
|
||||||
;;
|
|
||||||
*) fail usage "unknown option $mode (use --desktop-only, --build-only or --check)" ;;
|
|
||||||
esac
|
|
||||||
update_checkout
|
|
||||||
install_package
|
|
||||||
check_desktop
|
|
||||||
case "$mode" in
|
|
||||||
--desktop-only) ;;
|
|
||||||
--build-only) build_apk "$REPO_DIR" ;;
|
|
||||||
*) deploy_phone ;;
|
|
||||||
esac
|
|
||||||
log "done"
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
@ -1,71 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
r"""Export what the emulator phone published to the Firebase RTDB emulator.
|
|
||||||
|
|
||||||
The emulator live checks (a ``bypass`` reaching "the test backend") use a
|
|
||||||
probe build that syncs to the PC's RTDB emulator instead of prod
|
|
||||||
(``phone_app/lib/services/sync_emulator.dart``). This reads it back exactly
|
|
||||||
the way the PC reads prod -- ``_sync_transport._read_published``: device
|
|
||||||
discovery plus the E2E unlock -- and writes the ``[[device_id, alarm], ...]``
|
|
||||||
list that ``python -m wake_alarm._fallback --dry-run --published`` takes.
|
|
||||||
|
|
||||||
Run it with ``HOME`` set to a scratch directory whose
|
|
||||||
``.config/crdt-sync/password`` holds the dummy test passphrase the AVD was
|
|
||||||
given, so the real passphrase is never read, and with
|
|
||||||
``PYTHONUSERBASE=/home/kuhy/.local`` so ``crdt_sync`` still imports::
|
|
||||||
|
|
||||||
HOME=$SCRATCH PYTHONUSERBASE=$HOME/.local \\
|
|
||||||
/usr/bin/python3 scripts/emu_published.py http://127.0.0.1:9000 out.json
|
|
||||||
|
|
||||||
``crdt_sync`` is imported unguarded on purpose: the transport degrades a
|
|
||||||
missing module to "nothing published", which here would read as a failed
|
|
||||||
check instead of a broken setup.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
from pathlib import Path
|
|
||||||
import sys
|
|
||||||
|
|
||||||
from crdt_sync import (
|
|
||||||
FirebaseSyncClient,
|
|
||||||
FirebaseTokenProvider,
|
|
||||||
MemoryCredentialStore,
|
|
||||||
)
|
|
||||||
|
|
||||||
from wake_alarm._sync_transport import _read_published
|
|
||||||
|
|
||||||
|
|
||||||
class _OwnerToken(FirebaseTokenProvider):
|
|
||||||
"""The emulator's admin token; the RTDB emulator accepts ``auth=owner``.
|
|
||||||
|
|
||||||
Never signs in: no API key, an empty store, and ``id_token`` overridden.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self) -> None:
|
|
||||||
"""A provider with nothing to refresh."""
|
|
||||||
super().__init__("", MemoryCredentialStore())
|
|
||||||
|
|
||||||
def id_token(self) -> str:
|
|
||||||
"""Every request's ``auth`` parameter."""
|
|
||||||
return "owner"
|
|
||||||
|
|
||||||
|
|
||||||
def main(argv: list[str] | None = None) -> int:
|
|
||||||
"""Write the emulator's published logs to the output file; 1 when empty."""
|
|
||||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
||||||
parser.add_argument("url", help="the RTDB emulator's origin")
|
|
||||||
parser.add_argument("out", type=Path, help="where to write the JSON list")
|
|
||||||
args = parser.parse_args(argv)
|
|
||||||
client = FirebaseSyncClient(args.url, _OwnerToken())
|
|
||||||
published = _read_published(client)
|
|
||||||
pairs = [[device, json.loads(raw)] for device, raw in published]
|
|
||||||
args.out.write_text(json.dumps(pairs, indent=1), encoding="utf-8")
|
|
||||||
devices = " ".join(device for device, _ in pairs)
|
|
||||||
sys.stdout.write(f"{len(pairs)} device(s): {devices}\n")
|
|
||||||
return 0 if pairs else 1
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main())
|
|
||||||
@ -9,27 +9,7 @@
|
|||||||
# speakers' card has, plays the rising WAV once, then loops the full-volume
|
# speakers' card has, plays the rising WAV once, then loops the full-volume
|
||||||
# one until systemd stops the unit (RuntimeMaxSec is the backstop).
|
# one until systemd stops the unit (RuntimeMaxSec is the backstop).
|
||||||
#
|
#
|
||||||
# When the card is held (almost always the user's PipeWire), the FIRST busy
|
# Usage: ring_alsa.sh <rise.wav> <loop.wav>
|
||||||
# open -- no retries -- hands the ring to PipeWire as the user
|
|
||||||
# (wake_alarm._ring_main, via runuser). Killing the holder first would kill
|
|
||||||
# the PipeWire that fallback needs. Only if that fallback also fails: one
|
|
||||||
# `fuser -k -TERM` on the card's playback nodes, one more ALSA try, then exit
|
|
||||||
# non-zero. Needs WAKE_ALARM_USER (set by the unit; install.sh fills it in)
|
|
||||||
# and psmisc's fuser.
|
|
||||||
#
|
|
||||||
# The monitors ring too (2026-11-22): kuhy switches the speakers off at the
|
|
||||||
# knob for the night, so the 07:51 ring of 11-22 played 30 min into silence.
|
|
||||||
# Every HDMI/DP output whose ELD names a connected monitor gets its own
|
|
||||||
# aplay loop, IEC958 unmuted; each output logs one `ring_sink` line.
|
|
||||||
#
|
|
||||||
# --probe proves the monitors without a sound: two seconds of digital
|
|
||||||
# silence to each, IEC958 muted, one `ring_probe` line per sink, exit 1 when
|
|
||||||
# any fails or none is connected (wake-alarm-ring-probe.service).
|
|
||||||
#
|
|
||||||
# --monitors <rise> <loop> rings only the monitors, until SIGTERM: the
|
|
||||||
# PipeWire path runs it as the user beside pw-play (wake_alarm/_ring_monitors).
|
|
||||||
#
|
|
||||||
# Usage: ring_alsa.sh <rise.wav> <loop.wav> | --monitors <rise> <loop> | --probe
|
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
|
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@ -41,21 +21,11 @@ readonly DEVICE="plughw:CARD=${CARD},DEV=0"
|
|||||||
# Playback controls that may gate the speakers; only those present are set.
|
# Playback controls that may gate the speakers; only those present are set.
|
||||||
# Front is the rear line-out jack on this board.
|
# Front is the rear line-out jack on this board.
|
||||||
readonly CONTROLS=(Master PCM Speaker Headphone Front)
|
readonly CONTROLS=(Master PCM Speaker Headphone Front)
|
||||||
# The user whose PipeWire owns the card, and the interpreter that has the
|
|
||||||
# wake_alarm package (system python, same as the user timers).
|
|
||||||
readonly RING_USER="${WAKE_ALARM_USER:-}"
|
|
||||||
readonly PY="${WAKE_ALARM_PYTHON:-/usr/bin/python3}"
|
|
||||||
# A failed aplay (device briefly held elsewhere) must not spin the CPU.
|
# A failed aplay (device briefly held elsewhere) must not spin the CPU.
|
||||||
readonly RETRY_SECONDS=1
|
readonly RETRY_SECONDS=1
|
||||||
# How long a monitor's aplay must survive to count as opened.
|
|
||||||
readonly OPEN_CHECK_SECONDS=1
|
|
||||||
# The monitors as card:dev:name:hdmi-index lines; unset = read `aplay -l`.
|
|
||||||
# Set (even empty) only by the vmbox gate.
|
|
||||||
MONITORS_OVERRIDE="${WAKE_ALARM_MONITORS-__unset__}"
|
|
||||||
readonly MONITORS_OVERRIDE
|
|
||||||
|
|
||||||
usage() {
|
usage() {
|
||||||
echo "Usage: $(basename "$0") <rise.wav> <loop.wav> | --monitors <rise> <loop> | --probe" >&2
|
echo "Usage: $(basename "$0") <rise.wav> <loop.wav>" >&2
|
||||||
exit 2
|
exit 2
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -71,172 +41,21 @@ unmute_all() {
|
|||||||
done
|
done
|
||||||
}
|
}
|
||||||
|
|
||||||
# aplay's stderr says why it failed; only "busy" triggers the fallback.
|
|
||||||
play() {
|
play() {
|
||||||
local err
|
aplay -q -D "$DEVICE" "$1" || sleep "$RETRY_SECONDS"
|
||||||
err="$(mktemp)"
|
|
||||||
if aplay -q -D "$DEVICE" "$1" 2>"$err"; then
|
|
||||||
rm -f "$err"
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
if grep -qi 'busy' "$err"; then
|
|
||||||
rm -f "$err"
|
|
||||||
return 3
|
|
||||||
fi
|
|
||||||
cat "$err" >&2
|
|
||||||
rm -f "$err"
|
|
||||||
sleep "$RETRY_SECONDS"
|
|
||||||
}
|
|
||||||
|
|
||||||
# One line per connected monitor: card:dev:name:hdmi-index. `aplay -l` names
|
|
||||||
# an HDMI/DP device after its ELD ("HDMI 0 [G27Q]"); an empty port keeps
|
|
||||||
# "HDMI n [HDMI n]".
|
|
||||||
monitor_sinks() {
|
|
||||||
if [[ "$MONITORS_OVERRIDE" != "__unset__" ]]; then
|
|
||||||
tr ' ' '\n' <<<"$MONITORS_OVERRIDE" | grep -v '^$' || true
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
aplay -l 2>/dev/null |
|
|
||||||
sed -nE 's/^card [0-9]+: ([^ ]+) \[[^]]*\], device ([0-9]+): HDMI ([0-9]+) \[(.+)\]$/\1:\2:\4:\3/p' |
|
|
||||||
grep -vE ':HDMI [0-9]+:[0-9]+$' || true
|
|
||||||
}
|
|
||||||
|
|
||||||
# One sink's ring: the rise, a `ring_sink` line saying whether it opened,
|
|
||||||
# then the loop until SIGTERM. The rise lasts a minute, so "opened" means
|
|
||||||
# aplay is still playing after OPEN_CHECK_SECONDS. A sink that cannot open
|
|
||||||
# logs and gives up, so one dead monitor never stops the others.
|
|
||||||
ring_sink() {
|
|
||||||
local card="$1" dev="$2" name="$3" rise="$4" loop="$5" device err pid rc=0
|
|
||||||
device="plughw:CARD=${card},DEV=${dev}"
|
|
||||||
err="$(mktemp)"
|
|
||||||
aplay -q -D "$device" "$rise" 2>"$err" &
|
|
||||||
pid=$!
|
|
||||||
sleep "$OPEN_CHECK_SECONDS"
|
|
||||||
if ! kill -0 "$pid" 2>/dev/null; then
|
|
||||||
wait "$pid" || rc=$?
|
|
||||||
fi
|
|
||||||
if [[ $rc -ne 0 ]]; then
|
|
||||||
echo "ring_sink sink=$name device=$card,$dev result=error $(tr '\n' ' ' <"$err")"
|
|
||||||
rm -f "$err"
|
|
||||||
return 1
|
|
||||||
fi
|
|
||||||
echo "ring_sink sink=$name device=$card,$dev result=ok"
|
|
||||||
rm -f "$err"
|
|
||||||
wait "$pid" 2>/dev/null || true
|
|
||||||
while true; do
|
|
||||||
aplay -q -D "$device" "$loop" 2>/dev/null || sleep "$RETRY_SECONDS"
|
|
||||||
done
|
|
||||||
}
|
|
||||||
|
|
||||||
# Every monitor in the background, IEC958 unmuted first.
|
|
||||||
start_monitors() {
|
|
||||||
local rise="$1" loop="$2" card dev name index
|
|
||||||
while IFS=: read -r card dev name index; do
|
|
||||||
[[ -n "$card" ]] || continue
|
|
||||||
amixer -q -c "$card" sset "IEC958,${index}" unmute >/dev/null 2>&1 || true
|
|
||||||
ring_sink "$card" "$dev" "$name" "$rise" "$loop" &
|
|
||||||
done < <(monitor_sinks)
|
|
||||||
}
|
|
||||||
|
|
||||||
# Silence into every monitor; 0 only when each opened and took >= 1.5 s.
|
|
||||||
# IEC958 is muted for the check and put back the way it was found.
|
|
||||||
probe() {
|
|
||||||
local card dev name index start ms rc err was failed=0 found=0
|
|
||||||
while IFS=: read -r card dev name index; do
|
|
||||||
[[ -n "$card" ]] || continue
|
|
||||||
found=1
|
|
||||||
was=unmute
|
|
||||||
if amixer -c "$card" sget "IEC958,${index}" 2>/dev/null | grep -q '\[off\]'; then
|
|
||||||
was=mute
|
|
||||||
fi
|
|
||||||
amixer -q -c "$card" sset "IEC958,${index}" mute >/dev/null 2>&1 || true
|
|
||||||
start="$(date +%s%N)"
|
|
||||||
rc=0
|
|
||||||
err="$(aplay -q -D "plughw:CARD=${card},DEV=${dev}" -t raw -f S16_LE -r 48000 \
|
|
||||||
-c 2 -d 2 /dev/zero 2>&1)" || rc=$?
|
|
||||||
ms=$((($(date +%s%N) - start) / 1000000))
|
|
||||||
amixer -q -c "$card" sset "IEC958,${index}" "$was" >/dev/null 2>&1 || true
|
|
||||||
if [[ $rc -eq 0 && $ms -ge 1500 ]]; then
|
|
||||||
echo "ring_probe sink=$name device=$card,$dev result=ok ms=$ms"
|
|
||||||
else
|
|
||||||
echo "ring_probe sink=$name device=$card,$dev result=error rc=$rc ms=$ms ${err//$'\n'/ }"
|
|
||||||
failed=1
|
|
||||||
fi
|
|
||||||
done < <(monitor_sinks)
|
|
||||||
if [[ $found -eq 0 ]]; then
|
|
||||||
echo "ring_probe result=error no connected monitor"
|
|
||||||
return 1
|
|
||||||
fi
|
|
||||||
return "$failed"
|
|
||||||
}
|
|
||||||
|
|
||||||
# Ring through the user's PipeWire until systemd's SIGTERM; non-zero if it
|
|
||||||
# cannot play (the fallback itself reports ring_backend FAILED).
|
|
||||||
user_fallback() {
|
|
||||||
[[ -n "$RING_USER" ]] || return 1
|
|
||||||
local uid home
|
|
||||||
uid="$(id -u "$RING_USER")"
|
|
||||||
home="$(getent passwd "$RING_USER" | cut -d: -f6)"
|
|
||||||
echo "fallback-started: card busy, ringing through PipeWire as $RING_USER"
|
|
||||||
runuser -u "$RING_USER" -- env HOME="$home" PATH="$PATH" \
|
|
||||||
XDG_RUNTIME_DIR="/run/user/$uid" \
|
|
||||||
"$PY" -m wake_alarm._ring_main "$1" "$2"
|
|
||||||
}
|
|
||||||
|
|
||||||
# Last resort: free the card from whatever holds it, once.
|
|
||||||
kill_holder() {
|
|
||||||
local node
|
|
||||||
node="$(readlink "/proc/asound/$CARD")" || return 0
|
|
||||||
echo "kill-holder: fuser -k -TERM on ${node}"
|
|
||||||
# shellcheck disable=SC2046 # one argument per playback node, by design
|
|
||||||
fuser -k -TERM $(compgen -G "/dev/snd/pcmC${node#card}D*p") 2>&1 || true
|
|
||||||
sleep "$RETRY_SECONDS"
|
|
||||||
}
|
|
||||||
|
|
||||||
# The card was busy on its first open: PipeWire first, then kill, then fail.
|
|
||||||
# Returns only when the holder was killed and ALSA works again.
|
|
||||||
handle_busy() {
|
|
||||||
local rise="$1" loop="$2"
|
|
||||||
if user_fallback "$rise" "$loop"; then
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
echo "fallback-failed: killing the holder, one more ALSA try" >&2
|
|
||||||
kill_holder
|
|
||||||
aplay -q -D "$DEVICE" "$rise" || {
|
|
||||||
echo "Error: card $CARD still unusable" >&2
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
if [[ "${1:-}" == "--probe" ]]; then
|
|
||||||
probe
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
if [[ "${1:-}" == "--monitors" ]]; then
|
|
||||||
[[ $# -eq 3 ]] || usage
|
|
||||||
# SIGTERM from the PipeWire path: end every loop, then exit.
|
|
||||||
trap 'kill $(jobs -p) 2>/dev/null || true; exit 0' TERM INT
|
|
||||||
start_monitors "$2" "$3"
|
|
||||||
wait
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
[[ $# -eq 2 ]] || usage
|
[[ $# -eq 2 ]] || usage
|
||||||
local rise="$1" loop="$2"
|
local rise="$1" loop="$2"
|
||||||
[[ -r "$rise" && -r "$loop" ]] || {
|
[[ -r "$rise" && -r "$loop" ]] || {
|
||||||
echo "Error: cannot read $rise / $loop" >&2
|
echo "Error: cannot read $rise / $loop" >&2
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
# The monitor loops die with this script, whatever ends it.
|
|
||||||
trap 'kill $(jobs -p) 2>/dev/null || true' EXIT
|
|
||||||
start_monitors "$rise" "$loop"
|
|
||||||
unmute_all
|
unmute_all
|
||||||
local rc=0
|
play "$rise"
|
||||||
play "$rise" || rc=$?
|
|
||||||
[[ $rc -ne 3 ]] || handle_busy "$rise" "$loop"
|
|
||||||
[[ $rc -ne 0 ]] || echo "ring_sink sink=speakers device=$CARD,0 result=ok"
|
|
||||||
while true; do
|
while true; do
|
||||||
play "$loop" || sleep "$RETRY_SECONDS"
|
play "$loop"
|
||||||
done
|
done
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -8,9 +8,6 @@ Documentation=https://github.com/kuhyx/wake-alarm
|
|||||||
# graphical session owns the sound: the night lockdown masks lightdm, and
|
# graphical session owns the sound: the night lockdown masks lightdm, and
|
||||||
# the user is not in `audio`, so only root can reach the card.
|
# the user is not in `audio`, so only root can reach the card.
|
||||||
Type=simple
|
Type=simple
|
||||||
# install.sh replaces @USER@: whose PipeWire the script falls back to when
|
|
||||||
# the card is busy.
|
|
||||||
Environment=WAKE_ALARM_USER=@USER@
|
|
||||||
ExecStart=/usr/local/lib/wake-alarm/ring_alsa.sh /usr/local/share/wake-alarm/ring.wav /usr/local/share/wake-alarm/ring_loop.wav
|
ExecStart=/usr/local/lib/wake-alarm/ring_alsa.sh /usr/local/share/wake-alarm/ring.wav /usr/local/share/wake-alarm/ring_loop.wav
|
||||||
# Backstop for a fallback tick that died without stopping this unit: never
|
# Backstop for a fallback tick that died without stopping this unit: never
|
||||||
# ring longer than the 30-min cap plus a minute.
|
# ring longer than the 30-min cap plus a minute.
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user