Compare commits

..

No commits in common. "main" and "v1.0.0-build.325" have entirely different histories.

66 changed files with 286 additions and 1727 deletions

View File

@ -16,12 +16,18 @@ jobs:
fail-fast: false
matrix:
include:
- group: mypy
hooks: mypy
skip: ""
- group: pylint
hooks: pylint
skip: ""
# 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
# fail-open.
- group: rest
hooks: ""
skip: "free-days-interop,dependency-freshness"
skip: mypy,pylint,free-days-interop,dependency-freshness
name: pre-commit (${{ matrix.group }})
steps:
- uses: actions/checkout@v4

View File

@ -24,6 +24,8 @@ repos:
- id: check-merge-conflict
- id: detect-private-key
- id: debug-statements
- id: name-tests-test
args: [--pytest-test-first]
- id: check-ast
- id: mixed-line-ending
args: [--fix=lf]
@ -57,9 +59,77 @@ repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.15.2
hooks:
- id: ruff
args: [--fix, --unsafe-fixes, --exit-non-zero-on-fix, --show-fixes]
types_or: [python, pyi]
- id: ruff-format
types_or: [python, pyi]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.13.0
hooks:
- id: mypy
args:
- --ignore-missing-imports
- --no-error-summary
- --disable-error-code=no-untyped-def
- --disable-error-code=no-untyped-call
- --disable-error-code=var-annotated
- --disable-error-code=no-any-unimported
- --disable-error-code=type-arg
- --disable-error-code=no-any-return
- --disable-error-code=misc
- --disable-error-code=unused-ignore
- --disable-error-code=unreachable
- --disable-error-code=assignment
- --disable-error-code=no-redef
- --disable-error-code=attr-defined
- --disable-error-code=arg-type
- --disable-error-code=union-attr
- --disable-error-code=call-overload
- --disable-error-code=return-value
- --disable-error-code=redundant-cast
- --disable-error-code=empty-body
- --disable-error-code=list-item
- repo: https://github.com/pylint-dev/pylint
rev: v3.3.2
hooks:
- id: pylint
# dill (pylint --jobs) crashes on 3.15 (co_lnotab gone); 3.14 until it catches up.
language_version: python3.14
args:
- --rcfile=pyproject.toml
- --fail-under=10
- --jobs=4
additional_dependencies:
- pytest
# Kept in step with pyproject.toml: pip refuses two different
# direct URLs for one distribution, so any pin that drifts from
# the manifest becomes an unresolvable hook environment rather
# than merely an old one.
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
- kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays
# Test suites intentionally use patterns (protected-access, magic-value
# comparisons) that don't belong in the source-code 10/10 gate.
exclude: ^(\.venv/)|(^|/)(tests/|conftest\.py)
- repo: https://github.com/PyCQA/bandit
rev: 1.7.10
hooks:
- id: bandit
args:
- -c
- pyproject.toml
- --severity-level=high
- --confidence-level=medium
- --skip=B113
additional_dependencies: ["bandit[toml]"]
exclude: ^(tests/|.*test.*\.py$)
- repo: local
hooks:
- id: ci-mirror
@ -71,6 +141,13 @@ repos:
require_serial: true
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
hooks:
# Fails a commit that still points crdt_sync at a local path. Local
@ -90,6 +167,18 @@ repos:
language: system
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/.*)$
- 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
# rule that a TODO carries "REMOVE ME AFTER FINISH" and nothing else may.

View File

@ -217,9 +217,9 @@ self-wake's `rtcwake` and the root ring unit's `systemctl` lines live there.
- run: n/a: no single entry point; systemd timers (`install.sh`) drive it, inspect with `python -m wake_alarm._sync --show`, `python -m wake_alarm._session --show`, `python -m wake_alarm._trigger --dry-run`
- test: `python -m pytest -q wake_alarm/tests/ && cd phone_app && flutter test --reporter=compact`
- test-changed: `scripts/test_changed.sh`
- lint: n/a: dropped (kuhy, 2026-11-27)
- coverage: n/a: dropped (kuhy, 2026-11-27)
- coverage-gaps: n/a: dropped (kuhy, 2026-11-27)
- lint: `pre-commit run ruff --all-files && cd phone_app && flutter analyze --fatal-infos --fatal-warnings`
- coverage: `python -m pytest -q wake_alarm/tests/ --cov=wake_alarm --cov-branch --cov-report=xml --cov-fail-under=100`
- coverage-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

View File

@ -50,7 +50,6 @@ live. Causes (`bypass` phone event, `data.cause`):
| `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
@ -63,20 +62,9 @@ a minute is recorded once (both activities run the launch check).
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.
by one when it does (`SessionHandoff.afterDismiss`).
- **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
@ -85,100 +73,6 @@ a minute is recorded once (both activities run the launch check).
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
@ -230,11 +124,7 @@ 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`.
`ring_probe_done`. Read it with `journalctl -u wake-alarm-ring-probe`.
vmbox gate: `ring-alsa-monitor-sinks`, `ring-alsa-monitor-probe`
(`scripts/vmbox/guest_cases_monitors.sh`).

View File

@ -61,9 +61,7 @@ the first leg by itself — there is nothing to walk to.
of recreating it.
- **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
session for today and resumes it with `reRings + 1`. `re_ring_reasons`
says why: `deadline:<leg>`, or `bypass:<cause>` when a bypass restarted
the ring (`DOCS-bypass.md`).
session for today and resumes it with `reRings + 1`.
- **A silent buzz 3 min before each deadline** (`SessionWarn.kt`, request
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
@ -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.
The phone remains the only test of the AlarmManager deadline with the
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`.

View File

@ -54,13 +54,10 @@ 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.
- 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`.
- 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)
@ -160,8 +157,7 @@ Phone (`phone_events.kind`): `alarm_fired` (data: `reason` =
`exact`|`boot`|`watchdog`, `date` judged, `verdict`, incl. `free_day`|`sick_day`), `bypass` (data: `cause`, `date`, `session`; `DOCS-bypass.md`),
`bypass_ignored`, `notifications` (data: `enabled`, `trigger` =
`evening`|`app_block`|`channel_block`; `DOCS-bypass.md`), `unsuspended`, `lockdown_sent` (data:
`until`, `streak`, `resend`: true when a day already penalised sent its
stored lockdown again), `lift_sent`, `escape_used`, `boot`.
`until`, `streak`), `lift_sent`, `escape_used`, `boot`.
`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

View File

@ -84,30 +84,3 @@ dependencies {
// that needs a Context stays out of them.
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"),
)
}
}

View File

@ -4,5 +4,4 @@
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<application android:networkSecurityConfig="@xml/network_security_config" />
</manifest>

View File

@ -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>

View File

@ -145,8 +145,6 @@ object AlarmChannel {
// a deadline that rang while it sat in the background puts the
// dismiss sequence in front the moment it is looked at.
"isRinging" -> result.success(AlarmService.running)
"takeBypassReRing" -> result.success(BypassReRing.take(context))
"peekBypassReRing" -> result.success(BypassReRing.peek(context))
"beginStepCount" -> {
StepCounter.markRingStart(context)
result.success(null)

View File

@ -28,21 +28,6 @@ object BypassRules {
/** 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
}
}
/**
@ -90,9 +75,6 @@ object Bypass {
)
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

View File

@ -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)
}

View File

@ -67,8 +67,6 @@ data class StickRun(
val state: StickState,
val checkedThrough: LocalDate,
val signalUntil: LocalDate?,
/** [signalUntil] repeats a lockdown already bought, not a new miss's. */
val resend: Boolean = false,
)
/**
@ -95,9 +93,6 @@ object StickCheck {
/**
* 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
* [BACKLOG_DAYS] back -- in order, so the streak builds exactly as if
* each day had been checked on time. A first run (no checkedThrough)
@ -109,7 +104,6 @@ object StickCheck {
val verdicts = mutableListOf<DayVerdict>()
var state = inputs.state
var signal: LocalDate? = null
var resend = false
val checked = inputs.checkedThrough
var day = if (checked == null) {
today
@ -123,22 +117,12 @@ object StickCheck {
verdicts += DayVerdict(day, verdict)
if (verdict == StickVerdict.MISS) {
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
day = day.plusDays(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. */

View File

@ -15,8 +15,8 @@ import java.time.LocalDateTime
* 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
* 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
* for the streak (it only re-sends the same lockdown), which matters because Android replays BOOT_COMPLETED to a force-stopped
* [StickVerdict.ALREADY_PENALISED] makes a second miss on one day a no-op,
* which matters because Android replays BOOT_COMPLETED to a force-stopped
* app on its next launch.
*/
object StickRunner {
@ -50,18 +50,13 @@ object StickRunner {
if (run.state != before) StickStore.save(context, run.state)
StickStore.setCheckedThrough(context, run.checkedThrough)
// A missed day whose lockdown already ended (caught up days later)
// still counts toward the streak, but nothing is sent for it. A day
// already penalised sends its lockdown again ([StickRun.resend]).
// still counts toward the streak, but nothing is sent for it.
run.signalUntil?.let { until ->
WorkdayStick.sendLockdown(context, until)
EventLog.append(
context,
"lockdown_sent",
mapOf(
"until" to until.toString(),
"streak" to run.state.streak,
"resend" to run.resend,
),
mapOf("until" to until.toString(), "streak" to run.state.streak),
)
}
return run.verdicts.last().verdict

View File

@ -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"))
}
}

View File

@ -89,6 +89,16 @@ class StickCheckBypassTest {
assertEquals(StickState(), sick.state)
}
@Test
fun aSecondBypassTheSameDayIsAlreadyPenalised() {
val afterSunday = StickState(streak = 1, lockedThrough = mon, lastMiss = sun)
val run = StickCheck.run(
inputs(sun.atTime(8, 0), bypass = setOf(sun), state = afterSunday, checkedThrough = sun),
)
assertEquals(StickVerdict.ALREADY_PENALISED, run.verdicts.single().verdict)
assertNull(run.signalUntil)
}
@Test
fun aBypassCountsOnlyOnARingingDayWithARingOrSessionLive() {
assertTrue(BypassRules.counts(ringingDay = true, ringLive = true, sessionLive = false))

View File

@ -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)
}
}

View File

@ -1,8 +1,4 @@
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
# This newDsl flag was added by the Flutter template
android.newDsl=false

View File

@ -1,8 +1,7 @@
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/probe_passphrase.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/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`.
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await plantProbePassphrase();
await RoomProofSettings.saveNfcTagAt(0, 'ring1');
await RoomProofSettings.saveNfcTagAt(1, 'ring2');
await SessionTagSettings.saveTagAt(SessionTagSlot.bathroom, 'bath');
@ -33,22 +31,5 @@ Future<void> main() async {
await SessionTagSettings.saveTagAt(SessionTagSlot.desk, 'desk');
final scheduler = AlarmScheduler();
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();

View File

@ -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();
}

View File

@ -176,13 +176,10 @@ class _FreeDaysScreenState extends State<FreeDaysScreen> {
appBar: AppBar(
// title removed
actions: [
Tooltip(
message: 'Sync',
child: IconButton(
IconButton(
icon: const Icon(Icons.sync, semanticLabel: 'Sync now'),
onPressed: _busy ? null : () => unawaited(_sync()),
),
),
],
),
body: pool == null

View File

@ -94,9 +94,7 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Tooltip(
message: isConnected ? 'Connected' : 'Disconnected',
child: Icon(
Icon(
isConnected ? Icons.link : Icons.link_off,
color: isConnected
? Theme.of(context).colorScheme.tertiary
@ -106,24 +104,18 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
? 'Connected to GitHub.'
: 'Not connected to GitHub.',
),
),
const SizedBox(height: 12),
if (!isConnected)
Tooltip(
message: 'Connect',
child: ElevatedButton(
ElevatedButton(
key: const ValueKey<String>('github-connect'),
onPressed: _busy ? null : _connectGitHub,
child: const Icon(
Icons.link,
semanticLabel: 'Connect GitHub',
),
),
)
else
Tooltip(
message: 'Disconnect',
child: OutlinedButton(
OutlinedButton(
key: const ValueKey<String>('github-disconnect'),
onPressed: _busy ? null : _disconnect,
child: const Icon(
@ -131,7 +123,6 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
semanticLabel: 'Disconnect GitHub',
),
),
),
const SizedBox(height: 16),
StatusCue(semanticLabel: _status),
],

View File

@ -55,10 +55,8 @@ class HomeBody extends StatelessWidget {
final VoidCallback? onEscaped;
IconData? _statusIcon(String status) {
if (status.contains('Connect a sync backend')) return Icons.cloud_off;
if (status.contains('Sync store unavailable')) return Icons.sync_problem;
// Saved and armed offline; the push rides the next sync.
if (status.contains('Saved locally')) return Icons.cloud_upload;
if (status.startsWith('Connect a sync backend')) return Icons.cloud_off;
if (status.startsWith('Sync store unavailable')) return Icons.sync_problem;
if (status.contains('✓')) return Icons.cloud_done;
return null;
}
@ -79,15 +77,12 @@ class HomeBody extends StatelessWidget {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Tooltip(
message: 'Armed',
child: Icon(
Icon(
Icons.alarm_on,
size: 32,
color: theme.colorScheme.primary,
semanticLabel: 'Alarm is armed for',
),
),
HomePresenceLine(key: ValueKey<int>(syncEpoch)),
const SizedBox(height: 16),
Text(
@ -101,29 +96,23 @@ class HomeBody extends StatelessWidget {
Row(
mainAxisSize: MainAxisSize.min,
children: [
Tooltip(
message: 'Oneshot',
child: Icon(
Icon(
Icons.restore,
size: 18,
semanticLabel:
'One-shot early start, back to $baseline '
'after it rings',
),
),
Text(baseline),
],
)
else
Tooltip(
message: 'Daily',
child: Icon(
Icon(
Icons.all_inclusive,
size: 18,
color: theme.colorScheme.onSurfaceVariant,
semanticLabel: 'Every day. It cannot be turned off.',
),
),
const SizedBox(height: 32),
SizedBox(
width: double.infinity,
@ -150,15 +139,12 @@ class HomeBody extends StatelessWidget {
),
if (!configured) ...[
const SizedBox(height: 16),
Tooltip(
message: 'Offline',
child: Icon(
Icon(
Icons.cloud_off,
size: 28,
color: theme.extension<AppStatusColors>()!.warning,
semanticLabel: 'Open Settings to connect Firebase',
),
),
],
],
),

View File

@ -183,7 +183,6 @@ class _HomeScreenState extends State<HomeScreen> {
color: Theme.of(context).colorScheme.onSurfaceVariant,
semanticLabel: 'Free days',
),
tooltip: 'Free-days',
onPressed: () => Navigator.push<void>(
context,
appRoute<void>(context, (_) => const FreeDaysScreen()),
@ -195,7 +194,6 @@ class _HomeScreenState extends State<HomeScreen> {
color: Theme.of(context).colorScheme.onSurfaceVariant,
semanticLabel: 'Sick days',
),
tooltip: 'Sick-days',
onPressed: () => Navigator.push<void>(
context,
appRoute<void>(context, (_) => const SickDaysScreen()),

View File

@ -62,19 +62,13 @@ class _RingStakesLineState extends State<RingStakesLine> {
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Tooltip(
message: 'Deadline',
child: Icon(Icons.gavel_outlined, color: warningColor),
),
Icon(Icons.gavel_outlined, color: warningColor),
const SizedBox(width: 4),
Text(hhmm(stakes.by), style: TextStyle(color: warningColor)),
const SizedBox(width: 4),
const Icon(Icons.arrow_forward, size: 16),
const SizedBox(width: 4),
Tooltip(
message: 'Lock',
child: Icon(Icons.lock_outline, color: warningColor),
),
Icon(Icons.lock_outline, color: warningColor),
const SizedBox(width: 4),
Text(
_formatLockDate(stakes.lockThrough),

View File

@ -176,7 +176,7 @@ class _SessionScreenState extends State<SessionScreen> {
// The native deadline already rang (see [AlarmScheduler.isRinging]):
// the dismiss sequence belongs in front now, not after the 20 s grace.
if (session.isActive && await _scheduler.isRinging()) {
await _ring(await nativeRingReason(_scheduler, session), now);
await _ring('deadline:${session.currentLeg!.name}', now);
return;
}
if (!mounted) return;

View File

@ -93,9 +93,7 @@ class SettingsScreen extends StatelessWidget {
locked: locked,
),
),
Tooltip(
message: 'Export',
child: IconButton(
IconButton(
key: const Key('settings-export'),
icon: const Icon(Icons.upload_file, semanticLabel: 'Export data'),
onPressed: () => _run(context, () async {
@ -103,10 +101,7 @@ class SettingsScreen extends StatelessWidget {
return true;
}),
),
),
Tooltip(
message: 'Import',
child: IconButton(
IconButton(
key: const Key('settings-import'),
icon: const Icon(Icons.download, semanticLabel: 'Import data'),
onPressed: () => _run(
@ -114,7 +109,6 @@ class SettingsScreen extends StatelessWidget {
onImport ?? () => pickAndImport(alarm: alarmService),
),
),
),
],
),
body: ListView(

View File

@ -32,10 +32,7 @@ class StakesMarks extends StatelessWidget {
};
final rows = <Widget>[
_row('title', view.title, <Widget>[
Tooltip(
message: 'Stakes',
child: Icon(kindIcon, color: theme.colorScheme.primary),
),
Icon(kindIcon, color: theme.colorScheme.primary),
Icon(view.isToday ? Icons.today : Icons.event, size: 18),
Text(_dm(view.day), style: theme.textTheme.titleMedium),
]),
@ -49,39 +46,34 @@ class StakesMarks extends StatelessWidget {
if (dismissBy != null && lock != null) {
rows.add(
_row('stick', words.first, <Widget>[
const Tooltip(message: 'Alarm', child: Icon(Icons.alarm)),
const Icon(Icons.alarm),
Text(hhmm(dismissBy)),
const Icon(Icons.arrow_forward, size: 16),
const Tooltip(message: 'Lock', child: Icon(Icons.lock_outline)),
const Icon(Icons.lock_outline),
Text(_dm(lock)),
]),
);
} else if (finishBy != null && open != null) {
rows.add(
_row('carrot', words.first, <Widget>[
const Tooltip(message: 'Finish', child: Icon(Icons.flag_outlined)),
const Icon(Icons.flag_outlined),
Text(hhmm(finishBy)),
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)),
]),
);
} else if (view.kind != StakesDayKind.free &&
view.kind != StakesDayKind.sick) {
rows.add(
_row('unarmed', words.first, const <Widget>[
Tooltip(message: 'Off', child: Icon(Icons.alarm_off)),
]),
_row('unarmed', words.first, const <Widget>[Icon(Icons.alarm_off)]),
);
}
if (ring != null) {
rows.add(
_row('pc-ring', words.last, <Widget>[
const Tooltip(message: 'PC', child: Icon(Icons.computer)),
const Tooltip(
message: 'Ring',
child: Icon(Icons.notifications_active_outlined),
),
const Icon(Icons.computer),
const Icon(Icons.notifications_active_outlined),
Text(hhmm(ring)),
]),
);
@ -112,30 +104,18 @@ class StakesMarks extends StatelessWidget {
return <Widget>[
if (view.escapedToday)
_row('escaped', next(), <Widget>[
Tooltip(
message: 'Escaped',
child: Icon(Icons.bug_report_outlined, color: warning),
),
Icon(Icons.bug_report_outlined, color: warning),
Icon(Icons.check, color: warning),
]),
if (locked != null)
_row('locked', next(), <Widget>[
Tooltip(
message: 'Lock',
child: Icon(Icons.lock_outline, color: warning),
),
Icon(Icons.lock_outline, color: warning),
Text(_dm(locked), style: style),
]),
if (view.missedToday)
_row('missed', next(), <Widget>[
Tooltip(
message: 'Missed',
child: Icon(Icons.close, color: warning),
),
Tooltip(
message: 'PC',
child: Icon(Icons.computer, color: warning),
),
Icon(Icons.close, color: warning),
Icon(Icons.computer, color: warning),
]),
];
}

View File

@ -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_scheduler.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
/// 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.
///
/// 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 {
/// Creates a publisher; [arming] is injectable for tests.
AlarmPublisher({AlarmArming? arming})
@ -26,88 +21,53 @@ class AlarmPublisher {
/// 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
/// 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({
required AlarmSyncService? service,
required int hour,
required int minute,
http.Client? httpClient,
}) 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();
// syncBackend() falls back to GitHub alone, or pushes to Firebase alone
// via the mirror, so either credential is enough to proceed.
final configured = settings.isConfigured || await loadAccount() != null;
if (configured) {
final hasFirebase = await loadAccount() != null;
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 {
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 service.push(settings.token, httpClient: httpClient);
await service.push(settings.token);
await applySyncedSettings(service);
final problem = await arming.arm(hour, minute);
if (problem != null) return problem;
final inClock = await arming.registerWithClockApp(hour, minute);
return syncedStatus(hour, minute, inClock: inClock);
} on Exception catch (e) {
// The local save and the arming are already done; only the push
// failed. Say so — the time is not lost, it rides the next publish.
return armProblem ??
'${armedFor(hour, minute)}Saved locally — will sync to PC. '
'Error: $e';
}
} else {
return armProblem ??
'${armedFor(hour, minute)}'
'Connect a sync backend in Settings first.';
}
} else {
// Distinct from the "connect a backend" line on purpose. Both used to
// report the same thing, so a store that failed to open looked like a
// configuration the user had never done.
return armProblem ??
'${armedFor(hour, minute)}Sync store unavailable — reopen the app.';
}
return armProblem ?? syncedStatus(hour, minute, inClock: inClock);
return 'Error: $e';
}
}
}
/// 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.
/// never claims it. Only reached after `arm()` succeeded.
String syncedStatus(int hour, int minute, {required bool inClock}) {
final synced = '${armedFor(hour, minute)}Synced to PC ✓';
final time =
'${hour.toString().padLeft(2, '0')}:'
'${minute.toString().padLeft(2, '0')}';
final synced = 'Armed for $time. Synced to PC ✓';
return inClock ? '$synced Clock app set ✓' : synced;
}

View File

@ -207,16 +207,6 @@ class AlarmScheduler {
Future<bool> isRinging() async =>
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`,
/// `distanceMeters`, `reason`.
///

View File

@ -17,7 +17,6 @@ import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:http/http.dart' as http;
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.
///
@ -49,7 +48,6 @@ SecureCredentialStore credentialStore() => SecureCredentialStore(
/// Reads the per-device account, or null when sync has not been set up.
Future<FirebaseAccount?> loadAccount() async {
if (syncEmulatorOn) return emulatorAccount;
try {
return FirebaseAccount.tryParse(
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
/// token, so the usual path costs no authentication round trip.
Future<FirebaseRestClient?> openFirebase() async {
if (syncEmulatorOn) return emulatorClient();
final account = await loadAccount();
if (account == null) {
// 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
/// fact syncing looked broken.
Future<bool> isFirebaseConfigured() async {
if (syncEmulatorOn) return true;
try {
final auth = FirebaseTokenProvider(
apiKey: kProject.apiKey,
@ -218,8 +214,6 @@ Future<FirebaseRestClient?> _clientFromStoredSession() async {
/// (`_fetch_firebase_alarm() or _fetch_github_alarm()`), so a phone that has
/// not moved yet still reaches it.
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();
return firebase == null
? github

View File

@ -54,9 +54,7 @@ class SessionHandoff {
final current = await store.loadCurrent();
if (current != null && current.date == today) {
if (!current.isActive) return false;
current
..adoptBypassReRing(await scheduler.takeBypassReRing())
..recordReRing(now);
current.recordReRing(now);
await store.save(current);
return true;
}

View File

@ -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
/// marker when the re-ring was spent.
String noticeLabel(MorningSession session) {

View File

@ -162,18 +162,6 @@ extension SessionRules on MorningSession {
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.
///
/// 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) {
final leg = currentLeg;
reRings++;
reRingReasons.add(pendingReRingReason ?? reRingReasonFor(null));
reRingReasons.add(pendingReRingReason ?? 'deadline:${leg?.name ?? 'none'}');
pendingReRingReason = null;
if (leg != null && !now.isBefore(deadline(leg))) deadlineRung.add(leg);
updatedAt = now;

View File

@ -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,
);

View File

@ -37,15 +37,6 @@ enum CueKind {
CueKind? cueKindOf(String status) {
if (status.isEmpty) return null;
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 = [
'Error',
@ -81,6 +72,10 @@ CueKind? cueKindOf(String status) {
if (status.contains(kw)) return CueKind.ok;
}
if (status.contains('Connect a sync backend') ||
status.contains('Open Settings')) {
return CueKind.warning;
}
return CueKind.info;
}

View File

@ -101,20 +101,20 @@ packages:
dependency: "direct main"
description:
path: crdt_sync_dart
ref: "crdt_sync_dart-v0.14.2"
resolved-ref: "171a7f8ae34cec78df17a680e42878ca0b97c137"
ref: "crdt_sync_dart-v0.14.1"
resolved-ref: edd0f7a7882cb1d3904932ba94faa282d08165df
url: "https://github.com/kuhyx/utils"
source: git
version: "0.14.2"
version: "0.14.1"
crdt_sync_flutter:
dependency: "direct main"
description:
path: crdt_sync_flutter
ref: "crdt_sync_flutter-v0.9.2"
resolved-ref: "41af57870207f80a5bf571f15544a08fddcbe7bf"
ref: "crdt_sync_flutter-v0.9.1"
resolved-ref: "48dc28ad97b97c787aba4479c3ce51aade6e86b5"
url: "https://github.com/kuhyx/utils"
source: git
version: "0.9.2"
version: "0.9.1"
cross_file:
dependency: transitive
description:
@ -812,11 +812,11 @@ packages:
dependency: "direct main"
description:
path: sync_settings_ui
ref: "sync_settings_ui-v0.8.6"
resolved-ref: "41af57870207f80a5bf571f15544a08fddcbe7bf"
ref: "sync_settings_ui-v0.8.5"
resolved-ref: abfb596d7ce2f28acfefbd55e7b3227257325261
url: "https://github.com/kuhyx/utils"
source: git
version: "0.8.6"
version: "0.8.5"
term_glyph:
dependency: transitive
description:

View File

@ -12,13 +12,13 @@ dependencies:
crdt_sync:
git:
url: https://github.com/kuhyx/utils
ref: crdt_sync_dart-v0.14.2
ref: crdt_sync_dart-v0.14.1
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
ref: crdt_sync_flutter-v0.9.1
path: crdt_sync_flutter
cupertino_icons: 2.0.0
@ -61,7 +61,7 @@ dependencies:
sync_settings_ui:
git:
url: https://github.com/kuhyx/utils
ref: sync_settings_ui-v0.8.6
ref: sync_settings_ui-v0.8.5
path: sync_settings_ui
url_launcher: 6.3.3
uuid: 4.6.0

View File

@ -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:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wake_alarm_sync/services/alarm_arming.dart';
import 'package:wake_alarm_sync/services/alarm_publisher.dart';
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
import 'package:wake_alarm_sync/services/alarm_sync_service.dart';
import '../e2e_support.dart';
import '../fake_day_pool_store.dart';
import '../fake_secure_storage.dart';
/// 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() {
TestWidgetsFlutterBinding.ensureInitialized();
@ -69,17 +13,12 @@ void main() {
});
test('an unconfigured install is told to connect a backend', () async {
final scheduler = _RecordingScheduler();
final service = await _service();
final message = await AlarmPublisher(
arming: _RecordingArming(scheduler),
).publish(service: service, hour: 8, minute: 0);
// Offline-first: the time is stored locally and the phone is armed even
// though nothing can be pushed yet.
expect(service.currentAlarm, (hour: 8, minute: 0));
expect(message, contains('Armed for 08:00'));
final message = await AlarmPublisher().publish(
service: null,
hour: 8,
minute: 0,
);
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 {
@ -91,78 +30,13 @@ void main() {
SharedPreferences.setMockInitialValues(<String, Object>{
'github_token': 'ghp_configured',
});
final scheduler = _RecordingScheduler();
final message = await AlarmPublisher(
arming: _RecordingArming(scheduler),
).publish(service: null, hour: 8, minute: 0);
expect(message, contains('Armed for 08:00'));
final message = await AlarmPublisher().publish(
service: null,
hour: 8,
minute: 0,
);
expect(message, isNot(contains('Connect a sync backend')));
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', () {

View File

@ -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']);
});
}

View File

@ -13,12 +13,10 @@ void main() {
final now = DateTime(2026, 9, 17, 8, 4);
var hasNfc = true;
String? bypassCause;
late List<String> calls;
setUp(() {
hasNfc = true;
bypassCause = null;
calls = <String>[];
SharedPreferences.setMockInitialValues(<String, Object>{});
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
@ -26,7 +24,6 @@ void main() {
const MethodChannel(AlarmScheduler.channelName),
(call) async {
calls.add(call.method);
if (call.method == 'takeBypassReRing') return bypassCause;
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 {
final store = SessionStore();
await store.save(

View File

@ -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');
});
}

View File

@ -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');
});
}

View File

@ -51,14 +51,7 @@ void _collectSubtree(Element element, Set<Element> out) {
void expectNoWords(WidgetTester tester, String screen) {
final words = wordsOnScreen(tester);
expect(words, isEmpty, reason: 'words on $screen: $words');
final tooltips = tester.widgetList<Tooltip>(find.byType(Tooltip));
for (final tooltip in tooltips) {
expect(
tooltip.message,
matches(RegExp(r'^[^\s.!?,;:]{1,20}$')),
reason: 'tooltip on $screen: ${tooltip.message}',
);
}
expect(find.byType(Tooltip), findsNothing, reason: 'tooltip on $screen');
}
/// Pixel 6a portrait: 1080x2400 physical at 2.625.

View File

@ -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);
});
}

View File

@ -3,7 +3,6 @@ library;
import 'package:flutter_test/flutter_test.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';
void main() {
@ -61,24 +60,6 @@ void main() {
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', () {
expect(cueKindOf('hello'), equals(CueKind.info));
expect(cueKindOf('Syncing now'), equals(CueKind.info));

View File

@ -8,7 +8,7 @@ version = "1.0.0"
description = "Trigger that starts the morning routine at the phone's alarm time"
requires-python = ">=3.14"
dependencies = [
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.2#subdirectory=gatelock",
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock",
# 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
# install degrades the read instead of killing the per-minute trigger.
@ -169,6 +169,10 @@ addopts = [
"--strict-markers",
"--strict-config",
"-ra",
"--cov=wake_alarm",
"--cov-branch",
"--cov-report=term-missing",
"--cov-report=lcov",
]
filterwarnings = [
"error",
@ -186,6 +190,7 @@ omit = [
]
[tool.coverage.report]
fail_under = 100
show_missing = true
skip_covered = false
exclude_lines = [

View File

@ -4,10 +4,10 @@
# it is missing — but it is required here for mypy/pylint/tests.
bandit==1.9.4
codespell==2.4.3
coverage==7.17.5
coverage==7.17.4
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.2#subdirectory=gatelock
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock
kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
mypy==2.4.1
pre-commit==4.7.0

View File

@ -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())

View File

@ -21,13 +21,7 @@ import json
import logging
from typing import Any
from wake_alarm._constants import (
FOCUS_OWNER_DEVICE_ID,
MAX_HOUR,
MAX_MINUTE,
MIN_HOUR,
MIN_MINUTE,
)
from wake_alarm._constants import MAX_HOUR, MAX_MINUTE, MIN_HOUR, MIN_MINUTE
_logger = logging.getLogger(__name__)
@ -194,10 +188,6 @@ def newest_alarm(
"""
ranked: list[tuple[str, str, tuple[int, int]]] = []
for device_id, raw in published:
# focus-owner publishes only its bypass events, never an alarm; parsing
# it would log a WARNING on every live fetch.
if device_id == FOCUS_OWNER_DEVICE_ID:
continue
parsed = parse_log(raw)
if parsed is None:
_logger.info("Ignoring unusable alarm published by %r", device_id)

View File

@ -49,11 +49,6 @@ SYNC_TOKEN_FALLBACK_FILES: tuple[Path, ...] = (
# Where a successful read is cached, so a network blip can't cost a wake-up.
ALARM_CACHE_FILE: Path = Path.home() / ".config" / "wake_alarm" / "alarm_cache.json"
# The last successful Firebase fetch of every device's log, served offline.
SYNC_LOGS_CACHE_FILE: Path = (
Path.home() / ".config" / "wake_alarm" / "synced_logs_cache.json"
)
# Structured logs live under XDG state, not .config: they are churning runtime
# data, not configuration. The JSONL file is additive -- the journal keeps
@ -81,10 +76,6 @@ SYNC_LEGACY_PREFIX: str = "wake-alarm-sync/devices"
# lists. Copied over from the plaintext prefix like everything else.
SYNC_ALARM_PATH: str = f"{SYNC_DEVICES_PREFIX}/phone/alarm.json"
# focus-owner's own device directory. It publishes ``bypass`` with cause
# ``uninstalled`` when WakeAlarm is gone, so it is never the phone's push.
FOCUS_OWNER_DEVICE_ID: str = "focus-owner"
# The file each device publishes its alarm as, inside its own directory.
SYNC_ALARM_FILENAME: str = "alarm.json"

View File

@ -25,7 +25,6 @@ from wake_alarm._constants import (
ESCAPE_HATCH_LAST_DAY,
ESCAPE_REASON_MIN_CHARS,
ESCAPES_FIELD,
FOCUS_OWNER_DEVICE_ID,
PHONE_EVENTS_FIELD,
RING_STARTED_FIELD,
STICK_STATE_FIELD,
@ -205,13 +204,10 @@ def newest_push(logs: list[tuple[str, dict[str, Any]]]) -> float | None:
Every phone write stamps the field it changed, so the largest instant is
when the phone last uploaded anything. A stamp that cannot be dated is
skipped: None means "cannot tell", never "old". focus-owner's writes are
not the phone's: it publishes exactly when WakeAlarm is uninstalled.
skipped: None means "cannot tell", never "old".
"""
stamps: list[float] = []
for device_id, log in logs:
if device_id == FOCUS_OWNER_DEVICE_ID:
continue
for _, log in logs:
record = log.get("alarm")
fields = record.get("fields") if isinstance(record, dict) else None
for name in fields if isinstance(fields, dict) else ():

View File

@ -15,7 +15,6 @@ no session, no escape": fail toward ringing.
python -m wake_alarm._fallback --tick # what the timer runs
python -m wake_alarm._fallback --dry-run # decide now, change nothing
python -m wake_alarm._fallback --show # latch + last decision, offline
python -m wake_alarm._fallback --dry-run --published F # F replaces Firebase
"""
from __future__ import annotations
@ -51,7 +50,6 @@ from wake_alarm._fallback_policy import (
)
from wake_alarm._fallback_ring import ring
from wake_alarm._logging_setup import configure_logging
from wake_alarm._published_file import load_published
from wake_alarm._ring_probe import maybe_probe
from wake_alarm._ring_wav import SYSTEM_WAV_DIR, USER_WAV_DIR, ensure_pair
from wake_alarm._sick import alarm_stands_down
@ -217,22 +215,13 @@ def _terminate(signum: int, _frame: FrameType | None) -> None:
def main(argv: list[str] | None = None) -> int:
"""Entry point."""
parser = mode_parser("PC fallback alarm tick", "tick", "decide and act")
parser.add_argument("--published", help="with --dry-run: phone logs file")
args, now = parse_with_now(parser, argv, _now)
planted = None
if args.published is not None:
if not args.dry_run:
parser.error("--published only goes with --dry-run")
try:
planted = load_published(args.published)
except (OSError, TypeError, ValueError) as exc:
parser.error(f"--published {args.published}: {exc}")
if args.show:
sys.stdout.write(show(now))
elif args.dry_run and in_evening(now):
sys.stdout.write(evening_dry_run(now, planted))
sys.stdout.write(evening_dry_run(now))
elif args.dry_run:
seen = observe(now, sync=False, planted=planted)
seen = observe(now, sync=False)
sys.stdout.write(describe(seen, decide(seen.facts)))
else:
configure_logging(component="fallback")

View File

@ -57,10 +57,8 @@ def _tomorrow_off(now: datetime, *, sync: bool) -> str | None:
return SICK_TOMORROW if sick(tomorrow) else None
def observe_evening(
now: datetime, *, sync: bool, planted: list[tuple[str, str]] | None = None
) -> EveningFacts:
"""Gather the evening's facts; Firebase (or ``planted``) only when needed."""
def observe_evening(now: datetime, *, sync: bool) -> EveningFacts:
"""Gather the evening's facts; Firebase only when it can change them."""
day = now.date().isoformat()
facts = EveningFacts(
now=now,
@ -69,7 +67,7 @@ def observe_evening(
)
if not needs_fetch(facts):
return facts
published = fetch_firebase_logs() if planted is None else planted
published = fetch_firebase_logs()
if published is None:
return replace(facts, reachable=False)
return replace(
@ -154,9 +152,9 @@ def evening_tick(now: datetime) -> Decision:
return decision
def evening_dry_run(now: datetime, planted: list[tuple[str, str]] | None = None) -> str:
def evening_dry_run(now: datetime) -> str:
"""The ``--dry-run`` report for a 21:xx instant; writes nothing."""
facts = observe_evening(now, sync=False, planted=planted)
facts = observe_evening(now, sync=False)
decision = decide(facts)
verdict = "WOULD RING" if decision.ring else "quiet"
return (

View File

@ -62,14 +62,11 @@ def _sick_today(now: datetime, *, online: bool, sync: bool) -> bool:
return alarm_stands_down(now.date())
def observe(
now: datetime, *, sync: bool, planted: list[tuple[str, str]] | None = None
) -> Observation:
def observe(now: datetime, *, sync: bool) -> Observation:
"""Gather the facts; the network only when the decision needs it.
``sync`` is False for ``--dry-run``: pulling the sick-day pool rewrites
its local file, and a dry run writes nothing. ``planted`` (``--dry-run
--published``) stands in for the Firebase fetch.
its local file, and a dry run writes nothing.
"""
day = now.date().isoformat()
latch = read_latch(day)
@ -85,7 +82,7 @@ def observe(
)
if facts.free_day or facts.sick_day or not online:
return Observation(facts)
published = fetch_firebase_logs() if planted is None else planted
published = fetch_firebase_logs()
if published is None:
return Observation(facts, reachable=False)
view = enforcement_view(published)

View File

@ -64,8 +64,7 @@ def latest_field[T](
field: str, parse: Callable[[object, str], T | None], *, what: str
) -> T | None:
"""``newest_field`` over a live Firebase read; None when unreadable."""
# Offline-first: a dead network serves the last synced logs.
published = fetch_firebase_logs(offline_cache=True)
published = fetch_firebase_logs()
if published is None:
return None
value = newest_field(published, field, parse)

View File

@ -1,42 +0,0 @@
"""A planted stand-in for ``fetch_firebase_logs()``: ``--published FILE``.
Only for ``_fallback --dry-run``: the live check of the bypass ring needs
``bypass`` / ``dismissed`` events the PC can read, and there is no test
backend to put them in. The file is a JSON list of ``[device_id, alarm]``
pairs, the shape ``fetch_firebase_logs()`` returns. ``alarm`` is the
decrypted ``alarm.json`` -- an object (re-serialised here) or its raw text,
passed through as-is.
"""
from __future__ import annotations
import json
from pathlib import Path
_PAIR_LEN = 2
def _pair(entry: object) -> tuple[str, str]:
"""One ``[device_id, alarm]`` entry as ``(device_id, raw_json)``."""
if not isinstance(entry, list) or len(entry) != _PAIR_LEN:
msg = f"expected [device_id, alarm], got {entry!r}"
raise TypeError(msg)
device, alarm = entry
if not isinstance(device, str):
msg = f"device id must be a string, got {device!r}"
raise TypeError(msg)
if isinstance(alarm, str):
return device, alarm
if isinstance(alarm, dict):
return device, json.dumps(alarm)
msg = f"alarm for {device!r} must be an object or its JSON text"
raise TypeError(msg)
def load_published(path: str) -> list[tuple[str, str]]:
"""The planted logs; OSError/ValueError/TypeError when the file is unusable."""
raw = json.loads(Path(path).read_text(encoding="utf-8"))
if not isinstance(raw, list):
msg = "expected a JSON list of [device_id, alarm] pairs"
raise TypeError(msg)
return [_pair(entry) for entry in raw]

View File

@ -16,7 +16,7 @@ from datetime import timedelta
from typing import TYPE_CHECKING
from wake_alarm._constants import LOG_STATE_DIR
from wake_alarm._events import emit, emit_on_change
from wake_alarm._events import emit
from wake_alarm._ring_player import _ok, graphical_session
if TYPE_CHECKING:
@ -33,12 +33,8 @@ def maybe_probe(now: datetime, alarm_at: datetime) -> str | None:
return None
graphical, why = graphical_session()
if graphical:
# Not the state a fallback ring meets; try again tomorrow. Logged
# once a day, so a morning with no ring_probe line is a bug.
reason = "waiting_for_no_session"
key = f"{now.date().isoformat()}|{reason}"
emit_on_change("ring_probe", key, reason, session=why)
return reason
# Not the state a fallback ring meets; try again tomorrow.
return "waiting_for_no_session"
started, out = _ok(["sudo", "-n", "systemctl", "start", PROBE_UNIT])
emit("ring_probe", "started" if started else "failed", session=why, output=out)
if not started:

View File

@ -1,65 +0,0 @@
"""The last successfully-fetched Firebase logs, read back when offline.
``fetch_firebase_logs`` writes the cache after every success and, for the
display readers that ask for it (``_weight``, ``_energy`` via
``_field_reader``), serves it when a fetch fails, so they still answer with
the newest known data while the network is down. The alarm path and the
enforcement checks do not ask: they must see a failed read as a failure.
The alarm time keeps its own ``ALARM_CACHE_FILE``; this is the *details*
half of offline-first: the raw per-device logs, not just the hour and
minute.
"""
from __future__ import annotations
import json
import logging
from wake_alarm._constants import SYNC_LOGS_CACHE_FILE
_logger = logging.getLogger(__name__)
#: The arity of one cached ``(device_id, raw_log_json)`` pair.
_PAIR_ARITY = 2
def write_synced_logs_cache(published: list[tuple[str, str]]) -> None:
"""Persist [published] ``(device_id, raw_log_json)`` pairs.
A failed write is logged and swallowed: the fetch already succeeded, and
losing the cache must not crash the per-minute trigger or a reader.
"""
entry = {"logs": [[device_id, raw] for device_id, raw in published]}
try:
SYNC_LOGS_CACHE_FILE.parent.mkdir(parents=True, exist_ok=True)
SYNC_LOGS_CACHE_FILE.write_text(json.dumps(entry, indent=2))
except OSError as exc:
_logger.warning("Cannot write synced-logs cache: %s", exc)
def read_synced_logs_cache() -> list[tuple[str, str]] | None:
"""The cached pairs, or None when absent, unreadable or malformed.
A corrupt cache degrades to "nothing cached" — the fetch then degrades
further to its own fallbacks — never to a crash.
"""
try:
cached = json.loads(SYNC_LOGS_CACHE_FILE.read_text())
except OSError, json.JSONDecodeError:
return None
if not isinstance(cached, dict):
return None
logs = cached.get("logs")
if not isinstance(logs, list) or not logs:
return None
pairs = [
(pair[0], pair[1])
for pair in logs
if (
isinstance(pair, list)
and len(pair) == _PAIR_ARITY
and isinstance(pair[0], str)
and isinstance(pair[1], str)
)
]
return pairs or None

View File

@ -36,7 +36,6 @@ from wake_alarm._constants import (
SYNC_REPO_NAME,
SYNC_REPO_OWNER,
)
from wake_alarm._sync_log_cache import read_synced_logs_cache, write_synced_logs_cache
if TYPE_CHECKING:
from crdt_sync import Argon2Params, RemoteStore
@ -123,7 +122,7 @@ def _read_published(client: RemoteStore) -> list[tuple[str, str]]:
return published
def fetch_firebase_logs(*, offline_cache: bool = False) -> list[tuple[str, str]] | None:
def fetch_firebase_logs() -> list[tuple[str, str]] | None:
"""Fetch every device's decrypted ``alarm.json`` from Firebase.
Shared by the alarm reader and ``_weight``: the morning session's
@ -134,15 +133,6 @@ def fetch_firebase_logs(*, offline_cache: bool = False) -> list[tuple[str, str]]
(no or wrong passphrase) store, so the caller can fall back to GitHub and
then to the cache.
Every successful fetch rewrites the synced-logs cache. Only a caller that
passes *offline_cache* gets that cache back when the fetch fails: the
display readers (``_weight``, ``_energy``) want the newest known value
offline, while the alarm path (which has its own cache *after* the
GitHub fallback) and the enforcement checks must still see the failure.
Args:
offline_cache: Serve the last cached logs when the fetch fails.
Returns:
``(device_id, raw_json)`` per device, or None if unconfigured,
locked or unreadable.
@ -166,11 +156,10 @@ def fetch_firebase_logs(*, offline_cache: bool = False) -> list[tuple[str, str]]
E2eLockedError,
) as exc:
_logger.info("Cannot fetch the alarm from Firebase: %s", exc)
return read_synced_logs_cache() if offline_cache else None
return None
if not published:
_logger.info("No alarm published to Firebase yet")
return None
write_synced_logs_cache(published)
return published

View File

@ -186,12 +186,6 @@ def _hermetic(tmp_path: Path) -> Generator[None]:
# the trigger's cache. A missing Firebase config keeps fetches
# off the network unless a test patches the fetch itself.
patch("wake_alarm._sync.ALARM_CACHE_FILE", tmp_path / "alarm_cache.json"),
# The raw per-device logs (weigh-in, energy, ...) are the *details*
# half of offline-first; keep that cache off the live file too.
patch(
"wake_alarm._sync_log_cache.SYNC_LOGS_CACHE_FILE",
tmp_path / "synced_logs_cache.json",
),
patch(
"wake_alarm._sync_transport.FIREBASE_CONFIG_FILE",
tmp_path / "no-firebase.json",

View File

@ -215,19 +215,3 @@ class TestHlcInstant:
def test_an_unparsable_prefix_is_undated(self) -> None:
"""Garbage before the Z must not raise out of a per-minute tick."""
assert hlc_instant("not-a-timestampZ-0000-device") is None
def test_newest_alarm_skips_focus_owner_without_a_warning(
caplog: pytest.LogCaptureFixture,
) -> None:
"""focus-owner's log never carries an alarm; reading it is not a fault."""
hlc = "2026-11-23T06:00:00.000Z-0000-p"
phone = json.dumps(
{"alarm": {"fields": {"alarm_hour": [7, hlc], "alarm_minute": [30, hlc]}}}
)
owner = json.dumps({"alarm": {"fields": {"phone_events": [[], hlc]}}})
with caplog.at_level("INFO"):
result = newest_alarm([("focus-owner", owner), ("p", phone)])
assert result is not None
assert result[:2] == (7, 30)
assert not [r for r in caplog.records if r.levelname == "WARNING"]

View File

@ -102,11 +102,3 @@ def test_last_push_is_the_newest_dated_hlc_of_any_field_on_any_device() -> None:
def test_last_push_is_none_without_a_dated_stamp() -> None:
assert enforcement_view([("a", _log(alarm_hour=(7, "h")))]).last_push is None
assert enforcement_view([]).last_push is None
def test_last_push_ignores_focus_owner_writes() -> None:
"""focus-owner publishes ``bypass:uninstalled``; that is not a phone push."""
phone = _log(alarm_hour=(7, "2026-11-20T06:00:00.000Z-0000-p"))
owner = _log(phone_events=([], "2026-11-23T09:00:00.000Z-0000-f"))
view = enforcement_view([("p", phone), ("focus-owner", owner)])
assert view.last_push == datetime(2026, 11, 20, 6, 0, tzinfo=UTC).timestamp()

View File

@ -1,119 +0,0 @@
"""``--dry-run --published FILE``: plant the phone's logs without a backend.
The live check of the bypass ring (C8, 2026-11-22) could not see ``ring:
bypass`` from the CLI: there is no test backend to plant a ``bypass`` event
in. The file stands in for ``fetch_firebase_logs()`` -- a dry run only, so
a planted world never rings or writes a latch.
"""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import pytest
from wake_alarm import _fallback, _fallback_evening, _fallback_observe
from wake_alarm._fallback_latch import read_latch
from wake_alarm._published_file import load_published
from wake_alarm._sync import Alarm
if TYPE_CHECKING:
from collections.abc import Generator
from pathlib import Path
DAY = "2026-11-22"
def _alarm_json(*events: dict[str, object]) -> dict[str, object]:
return {"alarm": {"fields": {"phone_events": [list(events), "h"]}}}
def _bypass(at: str) -> dict[str, object]:
return {"at": f"{DAY}T{at}+01:00", "kind": "bypass", "data": {"date": DAY}}
def _write(tmp_path: Path, content: object) -> str:
path = tmp_path / "published.json"
path.write_text(json.dumps(content), encoding="utf-8")
return str(path)
@pytest.fixture(autouse=True)
def no_backend() -> Generator[MagicMock]:
"""Alarm 08:00 and a Firebase fetch that must never run."""
fetch = MagicMock(side_effect=AssertionError("fetched Firebase"))
with (
patch.object(_fallback_observe, "get_alarm", return_value=Alarm(8, 0, "c")),
patch.object(_fallback_observe, "fetch_firebase_logs", fetch),
patch.object(_fallback_evening, "fetch_firebase_logs", fetch),
):
yield fetch
def _dry_run(path: str, at: str) -> int:
return _fallback.main(["--dry-run", "--at", f"{DAY}T{at}", "--published", path])
def test_a_planted_bypass_rings_in_a_dry_run(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
path = _write(tmp_path, [["phone", _alarm_json(_bypass("10:15:00"))]])
assert _dry_run(path, "10:30") == 0
assert "WOULD RING: bypass" in capsys.readouterr().out
assert read_latch(DAY) is None
def test_raw_text_is_passed_through_as_is(tmp_path: Path) -> None:
raw = json.dumps(_alarm_json(_bypass("08:05:00")))
path = _write(tmp_path, [["phone", raw], ["tablet", {"alarm": {}}]])
assert load_published(path) == [
("phone", raw),
("tablet", '{"alarm": {}}'),
]
def test_an_evening_dry_run_reads_the_file_too(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
event = {
"at": f"{DAY}T21:00:00+01:00",
"kind": "notifications",
"data": {"enabled": False},
}
path = _write(tmp_path, [["phone", _alarm_json(event)]])
assert _dry_run(path, "21:05") == 0
assert "firebase=ok" in capsys.readouterr().out
@pytest.mark.parametrize("mode", ["--tick", "--show"])
def test_published_needs_dry_run(tmp_path: Path, mode: str) -> None:
path = _write(tmp_path, [])
with pytest.raises(SystemExit) as exc:
_fallback.main([mode, "--published", path])
assert exc.value.code == 2
@pytest.mark.parametrize(
"content",
[
{"phone": {}},
[["phone"]],
[[1, "{}"]],
[["phone", 3]],
],
)
def test_a_malformed_file_is_refused(tmp_path: Path, content: object) -> None:
with pytest.raises(SystemExit) as exc:
_dry_run(_write(tmp_path, content), "08:10")
assert exc.value.code == 2
def test_a_missing_or_unparsable_file_is_refused(tmp_path: Path) -> None:
bad = tmp_path / "bad.json"
bad.write_text("{", encoding="utf-8")
for path in (str(bad), str(tmp_path / "absent.json")):
with pytest.raises(SystemExit) as exc:
_dry_run(path, "08:10")
assert exc.value.code == 2

View File

@ -67,16 +67,3 @@ def test_it_waits_for_a_morning_with_no_session(done_file: Path) -> None:
def test_a_refused_start_is_retried_next_morning(done_file: Path) -> None:
assert _run(-3, graphical=False, started=False) == "failed"
assert not done_file.exists()
def test_a_skipped_morning_is_logged_once_a_day() -> None:
# Without it, a missing ring_probe line at 08:00 cannot tell "kuhy was
# logged in" from "the probe never ran".
with patch.object(_ring_probe, "emit_on_change") as emit:
assert _run(-3, graphical=True) == "waiting_for_no_session"
emit.assert_called_once_with(
"ring_probe",
"2026-11-23|waiting_for_no_session",
"waiting_for_no_session",
session="why",
)

View File

@ -1,200 +0,0 @@
"""The offline-first fallback of every Firebase-log reader.
``fetch_firebase_logs`` caches its last success (``_sync_log_cache``) and
serves it when a fetch fails, so the field readers (``_weight``,
``_energy``, ...) answer with the newest known data while the network is
down. These tests pin that contract.
"""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from crdt_sync import RemoteSyncError
import pytest
from wake_alarm import _sync_log_cache
from wake_alarm._sync_log_cache import (
read_synced_logs_cache,
write_synced_logs_cache,
)
from wake_alarm._sync_transport import fetch_firebase_logs, fetch_remote_alarm
if TYPE_CHECKING:
from pathlib import Path
from typing import NoReturn
_LOGS = [("device-a", '{"alarm": {}}')]
@pytest.fixture(autouse=True)
def _cache_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Point the cache at tmp for every test here; the autouse conftest
redirect covers the rest of the suite."""
monkeypatch.setattr(
_sync_log_cache, "SYNC_LOGS_CACHE_FILE", tmp_path / "logs_cache.json"
)
def test_write_then_read_roundtrip() -> None:
write_synced_logs_cache(_LOGS)
assert read_synced_logs_cache() == _LOGS
def test_read_missing_file_is_none() -> None:
assert read_synced_logs_cache() is None
def test_read_corrupt_file_is_none() -> None:
file = _sync_log_cache.SYNC_LOGS_CACHE_FILE
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text("not json")
assert read_synced_logs_cache() is None
def test_read_wrong_shape_is_none() -> None:
file = _sync_log_cache.SYNC_LOGS_CACHE_FILE
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(json.dumps({"logs": [{"wrong": "shape"}]}))
assert read_synced_logs_cache() is None
def test_read_cache_not_a_dict_is_none() -> None:
file = _sync_log_cache.SYNC_LOGS_CACHE_FILE
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(json.dumps(["logs"]))
assert read_synced_logs_cache() is None
def test_read_logs_not_a_list_is_none() -> None:
file = _sync_log_cache.SYNC_LOGS_CACHE_FILE
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(json.dumps({"logs": 5}))
assert read_synced_logs_cache() is None
def test_read_empty_logs_is_none() -> None:
file = _sync_log_cache.SYNC_LOGS_CACHE_FILE
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(json.dumps({"logs": []}))
assert read_synced_logs_cache() is None
def test_write_failure_is_swallowed() -> None:
# The cache path is a directory, so write_text raises; the failure must
# be swallowed, not crash the reader it protects.
blocker = _sync_log_cache.SYNC_LOGS_CACHE_FILE
blocker.parent.mkdir(parents=True, exist_ok=True)
blocker.mkdir()
write_synced_logs_cache(_LOGS) # must not raise
def _configured_transport(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""A transport that *is* configured: the fetch reaches the backend."""
config = tmp_path / "firebase-config.json"
config.write_text("{}")
monkeypatch.setattr("wake_alarm._sync_transport.FIREBASE_CONFIG_FILE", config)
monkeypatch.setattr(
"wake_alarm._sync_transport.firebase_client_for", lambda _app: object()
)
def test_failed_fetch_serves_the_cache(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_configured_transport(monkeypatch, tmp_path)
write_synced_logs_cache(_LOGS)
def _fail(_client: object) -> NoReturn:
msg = "offline"
raise RemoteSyncError(msg)
monkeypatch.setattr("wake_alarm._sync_transport._read_published", _fail)
assert fetch_firebase_logs(offline_cache=True) == _LOGS
# Callers that did not ask (alarm path, audit, fallback ring) still see
# the failure: stale logs must not pass for a live read there.
assert fetch_firebase_logs() is None
def test_a_log_cache_does_not_skip_the_github_alarm_fallback(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_configured_transport(monkeypatch, tmp_path)
write_synced_logs_cache(_LOGS)
def _fail(_client: object) -> NoReturn:
msg = "offline"
raise RemoteSyncError(msg)
monkeypatch.setattr("wake_alarm._sync_transport._read_published", _fail)
monkeypatch.setattr(
"wake_alarm._sync_transport._fetch_github_alarm", lambda: (6, 30, None)
)
assert fetch_remote_alarm() == (6, 30, None)
def test_unconfigured_fetch_without_cache_is_none(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
# Conftest default: the config file does not exist, no cache written.
assert fetch_firebase_logs() is None
def test_success_writes_the_cache(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_configured_transport(monkeypatch, tmp_path)
monkeypatch.setattr(
"wake_alarm._sync_transport._read_published", lambda _client: _LOGS
)
assert fetch_firebase_logs() == _LOGS
assert read_synced_logs_cache() == _LOGS
def test_an_empty_fetch_returns_none_and_keeps_the_cache(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
# An empty *successful* fetch (no devices, no exception) means "nothing
# is published right now", not "the last value is still live". Serving
# the old cache here would resurrect a phone that deliberately cleared
# its alarm, so the fetch returns None and leaves the cache untouched.
_configured_transport(monkeypatch, tmp_path)
write_synced_logs_cache(_LOGS)
monkeypatch.setattr(
"wake_alarm._sync_transport._read_published", lambda _client: []
)
assert fetch_firebase_logs() is None
assert read_synced_logs_cache() == _LOGS
def test_weight_offline_comes_from_the_cache(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
# The reader half of offline-first: with the network down, the newest
# known weigh-in is still the one last synced, not "none".
_configured_transport(monkeypatch, tmp_path)
log = json.dumps(
{
"alarm": {
"fields": {
"latest_weight_kg": [
{"date": "2026-11-26", "kg": 81.5},
"2026-11-26T07:00:00.000Z-0-device-a",
]
}
}
}
)
write_synced_logs_cache([("device-a", log)])
def _fail(_client: object) -> NoReturn:
msg = "offline"
raise RemoteSyncError(msg)
monkeypatch.setattr("wake_alarm._sync_transport._read_published", _fail)
from wake_alarm._weight import latest_weight
weight = latest_weight()
assert weight is not None
assert (weight.date, weight.kg) == ("2026-11-26", 81.5)