Compare commits

...

2 Commits

Author SHA1 Message Date
b6e89b93dc workout_app: run the break countdown in a foreground service with notifications
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
pre-commit / pre-commit (push) Has been cancelled
Tests / test (push) Has been cancelled
Tests / lock-popup-safety (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
The between-set break never finished once the phone's screen was off. Three
independent causes (worked through on-device on 2026-09-12; left
uncommitted awaiting the go-ahead, committed here as-is plus one pin bump):

1. The countdown was not wall-clock: `_breakRemaining--` on a
   Timer.periodic, which Android throttles and Doze suspends in a
   backgrounded isolate, so the counter stalled and _onBreakFinished()
   never fired. Now a BreakClock deadline on the wall clock.
2. An expired break was silently dropped on restore (`if (remaining > 0)`
   only) — now cued and logged.
3. No notification infrastructure at all: no package, no
   POST_NOTIFICATIONS / FOREGROUND_SERVICE / WAKE_LOCK.

Now: flutter_foreground_task runs the countdown in a service isolate that
survives BACK and the screen lock; flutter_local_notifications shows an
ongoing "Workout A · break m:ss / Next: …" notification with −1 rep / Done
actions and a "Break over" alert on its own channel (raw break_end sound,
vibration). Button presses go through a persisted BreakIntent queue the
screen drains on resume, so a press with the app killed is not lost.
Finish and Reset stop the service; a startup reaper handles the crash case.

Verified on the phone with the screen off and locked: service alive and
ticking while Dozing, both notifications on the lock screen, channel
importance 5 with the break_end sound. Not verifiable from adb (receiver is
RECEIVER_NOT_EXPORTED): an actual action-button tap, and a true recents
swipe — see stronglift_replacement/TODO-workout-app-v2.md.

Also fixed en route: the break-end sound had never played in any widget
test (AssetSource needs path_provider, which nothing faked, and the failure
was swallowed by catchError); the queue's prune wrote back a stale list.

This commit additionally:
- takes the freshness gate's bump flutter_local_notifications 22.3.1;
- restores web/package.json to HEAD (the tree held a stale pre-bump copy);
- gives scripts/check_flutter_coverage.sh a FLUTTER_TEST_CONCURRENCY knob:
  the default one-isolate-per-core run peaks over 4 GiB and is OOM-killed
  under the resource cap. Default behaviour unchanged.

Gate: flutter analyze clean, 511 tests, 3187/3187 lines (100%), pre-commit
green. Not re-installed on the phone for the 22.3.1 pin: no device attached
at commit time.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C7vgacLhb4WJjxuVj2QLEP
2026-09-13 20:28:36 +02:00
86b63108c7 Tombstone sync records durably: a ledger the PC re-pushes every tick
manual:2026-09-13T14:30 -- the synced copy of the football that this
morning's day-key rekey let back in under a second id -- made every
workout-sync tick log "Manual-workout budget exhausted -- not ingested".
Tombstoning it once did not stick: sync_log pulls only the OTHER devices'
logs and _manual_push re-derives the PC's log from log.json each tick, so
the next push overwrote the tombstone ("tombstoned", then "LIVE" five
seconds later). Deletion is monotonic only for records still in the merge.

- New _sync_tombstones: {id: {deleted_hlc, reason, tombstoned_at}} in
  screen_locker/sync_tombstones.json (gitignored with its siblings). The
  HLC is minted once and stored so re-pushing does not churn the store.
  The ledger path is resolved at call time, not as a default argument, so
  the test suite's redirect actually applies -- verified by hashing the
  real ledger before and after the run.
- _manual_push.records_from_workout_log merges the ledger over the live
  derivation, so every push carries the tombstones.
- scripts/tombstone_sync_record.py <id> [--apply --reason ...]: dry run
  reports live/tombstoned; --apply writes the ledger, runs one tick and
  reports what the store holds afterwards. Rerunnable.
- tests/_isolated_state.py redirects SYNC_TOMBSTONES_FILE (both bindings).

Verified: --apply -> "tombstoned"; a second ordinary tick -> "already
tombstoned" with the same HLC; workout-sync.service now logs "Sync record
manual:2026-09-13T14:30 is tombstoned -- skipping it" and the budget line
for that id is gone. log.json untouched (the local entry stays; it shares
the original's credit per duplicate_credits.json).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C7vgacLhb4WJjxuVj2QLEP
2026-09-13 20:20:06 +02:00
51 changed files with 4332 additions and 104 deletions

2
.gitignore vendored
View File

@ -19,6 +19,8 @@ htmlcov/
screen_locker/log.json
# ...and the ledger naming which of its entries record the same workout.
screen_locker/duplicate_credits.json
# ...and the sync tombstones the PC re-pushes every tick (names a workout id).
screen_locker/sync_tombstones.json
# ...including the timestamped backups a correction script leaves behind.
screen_locker/*.json.bak-*
screen_locker/sick_history.json

View File

@ -113,6 +113,9 @@ SCHEDULED_SKIPS_FILE = Path(__file__).resolve().parent / "scheduled_skips.json"
EXTRA_BENEFITS_FILE = Path(__file__).resolve().parent / "extra_benefits_state.json"
# State file storing the base (pre-bonus) shutdown hours and last reset date.
SHUTDOWN_BASE_FILE = Path(__file__).resolve().parent / "shutdown_base.json"
# Workout records this PC must keep deleted in the sync store, pushed as
# tombstones on every tick (see _sync_tombstones for why once is not enough).
SYNC_TOMBSTONES_FILE = Path(__file__).resolve().parent / "sync_tombstones.json"
# Self-expiring marker: "logged in during today's early-bird window, still
# waiting to see if a real workout shows up." Not a log.json entry —
# it's a same-day pending flag, checked against its own "date" field.

View File

@ -53,6 +53,7 @@ from screen_locker._log_io import load_workout_log
from screen_locker._log_mixin import _derive_workout_id
from screen_locker._push_outcome import describe_push
from screen_locker._sync_retry import with_sync_retry
from screen_locker._sync_tombstones import tombstone_records
from screen_locker._weekly_check import COUNTED_WORKOUT_TYPES
from screen_locker._workout_sync import _DEVICES_PREFIX, read_sync_token, remote_client
@ -157,6 +158,9 @@ def records_from_workout_log(log_file: Path) -> dict[str, Record]:
log[str(record_id)] = Record(
id=str(record_id), fields={_PAYLOAD_FIELD: (payload, hlc)}
)
# Re-pushed every tick: sync_log never reads this device's own remote
# log, so a tombstone written once is overwritten by the next push.
log.update(tombstone_records())
return log

View File

@ -0,0 +1,111 @@
"""Durable tombstones for workout records the PC must keep deleted in sync.
``_manual_push`` re-derives this device's sync log from ``log.json`` on every
tick and pushes it whole, and ``crdt_sync.sync_log`` pulls only the *other*
devices' logs — so a tombstone written once to the PC's device log is
overwritten by the very next push (observed 2026-09-13: ``--apply`` reported
"tombstoned", the dry run five seconds later reported "LIVE"). Deletion is
monotonic only for records that are still *in* the merge.
The fix is to make the tombstone part of what the PC pushes every time. This
module owns that ledger: ``{record_id: {deleted_hlc, reason, tombstoned_at}}``
in ``SYNC_TOMBSTONES_FILE``. The HLC is minted once and stored, so re-pushing
the same tombstone does not churn the store.
The signed ``log.json`` is never touched — a tombstone only stops the record
from syncing; the local entry stays (see ``scripts/annotate_duplicate_credits.py``
for why this repo annotates rather than deletes).
"""
from __future__ import annotations
from datetime import UTC, datetime
import json
import logging
from typing import TYPE_CHECKING, Any
from crdt_sync import Hlc, Record
from screen_locker._constants import SYNC_TOMBSTONES_FILE
if TYPE_CHECKING:
from pathlib import Path
_logger = logging.getLogger(__name__)
def _load(path: Path) -> dict[str, dict[str, Any]]:
"""Read the ledger; a missing file is an empty ledger, a corrupt one is loud."""
if not path.exists():
return {}
try:
raw = json.loads(path.read_text())
except (OSError, json.JSONDecodeError) as exc:
_logger.warning(
"Sync tombstone ledger %s is unreadable (%s) — pushing NO tombstones "
"this tick, so a record deleted here may resurface on other devices",
path,
exc,
)
return {}
if not isinstance(raw, dict):
_logger.warning(
"Sync tombstone ledger %s is not a JSON object — ignoring it", path
)
return {}
return {str(rid): entry for rid, entry in raw.items() if isinstance(entry, dict)}
def _ledger_path(path: Path | None) -> Path:
"""Resolve the ledger path at call time, so a patched module global applies.
A default argument would bind the real file at import time and the test
suite's redirect (``tests/_isolated_state.py``) would silently miss it.
"""
return SYNC_TOMBSTONES_FILE if path is None else path
def add_tombstone(
record_id: str,
device_id: str,
reason: str,
path: Path | None = None,
) -> bool:
"""Record *record_id* as deleted. Returns False if it already was."""
path = _ledger_path(path)
ledger = _load(path)
if record_id in ledger:
return False
ledger[record_id] = {
"deleted_hlc": Hlc.new_tick(device_id).to_str(),
"reason": reason,
"tombstoned_at": datetime.now(tz=UTC).isoformat(),
}
path.write_text(json.dumps(ledger, indent=2, sort_keys=True) + "\n")
return True
def tombstone_records(path: Path | None = None) -> dict[str, Record]:
"""Return every ledgered tombstone as a crdt_sync :class:`Record`.
Entries without a parsable ``deleted_hlc`` are skipped with a warning
rather than pushed clockless: a tombstone with no HLC still deletes, but
it cannot be ordered against a later un-delete on another device.
"""
records: dict[str, Record] = {}
for record_id, entry in _load(_ledger_path(path)).items():
hlc_str = entry.get("deleted_hlc")
try:
hlc = Hlc.from_str(str(hlc_str))
except (ValueError, TypeError) as exc:
_logger.warning(
"Sync tombstone %s has no usable deleted_hlc (%r: %s) — not pushed",
record_id,
hlc_str,
exc,
)
continue
records[record_id] = Record(
id=record_id, fields={}, deleted=True, deleted_hlc=hlc
)
return records

View File

@ -32,6 +32,15 @@ ISOLATED_STATE: tuple[tuple[str, tuple[str, ...]], ...] = (
"_status.EXTRA_BENEFITS_FILE",
),
),
# Pushed to the shared sync store on every tick; a test that wrote here
# would tombstone a real workout on the phone.
(
"sync_tombstones.json",
(
"_constants.SYNC_TOMBSTONES_FILE",
"_sync_tombstones.SYNC_TOMBSTONES_FILE",
),
),
(
"sick_day_state.json",
(

View File

@ -0,0 +1,149 @@
"""Tests for the durable sync-tombstone ledger and its place in every push.
Guards the 2026-09-13 finding: a tombstone written once to the PC's device log
was gone by the next tick, because ``sync_log`` never reads this device's own
remote log and ``_manual_push`` re-derives it from ``log.json`` every time.
"""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from crdt_sync import Hlc, Record
from screen_locker import _sync_tombstones
from screen_locker._manual_push import records_from_workout_log
from screen_locker._sync_tombstones import add_tombstone, tombstone_records
if TYPE_CHECKING:
from pathlib import Path
_DEVICE = "57582b3b-01c6-45cc-9674-ad2b95bebf29"
_RID = "manual:2026-09-13T14:30"
_MANUAL = {"type": "manual_workout", "source": "football 11v11", "start_time": "14:30"}
class TestAddTombstone:
"""The ledger is written once per id, with a clock minted at that moment."""
def test_creates_the_ledger_with_hlc_reason_and_time(self, tmp_path: Path) -> None:
path = tmp_path / "sync_tombstones.json"
assert add_tombstone(_RID, _DEVICE, "duplicate", path) is True
entry = json.loads(path.read_text())[_RID]
assert Hlc.from_str(entry["deleted_hlc"]).node_id == _DEVICE
assert entry["reason"] == "duplicate"
assert entry["tombstoned_at"].startswith("20")
def test_second_add_is_a_no_op_and_keeps_the_original_clock(
self, tmp_path: Path
) -> None:
path = tmp_path / "sync_tombstones.json"
add_tombstone(_RID, _DEVICE, "first", path)
before = path.read_text()
assert add_tombstone(_RID, _DEVICE, "second", path) is False
assert path.read_text() == before
def test_adds_alongside_existing_ids(self, tmp_path: Path) -> None:
path = tmp_path / "sync_tombstones.json"
add_tombstone(_RID, _DEVICE, "a", path)
add_tombstone("manual:2026-01-01T08:00", _DEVICE, "b", path)
assert set(json.loads(path.read_text())) == {_RID, "manual:2026-01-01T08:00"}
class TestTombstoneRecords:
"""Ledger → crdt_sync Records, loud about anything it cannot push."""
def test_missing_ledger_is_empty(self, tmp_path: Path) -> None:
assert tombstone_records(tmp_path / "absent.json") == {}
def test_ledgered_id_becomes_a_deleted_record(self, tmp_path: Path) -> None:
path = tmp_path / "sync_tombstones.json"
add_tombstone(_RID, _DEVICE, "duplicate", path)
record = tombstone_records(path)[_RID]
assert record == Record(
id=_RID,
fields={},
deleted=True,
deleted_hlc=Hlc.from_str(json.loads(path.read_text())[_RID]["deleted_hlc"]),
)
def test_same_clock_on_every_read(self, tmp_path: Path) -> None:
"""Re-pushing must not churn the store: the HLC is stored, not re-minted."""
path = tmp_path / "sync_tombstones.json"
add_tombstone(_RID, _DEVICE, "duplicate", path)
assert tombstone_records(path) == tombstone_records(path)
def test_corrupt_ledger_pushes_nothing_and_warns(
self, tmp_path: Path, caplog
) -> None:
path = tmp_path / "sync_tombstones.json"
path.write_text("{not json")
assert tombstone_records(path) == {}
assert "unreadable" in caplog.text
def test_non_object_ledger_is_ignored_and_warns(
self, tmp_path: Path, caplog
) -> None:
path = tmp_path / "sync_tombstones.json"
path.write_text("[]")
assert tombstone_records(path) == {}
assert "not a JSON object" in caplog.text
def test_non_dict_entries_are_dropped(self, tmp_path: Path) -> None:
path = tmp_path / "sync_tombstones.json"
path.write_text(json.dumps({_RID: "garbage"}))
assert tombstone_records(path) == {}
def test_entry_without_usable_hlc_is_skipped_and_warns(
self, tmp_path: Path, caplog
) -> None:
path = tmp_path / "sync_tombstones.json"
path.write_text(json.dumps({_RID: {"reason": "x"}}))
assert tombstone_records(path) == {}
assert "no usable deleted_hlc" in caplog.text
class TestPushCarriesTombstones:
"""records_from_workout_log replaces the live copy with the tombstone."""
def _log(self, tmp_path: Path) -> Path:
log_file = tmp_path / "log.json"
log_file.write_text(
json.dumps(
{
"2026-09-13": [
{
"timestamp": "2026-09-13T07:40:06+00:00",
"workout_data": _MANUAL,
"workout_id": _RID,
}
]
}
)
)
return log_file
def test_live_entry_is_pushed_when_not_ledgered(self, tmp_path: Path) -> None:
log = records_from_workout_log(self._log(tmp_path))
assert log[_RID].deleted is False
def test_ledgered_entry_is_pushed_as_a_tombstone(self, tmp_path: Path) -> None:
"""The isolated SYNC_TOMBSTONES_FILE (conftest) is what the push reads."""
add_tombstone(_RID, _DEVICE, "duplicate", _sync_tombstones.SYNC_TOMBSTONES_FILE)
log = records_from_workout_log(self._log(tmp_path))
assert log[_RID].deleted is True
assert log[_RID].fields == {}
def test_tombstone_for_an_id_not_in_the_log_is_still_pushed(
self, tmp_path: Path
) -> None:
add_tombstone(
"manual:2026-01-01T08:00",
_DEVICE,
"x",
_sync_tombstones.SYNC_TOMBSTONES_FILE,
)
log = records_from_workout_log(self._log(tmp_path))
assert log["manual:2026-01-01T08:00"].deleted is True
assert log[_RID].deleted is False

View File

@ -19,7 +19,15 @@ echo "Running flutter test --coverage ..."
# git to identify its own SDK. With it set, flutter reads THIS repository as
# the SDK -- reporting our HEAD as the framework revision -- and pub then
# resolves every version constraint against "0.0.0-unknown" and fails.
env -u GIT_DIR -u GIT_WORK_TREE -u GIT_INDEX_FILE flutter test --coverage
# FLUTTER_TEST_CONCURRENCY: one test isolate per core is the default and peaks
# well over 4 GiB on this suite, which the 4 GiB resource cap (capped.sh)
# OOM-kills. Set it to 1-2 when running under the cap; unset keeps the default.
concurrency=()
if [[ -n "${FLUTTER_TEST_CONCURRENCY:-}" ]]; then
concurrency=(--concurrency "$FLUTTER_TEST_CONCURRENCY")
fi
env -u GIT_DIR -u GIT_WORK_TREE -u GIT_INDEX_FILE \
flutter test --coverage "${concurrency[@]}"
cd - > /dev/null

138
scripts/tombstone_sync_record.py Executable file
View File

@ -0,0 +1,138 @@
#!/usr/bin/env python3
"""Tombstone one workout record in the shared sync store, durably.
Deletion in crdt_sync is monotonic: once a device log carries ``deleted=True``
for an id, every merge keeps it deleted. But ``sync_log`` pulls only the OTHER
devices' logs and ``_manual_push`` re-derives the PC's log from ``log.json``
every tick, so a tombstone written once to the PC's device log is gone by the
next push (seen 2026-09-13: "tombstoned", then "LIVE" five seconds later).
So this records the id in ``screen_locker/sync_tombstones.json``
(``_sync_tombstones``), which every push carries, then runs one sync tick and
reports what the store holds afterwards.
Written for ``manual:2026-09-13T14:30``: a synced copy of a football already
on disk, filed under a second id by that morning's day-key repair. It shares
the original's credit (``_weekly_check.credit_key``) and stays in the signed
log -- this repo annotates, never deletes -- but its sync record made every
15-minute tick log "budget exhausted -- not ingested".
Dry-run by default: pulls the store and reports whether the id is live.
Rerunnable: an id already in the ledger is left as it is.
Usage:
python3 scripts/tombstone_sync_record.py manual:2026-09-13T14:30
python3 scripts/tombstone_sync_record.py manual:2026-09-13T14:30 --apply \
--reason "synced duplicate of manual:2026-09-12T14:30"
"""
from __future__ import annotations
import argparse
import logging
from pathlib import Path
import sys
from crdt_sync import (
FileSyncStateStore,
GitHubSyncClient,
LogCodec,
Record,
RevisionTracking,
SyncTarget,
sync_log,
)
from screen_locker._constants import (
SYNC_REPO_NAME,
SYNC_REPO_OWNER,
SYNC_STATE_FILE,
SYNC_TIMEOUT_SECONDS,
)
from screen_locker._device import device_identity
from screen_locker._manual_push import (
_decode_log,
_encode_log,
records_from_workout_log,
)
from screen_locker._sync_tombstones import add_tombstone
from screen_locker._workout_sync import _DEVICES_PREFIX, read_sync_token, remote_client
_logger = logging.getLogger(__name__)
# The same path ScreenLocker resolves at runtime (screen_lock.py), as the
# sibling scripts do; there is no package constant for it.
LOG_FILE = Path(__file__).resolve().parent.parent / "screen_locker" / "log.json"
def _report(message: str) -> None:
"""Write one line to stdout (matches the other scripts in this directory)."""
sys.stdout.write(f"{message}\n")
def _sync(local_log: dict[str, Record]) -> dict[str, Record]:
"""Run one sync tick with *local_log* as this device's view; return the merge."""
identity = device_identity()
token = read_sync_token()
if token is None:
msg = "no sync token — cannot reach the store"
raise SystemExit(msg)
client = remote_client(
GitHubSyncClient(
SYNC_REPO_OWNER, SYNC_REPO_NAME, token, timeout_seconds=SYNC_TIMEOUT_SECONDS
)
)
return sync_log(
SyncTarget(
client=client,
device_id=identity.device_id,
legacy_device_id=identity.legacy_id,
path_prefix=_DEVICES_PREFIX,
),
local_log,
LogCodec(decode=_decode_log, encode=_encode_log),
RevisionTracking(state_store=FileSyncStateStore(SYNC_STATE_FILE)),
)
def main() -> int:
"""Entry point."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"record_id", help="sync record id, e.g. manual:2026-09-13T14:30"
)
parser.add_argument("--apply", action="store_true", help="write the tombstone")
parser.add_argument("--reason", default="", help="why (kept in the ledger)")
args = parser.parse_args()
logging.basicConfig(
level=logging.WARNING, format="%(levelname)s %(name)s: %(message)s"
)
if args.apply:
if not args.reason:
parser.error("--apply needs --reason so the ledger says why")
if add_tombstone(args.record_id, device_identity().device_id, args.reason):
_report(f"{args.record_id}: added to the tombstone ledger")
else:
_report(f"{args.record_id}: already in the tombstone ledger")
# Exactly what _manual_push pushes on a tick: log.json plus the ledger.
local_log = records_from_workout_log(LOG_FILE)
merged = _sync(local_log)
record = merged.get(args.record_id)
if record is None:
_report(
f"{args.record_id}: not in the store on any device — nothing to tombstone"
)
return 1
if record.deleted:
verb = "tombstoned" if args.apply else "already tombstoned"
_report(f"{args.record_id}: {verb} (deleted_hlc={record.deleted_hlc})")
return 0
_report(
f"{args.record_id}: LIVE in the store — re-run with --apply to tombstone it"
)
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@ -9,7 +9,7 @@ High (max 2 features):
adds breaks between REPS (3 minutes if REP succeeded (as in all reps were done) and 5 minutes if it failed) <-- currently app ads breaks between SETS which wrong
STILL OPEN (2026-08-09): breaks are still per-SET, and suppressed on the last set of an exercise. Needs a decision — "break between reps" would mean pausing mid-set, which is unusual; confirm intent before building.
After break time (after REPS) is over app should play a sound and vibrate the phone and generally point the user attention towards the app
DONE (verified 2026-08-09): break end plays assets/sounds/break_end.mp3 and vibrates 800ms. Caveat: only while the app is foregrounded — Dart timers suspend in the background, which needs a native foreground service (deferred).
DONE (verified 2026-09-12, on-device, screen off and locked): break end plays assets/sounds/break_end.mp3 and vibrates 800ms, AND the OS rings the break_end_v1 channel from res/raw. The old "only while foregrounded" caveat is gone: a flutter_foreground_task service holds a wake lock and owns the deadline, and the countdown is now derived from a stored end time instead of a tick counter that stalled whenever Android throttled the isolate.
Mid (max 3 features):
change warmup exercises weight from 2/3 to 3/4 of target weight
@ -21,6 +21,7 @@ Low (max 4 features):
If set is finished user cannot modify reps on this set for some reason -> this is a bug user should ALWAYS be able to modify ANY reps in ANY exercise
shows history of workouts and a graph for showing progress
The app should be capable of working in the background without any problem and display status notifications allowing user to click on "done rep" from the status bar
DONE (2026-09-12): a foreground service runs for the whole workout and shows an ongoing notification — "Workout A · break 1:47" / "Next: Dumbbell Lunge — set 2/5 / 12 reps @ 10 kg" — with three action buttons: ✓ Done (records the set at full target reps), − 1 rep (decrements the set recorded last, which also stretches a 3-min rest to 5), Skip break. Presses go into a durable SharedPreferences queue and are applied through the same _tapCircle/_skipBreak the on-screen buttons use, so a press made while the app is dead still lands on the next launch. Verified on-device with the screen off and locked; the button PRESSES themselves still want a human tap to confirm end-to-end (the plugin's receiver is NOT_EXPORTED, so adb cannot fire them).
automatically decreases weight if user had a break from using the app <-- not sure if implemented (maybe implemented but did not have a change to check it add fallback manual setting of weights by user)

View File

@ -5,15 +5,15 @@ Implementing design_v2.md improvements.
## Key Decisions
- Active session persisted to SQLite on every tap so force-kill is safe
- PopScope removed — back button returns to home, workout continues in DB
- Back button: PopScope is still present and pins the route in lock mode
(workout_screen.dart) — the older "PopScope removed" note here was wrong
- Auto-resume: HomeScreen auto-navigates to workout on first load if session exists
## Deferred / Not Yet Implemented
- **Background notifications + break sound when phone is sleeping**: Dart timers
suspend when app is backgrounded. Needs a native Android foreground service
(e.g. `flutter_foreground_task` or custom Kotlin service) to keep the break
countdown running and fire the alert even when the screen is off.
File as a separate task before marking the app "done."
- Break timing is wall-clock (`BreakClock`), never a tick counter: Android
throttles and Doze suspends timers in a backgrounded isolate
- A `flutter_foreground_task` service owns the deadline for the whole
workout and shows the status-bar notification; notification presses go
through a durable prefs queue, never straight into sqflite (the CRDT
sync layer owns that database's ordering)
## Next Steps
- Clarify user intent on "no break between sets" (contradicts design_v2.md which

View File

@ -29,6 +29,12 @@ android {
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
// Required by flutter_local_notifications 22.x, which uses java.time
// APIs that only exist from API 26. minSdk here is 24, so they have to
// be backported. The plugin's README says to enable this even when the
// app schedules no notifications -- we don't, and it is still needed:
// without it the Android build fails outright.
isCoreLibraryDesugaringEnabled = true
}
defaultConfig {
@ -72,3 +78,8 @@ kotlin {
flutter {
source = "../.."
}
dependencies {
// Backports java.time for minSdk 24; see isCoreLibraryDesugaringEnabled.
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.5")
}

View File

@ -10,6 +10,26 @@
<uses-permission android:name="android.permission.VIBRATE" />
<!-- Required to bind a server socket for the HTTP fallback sync endpoint -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Android 13+ runtime opt-in. Requested when a workout starts, not at
launch: that is the moment the service is about to be created, so the
prompt has obvious context. A denial is surfaced in the UI, never
swallowed: without it the foreground service still runs but shows
nothing, which looks exactly like the bug this feature fixes. -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- The rest-period deadline has to keep ticking while the phone is in a
pocket. A Dart timer in the UI isolate cannot: Android throttles it and
Doze suspends it outright. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission
android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<!-- Required by ForegroundTaskOptions(allowWakeLock: true), which takes a
PARTIAL_WAKE_LOCK so the deadline fires with the screen off. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Makes the battery-optimisation opt-out show the system dialog instead
of returning denied. HyperOS kills background services hard; see the
OEM notes in the workout app README. -->
<uses-permission
android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<application
android:label="workout_app"
android:name="${applicationName}"
@ -36,6 +56,21 @@
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- android:stopWithTask="false" is LOAD-BEARING, not boilerplate: it
is what keeps the break timer alive after the app is swiped out of
recents mid-workout, which is the whole point of the service. Do
not "tidy" it away.
foregroundServiceType="dataSync" rather than "health": health
additionally demands a runtime ACTIVITY_RECOGNITION/BODY_SENSORS
grant on Android 14+, and specialUse needs a Play-review
justification property. Neither buys anything for a sideloaded
personal app, and dataSync's 6h/24h budget dwarfs a workout. -->
<service
android:name="com.pravera.flutter_foreground_task.service.ForegroundService"
android:foregroundServiceType="dataSync"
android:exported="false"
android:stopWithTask="false" />
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data

View File

@ -2,9 +2,12 @@
import 'dart:async';
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/screens/home_screen.dart';
import 'package:workout_app/services/backup_service.dart';
import 'package:workout_app/services/break_service_controller.dart';
import 'package:workout_app/services/foreground_break_client_flutter.dart';
import 'package:workout_app/services/http_server_service.dart';
import 'package:workout_app/services/lock_mode.dart';
import 'package:workout_app/services/progression_sync_service.dart';
@ -18,6 +21,11 @@ import 'package:workout_app/ui/theme.dart';
// up are unit-tested individually; the entry point itself is not.
void main(List<String> args) async {
WidgetsFlutterBinding.ensureInitialized();
// The UI end of the channel the break foreground service talks back on.
// Must precede runApp, and must happen even on Linux: the call is a no-op
// where there is no service, and skipping it would mean the workout screen
// silently never hears a notification button press.
FlutterForegroundTask.initCommunicationPort();
// Must precede runApp: the UI reads this to decide whether to offer
// any way out of the workout.
lockModeEnabled = parseLockMode(args);
@ -50,6 +58,13 @@ void main(List<String> args) async {
);
}
await StorageService.init();
// Before the UI exists: a service left over from a crashed or force-stopped
// workout must not sit in the status bar counting down nothing.
await stopStaleBreakService(
FlutterForegroundBreakClient(),
hasActiveWorkout: () async =>
await StorageService.instance.loadActiveSession() != null,
);
await StorageService.instance.restoreFromBackupIfNeeded();
// The permission-free restore path, and the reason storage is now optional.
// `backup.json` is unreadable without the grant, so on a denied reinstall the

View File

@ -0,0 +1,104 @@
/// A workout action the user triggered from the status-bar notification.
library;
import 'dart:convert';
import 'dart:developer';
/// The three things a notification button can ask the workout screen to do.
enum BreakIntentKind {
/// Record the target set as completed at its full target reps.
done,
/// Knock one rep off an already-recorded set.
minusRep,
/// End the running rest period early.
skipBreak;
/// Parses [name] back into a kind, or null when it is not one of these.
static BreakIntentKind? tryParse(String name) {
for (final kind in BreakIntentKind.values) {
if (kind.name == name) return kind;
}
return null;
}
}
/// One durable, self-describing button press.
///
/// Self-describing matters: the foreground service resolves which set a press
/// refers to *at press time* and writes those indices down. Re-deriving "the
/// most recent set" when the queue is drained would resolve against state the
/// user never saw, which is how a decrement lands on the wrong set.
class BreakIntent {
/// Creates an intent.
const BreakIntent({
required this.seq,
required this.kind,
required this.exIdx,
required this.setIdx,
required this.tsMs,
});
/// Rebuilds an intent from [json], or returns null if it is not one.
///
/// Total rather than throwing: a malformed entry must never wedge the drain
/// loop, and the caller logs each rejection with its raw text.
static BreakIntent? tryDecode(String json) {
final Object? decoded;
try {
decoded = jsonDecode(json);
} on FormatException catch (error) {
log(
'BreakIntent: a queued notification press is unreadable and will be '
'skipped — the press is lost. $error. Raw text: $json',
level: 900,
);
return null;
}
if (decoded is! Map<String, dynamic>) return null;
final seq = decoded['seq'];
final kindName = decoded['kind'];
final exIdx = decoded['exIdx'];
final setIdx = decoded['setIdx'];
final tsMs = decoded['tsMs'];
if (seq is! int || kindName is! String || exIdx is! int) return null;
if (setIdx is! int || tsMs is! int) return null;
final kind = BreakIntentKind.tryParse(kindName);
if (kind == null) return null;
return BreakIntent(
seq: seq,
kind: kind,
exIdx: exIdx,
setIdx: setIdx,
tsMs: tsMs,
);
}
/// Monotonic sequence number, allocated by the service isolate.
final int seq;
/// What the user asked for.
final BreakIntentKind kind;
/// Exercise this press referred to, or -1 when it referred to no set.
final int exIdx;
/// Set this press referred to, or -1 when it referred to no set.
final int setIdx;
/// When the button was pressed, epoch milliseconds.
final int tsMs;
/// Serializes this intent for the durable queue.
String encode() => jsonEncode({
'seq': seq,
'kind': kind.name,
'exIdx': exIdx,
'setIdx': setIdx,
'tsMs': tsMs,
});
@override
String toString() => 'BreakIntent(#$seq ${kind.name} [$exIdx][$setIdx])';
}

View File

@ -0,0 +1,191 @@
/// What the foreground service needs to know about the running workout.
library;
import 'package:flutter/foundation.dart';
/// A complete picture of the workout, as the notification should show it.
///
/// Always sent whole, never as a delta. Android can restart the service isolate
/// independently of the UI, and a restarted isolate has no history to apply a
/// delta to — so the UI pushes the entire picture on every change instead.
@immutable
class BreakSnapshot {
/// Creates a snapshot.
const BreakSnapshot({
required this.workoutType,
required this.breakEndMs,
required this.breakDurationSecs,
required this.breakLabel,
required this.breakForExIdx,
required this.breakForSetIdx,
required this.nextExIdx,
required this.nextSetIdx,
required this.nextExName,
required this.nextSetNumber,
required this.nextTotalSets,
required this.nextReps,
required this.nextWeight,
required this.lastExIdx,
required this.lastSetIdx,
required this.setsRemaining,
this.finished = false,
});
/// Rebuilds a snapshot from the map sent across the isolate boundary.
///
/// Returns null rather than throwing: the payload crosses a platform channel,
/// and a malformed one must leave the notification as it was instead of
/// taking down the service isolate.
static BreakSnapshot? tryFromMap(Map<Object?, Object?> map) {
int? i(String k) => map[k] is int ? map[k]! as int : null;
final workoutType = map['workoutType'];
if (workoutType is! String) return null;
final nextExName = map['nextExName'];
if (nextExName is! String) return null;
final breakLabel = map['breakLabel'];
if (breakLabel is! String) return null;
final weight = map['nextWeight'];
if (weight is! num) return null;
final keys = [
'breakEndMs',
'breakDurationSecs',
'breakForExIdx',
'breakForSetIdx',
'nextExIdx',
'nextSetIdx',
'nextSetNumber',
'nextTotalSets',
'nextReps',
'lastExIdx',
'lastSetIdx',
'setsRemaining',
];
for (final k in keys) {
if (i(k) == null) return null;
}
return BreakSnapshot(
workoutType: workoutType,
breakEndMs: i('breakEndMs')!,
breakDurationSecs: i('breakDurationSecs')!,
breakLabel: breakLabel,
breakForExIdx: i('breakForExIdx')!,
breakForSetIdx: i('breakForSetIdx')!,
nextExIdx: i('nextExIdx')!,
nextSetIdx: i('nextSetIdx')!,
nextExName: nextExName,
nextSetNumber: i('nextSetNumber')!,
nextTotalSets: i('nextTotalSets')!,
nextReps: i('nextReps')!,
nextWeight: weight.toDouble(),
lastExIdx: i('lastExIdx')!,
lastSetIdx: i('lastSetIdx')!,
setsRemaining: i('setsRemaining')!,
finished: map['finished'] == true,
);
}
/// 'A' or 'B'.
final String workoutType;
/// Wall-clock deadline of the running rest, or 0 when none is running.
final int breakEndMs;
/// Full length of the running rest, for the countdown's denominator.
final int breakDurationSecs;
/// Human label of the running rest, e.g. 'Rest (3 min — well done!)'.
final String breakLabel;
/// Exercise the running rest belongs to, or -1.
final int breakForExIdx;
/// Set the running rest belongs to; -1 means a warmup rest.
final int breakForSetIdx;
/// Exercise the `Done` button would record, or -1 when the workout is over.
final int nextExIdx;
/// Set the `Done` button would record, or -1 when the workout is over.
final int nextSetIdx;
/// Display name of the next exercise.
final String nextExName;
/// 1-based number of the next set, for 'set 3/5'.
final int nextSetNumber;
/// How many sets that exercise has, for 'set 3/5'.
final int nextTotalSets;
/// Target reps of the next set.
final int nextReps;
/// Working weight of the next set, in kg.
final double nextWeight;
/// Exercise the `− 1 rep` button would decrement, or -1.
final int lastExIdx;
/// Set the `− 1 rep` button would decrement, or -1.
final int lastSetIdx;
/// Sets still untapped across the whole workout.
final int setsRemaining;
/// True once the workout has been finished and saved.
final bool finished;
/// True while a rest period is recorded as running.
bool get hasBreak => breakEndMs > 0;
/// True when there is a set left for `Done` to record.
bool get hasNextSet => nextExIdx >= 0 && nextSetIdx >= 0;
/// Flattens this snapshot for `sendDataToTask`, which takes primitives only.
Map<String, Object?> toMap() => {
'workoutType': workoutType,
'breakEndMs': breakEndMs,
'breakDurationSecs': breakDurationSecs,
'breakLabel': breakLabel,
'breakForExIdx': breakForExIdx,
'breakForSetIdx': breakForSetIdx,
'nextExIdx': nextExIdx,
'nextSetIdx': nextSetIdx,
'nextExName': nextExName,
'nextSetNumber': nextSetNumber,
'nextTotalSets': nextTotalSets,
'nextReps': nextReps,
'nextWeight': nextWeight,
'lastExIdx': lastExIdx,
'lastSetIdx': lastSetIdx,
'setsRemaining': setsRemaining,
'finished': finished,
};
/// Returns a copy with the listed fields replaced.
BreakSnapshot copyWith({
int? breakEndMs,
int? breakDurationSecs,
String? breakLabel,
int? setsRemaining,
bool? finished,
}) => BreakSnapshot(
workoutType: workoutType,
breakEndMs: breakEndMs ?? this.breakEndMs,
breakDurationSecs: breakDurationSecs ?? this.breakDurationSecs,
breakLabel: breakLabel ?? this.breakLabel,
breakForExIdx: breakForExIdx,
breakForSetIdx: breakForSetIdx,
nextExIdx: nextExIdx,
nextSetIdx: nextSetIdx,
nextExName: nextExName,
nextSetNumber: nextSetNumber,
nextTotalSets: nextTotalSets,
nextReps: nextReps,
nextWeight: nextWeight,
lastExIdx: lastExIdx,
lastSetIdx: lastSetIdx,
setsRemaining: setsRemaining ?? this.setsRemaining,
finished: finished ?? this.finished,
);
}

View File

@ -7,10 +7,18 @@ import 'dart:developer';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:vibration/vibration.dart';
import 'package:workout_app/models/break_intent.dart';
import 'package:workout_app/models/break_snapshot.dart';
import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/models/exercise_result.dart';
import 'package:workout_app/models/set_result.dart';
import 'package:workout_app/models/workout_session.dart';
import 'package:workout_app/services/break_clock.dart';
import 'package:workout_app/services/break_intent_queue.dart';
import 'package:workout_app/services/break_intent_store.dart';
import 'package:workout_app/services/break_service_controller.dart';
import 'package:workout_app/services/foreground_break_client.dart';
import 'package:workout_app/services/foreground_break_client_flutter.dart';
import 'package:workout_app/services/lock_mode.dart';
import 'package:workout_app/services/progression_sync_service.dart';
import 'package:workout_app/services/storage_service.dart';
@ -26,12 +34,19 @@ part 'workout_screen_body.dart';
part 'workout_screen_breaks.dart';
part 'workout_screen_dialogs.dart';
part 'workout_screen_finish.dart';
part 'workout_screen_intents.dart';
part 'workout_screen_session.dart';
part 'workout_screen_taps.dart';
const _successBreakSecs = 180; // 3 min after successful set
const _failBreakSecs = 300; // 5 min after failed set
const _warmupBreakSecs = 180; // 3 min after warmup
// How late a restored break's end cue may still be played. Long enough to
// cover the app being killed and reopened mid-rest; short enough that
// resuming yesterday's session does not blast the sound across the gym.
const _expiredBreakGraceSecs = 120;
/// Screen that drives an active workout session with per-rep tracking.
class WorkoutScreen extends StatefulWidget {
/// Creates a [WorkoutScreen].
@ -40,6 +55,7 @@ class WorkoutScreen extends StatefulWidget {
required this.exercises,
super.key,
this.savedState,
this.breakClient,
});
/// 'A' or 'B' — used for history and progression.
@ -51,6 +67,11 @@ class WorkoutScreen extends StatefulWidget {
/// Serialized state to restore (crash-recovery); null for a fresh session.
final Map<String, dynamic>? savedState;
/// Foreground-service client, injectable so tests can drive the notification
/// path on a host that has no foreground service. Null means the real one.
@visibleForTesting
final ForegroundBreakClient? breakClient;
@override
State<WorkoutScreen> createState() => _WorkoutScreenState();
}
@ -65,17 +86,27 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
Map<String, ExerciseState> _exerciseStates = {};
// Break state
int _breakRemaining = 0;
int _breakDurationSecs = 0;
DateTime? _breakStartTime;
// Break state. The deadline is the source of truth: `_breakClock` is what
// survives the app being backgrounded, and everything else is derived from
// it. See services/break_clock.dart for why a tick counter could not be.
BreakClock? _breakClock;
Timer? _breakTimer;
String _breakLabel = '';
int _breakForExIdx = -1;
int _breakForSetIdx = -1; // -1 = warmup break
/// A break restored as already-expired, awaiting its cue after first frame.
BreakClock? _expiredBreak;
int get _breakRemaining =>
_breakClock?.remainingSecsAt(DateTime.now()) ?? 0;
int get _breakDurationSecs => _breakClock?.durationSecs ?? 0;
bool get _inBreak => _breakRemaining > 0;
late final AppLifecycleListener _lifecycle;
late final BreakServiceController _breaks;
final _audio = AudioPlayer();
final _sync = SyncService();
bool _finished = false;
@ -92,7 +123,19 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
_elapsedTimer = Timer.periodic(const Duration(seconds: 1), (_) {
setState(() => _elapsed = DateTime.now().difference(_startTime));
});
// Coming back to the foreground is the one moment the countdown is
// guaranteed to be stale: ticks stop while the app is away, and the clock
// has to be re-read before the user sees a frame.
_lifecycle = AppLifecycleListener(onResume: _onResumed);
_breaks = BreakServiceController(
widget.breakClient ?? FlutterForegroundBreakClient(),
BreakIntentQueue(PrefsBreakIntentStore()),
);
unawaited(_loadExerciseStates());
WidgetsBinding.instance.addPostFrameCallback((_) {
unawaited(_settleExpiredBreak());
unawaited(_startBreakService());
});
}
void _initFresh() {
@ -121,6 +164,13 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
void dispose() {
_elapsedTimer.cancel();
_breakTimer?.cancel();
_lifecycle.dispose();
// Deliberately NOT stopping the break service here. The back button pops
// this screen while the workout carries on in the database, and stopping
// the service on dispose killed the countdown and the notification with
// it -- silently putting the user back on the bug this feature fixes.
// The service is stopped only by Finish, by Reset, and by the stale-service
// reaper in main() for the case where neither ever happens.
unawaited(_audio.dispose());
super.dispose();
}
@ -135,61 +185,12 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
bool get _allSetsCompleted => _tapped.every((row) => row.every((t) => t));
// ── Interaction ────────────────────────────────────────────────────────────
void _tapCircle(int exIdx, int setIdx) {
if (_finished) return;
final wasNotTapped = !_tapped[exIdx][setIdx];
if (wasNotTapped && _inBreak) return;
setState(() {
if (wasNotTapped) {
_tapped[exIdx][setIdx] = true;
} else {
_doneReps[exIdx][setIdx] = (_doneReps[exIdx][setIdx] - 1).clamp(0, 999);
_recomputeBreakIfNeeded(exIdx, setIdx);
}
});
if (wasNotTapped) {
final rest = _restAfterSet(exIdx, setIdx);
if (rest != null) {
_startBreak(rest.seconds, rest.label, exIdx, setIdx);
}
}
// Only a newly-completed set moves the workout forward; a rep decrement
// re-enters here and must not cost a remote write.
unawaited(_saveActiveSession(toFirebase: wasNotTapped));
}
void _tapWarmup(int exIdx) {
if (_finished || _warmupTapped[exIdx]) return;
setState(() => _warmupTapped[exIdx] = true);
if (!_inBreak) {
_startBreak(_warmupBreakSecs, 'Warmup rest (3 min)', exIdx, -1);
}
unawaited(_saveActiveSession(toFirebase: true));
}
void _resetCircle(int exIdx, int setIdx) {
if (_finished) return;
setState(() {
_tapped[exIdx][setIdx] = false;
_doneReps[exIdx][setIdx] = widget.exercises[exIdx].reps;
});
if (_breakForExIdx == exIdx && _breakForSetIdx == setIdx) {
_cancelBreak();
}
unawaited(_saveActiveSession());
}
/// Runs [fn] inside `setState` on behalf of the break/threshold extensions.
/// Runs [fn] inside `setState` on behalf of this library's extensions.
///
/// `setState` is `@protected`, so an extension cannot call it directly. This
/// shim is the one seam through which `workout_screen_breaks.dart` mutates
/// state; keeping it named makes those writes greppable from here.
/// shim is the one seam through which `workout_screen_breaks.dart` and
/// `workout_screen_taps.dart` mutate state; keeping it named makes those
/// writes greppable from here.
void _applyBreakState(VoidCallback fn) => setState(fn);
// ── Finish / Reset ─────────────────────────────────────────────────────────
@ -201,6 +202,9 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
Future<void> _finishWorkout() async {
_elapsedTimer.cancel();
_breakTimer?.cancel();
// Before the state flips: the service must not outlive the workout, and
// with stopWithTask="false" nothing else will ever stop it.
await _breaks.stop();
setState(() => _finished = true);
await _persistFinishedWorkout();
}

View File

@ -10,40 +10,56 @@ extension _WorkoutScreenBreaks on _WorkoutScreenState {
void _startBreak(int secs, String label, int exIdx, int setIdx) {
_breakTimer?.cancel();
_applyBreakState(() {
_breakDurationSecs = secs;
_breakRemaining = secs;
_breakClock = BreakClock.startingAt(DateTime.now(), secs);
_breakLabel = label;
_breakForExIdx = exIdx;
_breakForSetIdx = setIdx;
_breakStartTime = DateTime.now();
});
_breakTimer = Timer.periodic(const Duration(seconds: 1), _tickBreak);
}
void _tickBreak(Timer t) {
_applyBreakState(() => _breakRemaining--);
if (_breakRemaining <= 0) {
t.cancel();
/// The once-a-second tick.
void _tickBreak(Timer t) => _refreshBreak();
/// Re-reads the deadline after the app was away, and drains any press made
/// from the notification while it was.
void _onResumed() {
unawaited(_drainIntents());
_refreshBreak();
}
/// Re-renders the countdown from the deadline, and ends the rest once past.
///
/// Deliberately not a decrement: ticks are throttled, and in Doze dropped
/// entirely, once the app is backgrounded — so counting them loses time.
/// Reading the clock instead means a timer that stalled for ten minutes
/// fires the cue on its very next tick rather than never.
void _refreshBreak() {
final clock = _breakClock;
if (clock == null) return;
if (clock.expiredAt(DateTime.now())) {
_breakTimer?.cancel();
unawaited(_onBreakFinished());
} else {
_applyBreakState(() {});
}
}
void _cancelBreak() {
_breakTimer?.cancel();
_applyBreakState(() {
_breakRemaining = 0;
_breakClock = null;
_breakForExIdx = -1;
_breakForSetIdx = -1;
_breakStartTime = null;
});
}
Future<void> _onBreakFinished() async {
await _playBreakEndCue();
_applyBreakState(() {
_breakClock = null;
_breakForExIdx = -1;
_breakForSetIdx = -1;
_breakStartTime = null;
});
unawaited(_saveActiveSession());
}

View File

@ -66,6 +66,10 @@ extension _WorkoutScreenDialogs on _WorkoutScreenState {
),
);
if (ok == true) {
// The service outlives the screen by design (stopWithTask="false"), so
// abandoning a workout has to take it down explicitly -- otherwise the
// notification sits there counting down a workout that no longer exists.
await _breaks.stop();
await StorageService.instance.clearActiveSession();
if (mounted) Navigator.of(context).pop();
}

View File

@ -0,0 +1,168 @@
// Applying notification button presses, and describing the workout for the
// foreground service.
//
// A `part` for the same reason as workout_screen_session.dart: the extension
// reaches private `_WorkoutScreenState` fields, and mutations go through the
// `_applyBreakState` shim because `setState` is `@protected`.
part of 'workout_screen.dart';
/// The bridge between the status-bar notification and the workout state.
extension _WorkoutScreenIntents on _WorkoutScreenState {
/// Describes the workout exactly as the notification should show it.
BreakSnapshot _buildSnapshot() {
final next = _nextTarget();
final last = _lastRecorded();
final nextEx = next == null ? null : widget.exercises[next.$1];
return BreakSnapshot(
workoutType: widget.workoutType,
breakEndMs: _breakClock?.endTime.millisecondsSinceEpoch ?? 0,
breakDurationSecs: _breakDurationSecs,
breakLabel: _breakLabel,
breakForExIdx: _breakForExIdx,
breakForSetIdx: _breakForSetIdx,
nextExIdx: next?.$1 ?? -1,
nextSetIdx: next?.$2 ?? -1,
nextExName: nextEx?.name ?? '',
nextSetNumber: (next?.$2 ?? -1) + 1,
nextTotalSets: nextEx?.sets ?? 0,
nextReps: nextEx?.reps ?? 0,
nextWeight: nextEx?.weight ?? 0,
lastExIdx: last?.$1 ?? -1,
lastSetIdx: last?.$2 ?? -1,
setsRemaining: _setsRemaining(),
finished: _finished,
);
}
/// The set `✓ Done` would record: the first untapped one.
///
/// Scans the break's own exercise first, so finishing a rest offers the next
/// set of the lift the user is standing at rather than jumping ahead.
(int, int)? _nextTarget() {
final preferred = _breakForExIdx;
if (preferred >= 0 && preferred < widget.exercises.length) {
final inExercise = _firstUntappedIn(preferred);
if (inExercise != null) return (preferred, inExercise);
}
for (var ex = 0; ex < widget.exercises.length; ex++) {
final setIdx = _firstUntappedIn(ex);
if (setIdx != null) return (ex, setIdx);
}
return null;
}
int? _firstUntappedIn(int exIdx) {
for (var s = 0; s < _tapped[exIdx].length; s++) {
if (!_tapped[exIdx][s]) return s;
}
return null;
}
/// The set `− 1 rep` would decrement: the one the break belongs to, else the
/// last tapped set in plan order.
(int, int)? _lastRecorded() {
if (_breakForExIdx >= 0 && _breakForSetIdx >= 0) {
return (_breakForExIdx, _breakForSetIdx);
}
for (var ex = widget.exercises.length - 1; ex >= 0; ex--) {
for (var s = _tapped[ex].length - 1; s >= 0; s--) {
if (_tapped[ex][s]) return (ex, s);
}
}
return null;
}
int _setsRemaining() {
var count = 0;
for (final row in _tapped) {
for (final done in row) {
if (!done) count++;
}
}
return count;
}
/// Hands the workout to the foreground service, then applies anything the
/// user already pressed on a notification from a previous run of the app.
///
/// Order matters: `_restoreFromSaved` has already rebuilt the base state from
/// sqflite, and the queue is the delta on top of it. Draining first would be
/// overwritten by the stale base.
Future<void> _startBreakService() async {
final result = await _breaks.start(
_buildSnapshot(),
onDrainNudge: () => unawaited(_drainIntents()),
);
if (result.needsPermissionWarning && mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Notifications are off — the rest timer still runs and still '
'sounds, but there will be no status-bar countdown.',
),
duration: Duration(seconds: 6),
),
);
}
await _drainIntents();
}
/// Applies every press the user made from the notification, oldest first.
Future<void> _drainIntents() =>
_breaks.drain((intent) async => _applyIntent(intent));
/// Applies one press, or says out loud why it could not be.
///
/// Every path goes through the same `_tapCircle` / `_skipBreak` the on-screen
/// buttons use, so the notification can never invent a rule the UI does not
/// have. A press that no longer makes sense is dropped rather than forced:
/// the state moved on while the press was in the queue.
void _applyIntent(BreakIntent intent) {
if (_finished) {
_dropIntent(intent, 'the workout is already finished');
return;
}
switch (intent.kind) {
case BreakIntentKind.skipBreak:
if (!_inBreak) {
_dropIntent(intent, 'no rest period is running any more');
return;
}
_skipBreak();
case BreakIntentKind.done:
if (!_isValidSet(intent)) return;
if (_tapped[intent.exIdx][intent.setIdx]) {
_dropIntent(intent, 'that set was already recorded');
return;
}
// Pressing Done during a rest means "I am done resting AND done with
// the set" -- the two taps the user would make by hand. `_tapCircle`
// refuses a new set mid-break, so the rest is ended first.
if (_inBreak) _skipBreak();
_tapCircle(intent.exIdx, intent.setIdx);
case BreakIntentKind.minusRep:
if (!_isValidSet(intent)) return;
if (!_tapped[intent.exIdx][intent.setIdx]) {
_dropIntent(intent, 'that set is no longer recorded');
return;
}
_tapCircle(intent.exIdx, intent.setIdx);
}
}
bool _isValidSet(BreakIntent intent) {
final exOk = intent.exIdx >= 0 && intent.exIdx < widget.exercises.length;
if (!exOk || intent.setIdx < 0 ||
intent.setIdx >= _tapped[intent.exIdx].length) {
_dropIntent(intent, 'it points at a set this workout does not have');
return false;
}
return true;
}
void _dropIntent(BreakIntent intent, String why) => log(
'WorkoutScreen: dropped notification press $intent — $why. The button '
'press was recorded before the workout moved on.',
level: 900,
);
}

View File

@ -10,8 +10,9 @@ part of 'workout_screen.dart';
extension _WorkoutScreenSession on _WorkoutScreenState {
/// Rebuilds in-memory session state from a persisted [s] blob.
///
/// Restores a break only when its recorded end time is still in the future,
/// so a session resumed after the rest period simply has no break running.
/// A break whose recorded end time has already passed is *not* dropped: it is
/// parked in `_expiredBreak` so the screen can say so and, if the user only
/// just missed it, play the cue they were waiting for.
void _restoreFromSaved(Map<String, dynamic> s) {
_startTime = DateTime.fromMillisecondsSinceEpoch(s['startTimeMs'] as int);
_tapped = (s['tapped'] as List)
@ -26,19 +27,55 @@ extension _WorkoutScreenSession on _WorkoutScreenState {
final breakDur = s['breakDurationSecs'] as int? ?? 0;
if (breakEndMs > 0 && breakDur > 0) {
final endTime = DateTime.fromMillisecondsSinceEpoch(breakEndMs);
final remaining = endTime.difference(DateTime.now()).inSeconds;
if (remaining > 0) {
final clock = BreakClock(endTime: endTime, durationSecs: breakDur);
if (!clock.expiredAt(DateTime.now())) {
_breakForExIdx = s['breakForExIdx'] as int? ?? -1;
_breakForSetIdx = s['breakForSetIdx'] as int? ?? -1;
_breakLabel = s['breakLabel'] as String? ?? 'Rest';
_breakDurationSecs = breakDur;
_breakStartTime = endTime.subtract(Duration(seconds: breakDur));
_breakRemaining = remaining;
_breakClock = clock;
_breakTimer = Timer.periodic(const Duration(seconds: 1), _tickBreak);
} else {
// NEVER fail silently. This branch used to be an implicit no-op, which
// is why "the break never rang" was indistinguishable from "there was
// no break": the app was away when the rest ended, and said nothing
// about it on the way back.
log(
'WorkoutScreen: the restored session had a rest period that ended '
'${clock.secondsOverdueAt(DateTime.now())}s ago while the app was '
'not running, so its end cue never played.',
level: 900,
);
_expiredBreak = clock;
}
}
}
/// Plays the cue for a break that ended while the app was away, if it is
/// still recent enough to be useful.
///
/// Called once, after the first frame. Beyond the grace window the rest is
/// ancient history and firing the sound would just be startling — but the
/// `log` above has already recorded it either way.
Future<void> _settleExpiredBreak() async {
final clock = _expiredBreak;
_expiredBreak = null;
if (clock == null) return;
final overdue = clock.secondsOverdueAt(DateTime.now());
if (overdue > _expiredBreakGraceSecs) {
log(
'WorkoutScreen: not replaying the rest-end cue — it is ${overdue}s '
'late, past the ${_expiredBreakGraceSecs}s grace window.',
level: 800,
);
return;
}
await _playBreakEndCue();
// Forget the break now it has been settled. Without this the saved session
// still carries its deadline, so relaunching twice inside the grace window
// would sound the cue again for a rest that ended once.
unawaited(_saveActiveSession());
}
/// Persists the active session locally, and to Firebase when [toFirebase].
///
/// [toFirebase] is false on the per-tap paths (rep decrements, break
@ -49,6 +86,11 @@ extension _WorkoutScreenSession on _WorkoutScreenState {
Future<void> _saveActiveSession({bool toFirebase = false}) async {
final data = _activeSessionData();
await StorageService.instance.saveActiveSession(data);
// The one seam the notification is fed from. Every event that moves the
// workout on -- a set, a warmup, a rep decrement, a skip, a reset, a
// drained press -- already comes through here, so hanging the push on it
// means none of them can be forgotten.
unawaited(_breaks.push(_buildSnapshot()));
if (!toFirebase) return;
_lastActiveSessionPush = ProgressionSyncService()
.pushActiveSession(data)
@ -74,30 +116,26 @@ extension _WorkoutScreenSession on _WorkoutScreenState {
'breakForSetIdx': _breakForSetIdx,
'breakLabel': _breakLabel,
'breakDurationSecs': _breakDurationSecs,
'breakEndMs': _breakStartTime != null
? _breakStartTime!
.add(Duration(seconds: _breakDurationSecs))
.millisecondsSinceEpoch
: 0,
'breakEndMs': _breakClock?.endTime.millisecondsSinceEpoch ?? 0,
};
}
/// When the user decrements reps on the set that triggered the current break,
/// switch between 3-min (success) and 5-min (fail) durations.
void _recomputeBreakIfNeeded(int exIdx, int setIdx) {
if (!_inBreak) return;
// Read the clock ONCE. `_inBreak` re-reads DateTime.now() every time it is
// touched, so guarding on it and then dereferencing `_breakClock!` is a
// null-assertion waiting for the break to expire between the two lines.
final clock = _breakClock;
if (clock == null || clock.expiredAt(DateTime.now())) return;
if (_breakForExIdx != exIdx || _breakForSetIdx != setIdx) return;
if (_breakForSetIdx == -1) return; // warmup break, never recompute
final succeeded = _doneReps[exIdx][setIdx] >= widget.exercises[exIdx].reps;
final newDuration = succeeded ? _successBreakSecs : _failBreakSecs;
if (newDuration == _breakDurationSecs) return;
if (newDuration == clock.durationSecs) return;
final elapsed = DateTime.now().difference(_breakStartTime!).inSeconds;
final newRemaining = (newDuration - elapsed).clamp(0, newDuration);
_breakDurationSecs = newDuration;
_breakRemaining = newRemaining;
_breakClock = clock.withDuration(newDuration);
_breakLabel = succeeded
? 'Rest (3 min — well done!)'
: 'Rest (5 min — keep going!)';

View File

@ -0,0 +1,65 @@
// Rep-circle and warmup tap handlers for the active workout screen.
//
// A `part` rather than a separate library so the extension keeps reaching the
// private `_WorkoutScreenState` fields. `setState` is `@protected` and cannot
// be called from an extension, so these mutate through the state class's
// `_applyBreakState` shim — the same seam `workout_screen_breaks.dart` uses.
part of 'workout_screen.dart';
/// The three ways a user records work: tap a set, tap a warmup, undo a set.
extension _WorkoutScreenTaps on _WorkoutScreenState {
/// Records set [setIdx] of exercise [exIdx], or decrements its reps.
///
/// First tap marks the set done at the exercise's full target reps and earns
/// the rest period. Every later tap decrements the reps by one, which can
/// flip the running break between its 3-minute and 5-minute durations.
void _tapCircle(int exIdx, int setIdx) {
if (_finished) return;
final wasNotTapped = !_tapped[exIdx][setIdx];
if (wasNotTapped && _inBreak) return;
_applyBreakState(() {
if (wasNotTapped) {
_tapped[exIdx][setIdx] = true;
} else {
_doneReps[exIdx][setIdx] = (_doneReps[exIdx][setIdx] - 1).clamp(0, 999);
_recomputeBreakIfNeeded(exIdx, setIdx);
}
});
if (wasNotTapped) {
final rest = _restAfterSet(exIdx, setIdx);
if (rest != null) {
_startBreak(rest.seconds, rest.label, exIdx, setIdx);
}
}
// Only a newly-completed set moves the workout forward; a rep decrement
// re-enters here and must not cost a remote write.
unawaited(_saveActiveSession(toFirebase: wasNotTapped));
}
/// Marks exercise [exIdx]'s warmup done and starts the warmup rest.
void _tapWarmup(int exIdx) {
if (_finished || _warmupTapped[exIdx]) return;
_applyBreakState(() => _warmupTapped[exIdx] = true);
if (!_inBreak) {
_startBreak(_warmupBreakSecs, 'Warmup rest (3 min)', exIdx, -1);
}
unawaited(_saveActiveSession(toFirebase: true));
}
/// Undoes set [setIdx] of [exIdx], restoring its full target reps.
void _resetCircle(int exIdx, int setIdx) {
if (_finished) return;
_applyBreakState(() {
_tapped[exIdx][setIdx] = false;
_doneReps[exIdx][setIdx] = widget.exercises[exIdx].reps;
});
if (_breakForExIdx == exIdx && _breakForSetIdx == setIdx) {
_cancelBreak();
}
unawaited(_saveActiveSession());
}
}

View File

@ -0,0 +1,73 @@
/// Wall-clock arithmetic for a rest period between sets.
library;
import 'package:flutter/foundation.dart';
/// An immutable rest period, described by when it *ends* rather than by how
/// many ticks are left.
///
/// The break countdown used to be a plain `int` decremented once per
/// `Timer.periodic` tick. Android throttles — and in Doze suspends — timers in
/// a backgrounded isolate, so that counter stalled, never reached zero, and the
/// break-end cue never fired. Deriving the remaining time from a stored
/// deadline makes a stalled timer merely *stale*: the next tick, whenever it
/// lands, reports the truth.
@immutable
class BreakClock {
/// Creates a clock for a break of [durationSecs] ending at [endTime].
const BreakClock({required this.endTime, required this.durationSecs});
/// Creates a clock for a break of [durationSecs] starting at [start].
factory BreakClock.startingAt(DateTime start, int durationSecs) => BreakClock(
endTime: start.add(Duration(seconds: durationSecs)),
durationSecs: durationSecs,
);
/// When the rest period is over.
final DateTime endTime;
/// The rest period's full length in seconds, for the progress bar.
final int durationSecs;
/// When the rest period began.
DateTime get startTime => endTime.subtract(Duration(seconds: durationSecs));
/// Whole seconds left at [now], rounded up and floored at zero.
///
/// Rounded up so a break of 180 s reads "180" for its whole first second,
/// matching what the decrementing counter used to show.
int remainingSecsAt(DateTime now) {
final us = endTime.difference(now).inMicroseconds;
if (us <= 0) return 0;
return (us + Duration.microsecondsPerSecond - 1) ~/
Duration.microsecondsPerSecond;
}
/// True once [now] has reached [endTime].
bool expiredAt(DateTime now) => !now.isBefore(endTime);
/// Whole seconds since the break ended; zero while it is still running.
int secondsOverdueAt(DateTime now) {
final overdue = now.difference(endTime).inSeconds;
return overdue > 0 ? overdue : 0;
}
/// Returns this break re-cut to [secs], keeping the moment it started.
///
/// This is the 3-min ↔ 5-min switch that happens when the user decrements
/// reps on the set that earned the rest: the clock does not restart, it just
/// ends sooner or later than it was going to.
BreakClock withDuration(int secs) => BreakClock.startingAt(startTime, secs);
@override
bool operator ==(Object other) =>
other is BreakClock &&
other.endTime == endTime &&
other.durationSecs == durationSecs;
@override
int get hashCode => Object.hash(endTime, durationSecs);
@override
String toString() => 'BreakClock($endTime, ${durationSecs}s)';
}

View File

@ -0,0 +1,155 @@
/// The durable hand-off between the foreground service and the workout screen.
library;
import 'dart:async';
import 'dart:developer';
import 'package:workout_app/models/break_intent.dart';
import 'package:workout_app/services/break_intent_store.dart';
/// A write-ahead log of notification button presses.
///
/// The foreground service runs in its own isolate that outlives the UI, so a
/// button press cannot simply call into the workout screen — the screen may not
/// exist. Every press is therefore appended here first and applied later, which
/// also makes the "app is alive" and "app was killed" paths the same code.
///
/// The service's live `sendDataToMain` message carries no payload: it is only a
/// nudge to drain. That is what makes double-application impossible rather than
/// merely unlikely.
class BreakIntentQueue {
/// Creates a queue over [store].
BreakIntentQueue(this._store);
/// Last sequence number handed out. Written only by the service isolate.
static const seqKey = 'workout.break.seq';
/// The pending intents. Appended by the service, pruned by the UI.
static const intentsKey = 'workout.break.intents';
/// Last sequence number applied. Written only by the UI isolate.
static const lastAppliedKey = 'workout.break.lastApplied';
/// Beyond this many pending presses the oldest are dropped, loudly.
///
/// A workout is a few dozen presses; anything approaching this means the UI
/// has not drained for a very long time and the oldest entries are stale.
static const maxEntries = 64;
final BreakIntentStore _store;
bool _draining = false;
bool _redrainRequested = false;
/// Appends a press and returns the intent that was recorded.
///
/// Called from the service isolate. The sequence number is written *before*
/// the list: a crash between the two leaves a gap in the numbering, which the
/// `seq > lastApplied` filter tolerates. Writing the list first would let two
/// presses share a number, and the second would be silently swallowed as a
/// duplicate — a lost press is worse than a skipped number.
Future<BreakIntent> enqueue({
required BreakIntentKind kind,
required int exIdx,
required int setIdx,
required DateTime now,
}) async {
final seq = await _store.readInt(seqKey) + 1;
await _store.writeInt(seqKey, seq);
final intent = BreakIntent(
seq: seq,
kind: kind,
exIdx: exIdx,
setIdx: setIdx,
tsMs: now.millisecondsSinceEpoch,
);
final entries = [
...await _store.readStringList(intentsKey),
intent.encode(),
];
if (entries.length > maxEntries) {
final dropped = entries.length - maxEntries;
log(
'BreakIntentQueue: queue overflowed at ${entries.length} entries — '
'dropped the $dropped oldest notification press(es) unapplied. The '
'workout screen has not drained the queue for a very long time.',
level: 900,
);
entries.removeRange(0, dropped);
}
await _store.writeStringList(intentsKey, entries);
return intent;
}
/// Applies every press the UI has not seen yet, oldest first.
///
/// [apply] is called once per intent, in sequence order. `lastApplied` is
/// committed after each one rather than at the end, so a crash part-way
/// through resumes from where it stopped instead of replaying work the user
/// can already see.
///
/// Re-entrant calls do not nest: a nudge that arrives mid-drain schedules one
/// more pass instead, so a press is never lost and never applied twice.
Future<void> drain(Future<void> Function(BreakIntent intent) apply) async {
if (_draining) {
_redrainRequested = true;
return;
}
_draining = true;
try {
do {
_redrainRequested = false;
await _drainOnce(apply);
} while (_redrainRequested);
} finally {
_draining = false;
}
}
Future<void> _drainOnce(Future<void> Function(BreakIntent) apply) async {
final raw = await _store.readStringList(intentsKey);
if (raw.isEmpty) return;
var lastApplied = await _store.readInt(lastAppliedKey);
final pending = <BreakIntent>[];
for (final entry in raw) {
final intent = BreakIntent.tryDecode(entry);
if (intent == null) {
log(
'BreakIntentQueue: dropped an unreadable queue entry — a '
'notification press was lost. Raw text: $entry',
level: 900,
);
continue;
}
if (intent.seq > lastApplied) pending.add(intent);
}
pending.sort((a, b) => a.seq.compareTo(b.seq));
for (final intent in pending) {
await apply(intent);
lastApplied = intent.seq;
await _store.writeInt(lastAppliedKey, lastApplied);
}
// Re-READ before pruning. `raw` is a snapshot from before the applies, and
// the service isolate appends to this list whenever the user presses a
// button -- including while this drain was running. Writing the filtered
// snapshot back would erase any press that arrived in between, silently.
final current = await _store.readStringList(intentsKey);
final keep = [
for (final entry in current)
if ((BreakIntent.tryDecode(entry)?.seq ?? -1) > lastApplied) entry,
];
if (keep.length != current.length) {
await _store.writeStringList(intentsKey, keep);
}
}
/// Forgets every pending press, e.g. when a workout is finished or reset.
Future<void> clear() async {
await _store.writeStringList(intentsKey, const []);
await _store.writeInt(lastAppliedKey, await _store.readInt(seqKey));
}
}

View File

@ -0,0 +1,60 @@
/// Cross-isolate key/value storage for the notification intent queue.
library;
import 'package:shared_preferences/shared_preferences.dart';
/// The handful of reads and writes the intent queue needs.
///
/// An interface rather than `SharedPreferencesAsync` directly so the queue's
/// ordering rules can be tested without a platform channel, and so the one
/// place that talks to the platform is small enough to read in one go.
abstract class BreakIntentStore {
/// Reads [key], or zero when it has never been written.
Future<int> readInt(String key);
/// Writes [value] to [key].
Future<void> writeInt(String key, int value);
/// Reads [key], or an empty list when it has never been written.
Future<List<String>> readStringList(String key);
/// Writes [value] to [key].
Future<void> writeStringList(String key, List<String> value);
}
/// The real store, backed by `SharedPreferencesAsync`.
///
/// `SharedPreferencesAsync`, never `SharedPreferences.getInstance()`. The
/// legacy API hands back a snapshot cached at load time, so the UI isolate
/// would keep reading the queue as it looked when the screen opened and would
/// never see anything the foreground service appended. Every notification
/// button would appear to do nothing at all.
class PrefsBreakIntentStore implements BreakIntentStore {
/// Creates a store over [prefs], defaulting to a fresh async instance.
PrefsBreakIntentStore([SharedPreferencesAsync? prefs]) : _prefs = prefs;
/// Resolved on first use, never in the constructor.
///
/// `SharedPreferencesAsync()` throws unless a platform instance is
/// registered, and the workout screen builds a store in `initState` on every
/// platform -- including Linux desktop and the test host, where there is no
/// foreground service to have queued anything in the first place. Deferring
/// means merely owning a store costs nothing.
SharedPreferencesAsync? _prefs;
SharedPreferencesAsync get _resolved => _prefs ??= SharedPreferencesAsync();
@override
Future<int> readInt(String key) async => await _resolved.getInt(key) ?? 0;
@override
Future<void> writeInt(String key, int value) => _resolved.setInt(key, value);
@override
Future<List<String>> readStringList(String key) async =>
await _resolved.getStringList(key) ?? const [];
@override
Future<void> writeStringList(String key, List<String> value) =>
_resolved.setStringList(key, value);
}

View File

@ -0,0 +1,87 @@
/// The words on the workout's ongoing status-bar notification.
library;
import 'package:flutter/foundation.dart';
import 'package:workout_app/models/break_snapshot.dart';
import 'package:workout_app/services/break_clock.dart';
/// Rendered notification copy: what Android shows collapsed, and expanded.
@immutable
class BreakNotificationCopy {
/// Creates a rendered title/body pair.
const BreakNotificationCopy(this.title, this.body);
/// Line one. Android shows this even when the notification is collapsed, so
/// the countdown lives here rather than in the body.
final String title;
/// Lines two and three: which exercise, which set, how many reps at what
/// weight. Only visible when the notification is expanded.
final String body;
@override
bool operator ==(Object other) =>
other is BreakNotificationCopy &&
other.title == title &&
other.body == body;
@override
int get hashCode => Object.hash(title, body);
@override
String toString() => 'BreakNotificationCopy($title | $body)';
}
/// Turns a [BreakSnapshot] into the text on the notification.
///
/// Pure by design: this is the part that changes every second, so it has to be
/// cheap to compare (the service only redraws when the text actually changed)
/// and testable without a device.
abstract final class BreakNotificationText {
/// Renders the notification for [snapshot] as of [now].
static BreakNotificationCopy render(BreakSnapshot snapshot, DateTime now) {
if (snapshot.finished) {
return const BreakNotificationCopy(
'Workout complete',
'Open the app to save it.',
);
}
return BreakNotificationCopy(
_title(snapshot, now),
_body(snapshot),
);
}
static String _title(BreakSnapshot s, DateTime now) {
final prefix = 'Workout ${s.workoutType}';
if (!s.hasBreak) {
return '$prefix · lift';
}
final clock = BreakClock(
endTime: DateTime.fromMillisecondsSinceEpoch(s.breakEndMs),
durationSecs: s.breakDurationSecs,
);
final remaining = clock.remainingSecsAt(now);
if (remaining <= 0) return '$prefix · break over';
return '$prefix · break ${formatMmSs(remaining)}';
}
static String _body(BreakSnapshot s) {
if (!s.hasNextSet) return 'Every set is done — finish the workout.';
return 'Next: ${s.nextExName} — set ${s.nextSetNumber}/${s.nextTotalSets}\n'
'${s.nextReps} reps @ ${formatWeight(s.nextWeight)} kg';
}
/// Formats [totalSecs] as `m:ss`, e.g. 107 -> `1:47`.
static String formatMmSs(int totalSecs) {
final m = totalSecs ~/ 60;
final s = (totalSecs % 60).toString().padLeft(2, '0');
return '$m:$s';
}
/// Formats [kg] without a pointless trailing zero: 40.0 -> `40`.
static String formatWeight(double kg) {
final oneDp = kg.toStringAsFixed(1);
return oneDp.endsWith('.0') ? oneDp.substring(0, oneDp.length - 2) : oneDp;
}
}

View File

@ -0,0 +1,124 @@
/// Owns the foreground service on behalf of the workout screen.
library;
import 'dart:async';
import 'dart:developer';
import 'package:workout_app/models/break_intent.dart';
import 'package:workout_app/models/break_snapshot.dart';
import 'package:workout_app/services/break_intent_queue.dart';
import 'package:workout_app/services/foreground_break_client.dart';
/// Stops a break service left running by a workout that no longer exists.
///
/// The service deliberately outlives its screen — the back button pops the
/// workout while it carries on in the database — and `stopWithTask="false"`
/// means it also outlives the task being swiped away. That is the point, but
/// it means a crash between "service started" and "workout finished" would
/// otherwise leave a notification counting down forever with nothing behind
/// it. Called once at startup, when the answer is knowable.
Future<bool> stopStaleBreakService(
ForegroundBreakClient client, {
required Future<bool> Function() hasActiveWorkout,
}) async {
if (!client.isSupported) return false;
if (!await client.isRunning()) return false;
if (await hasActiveWorkout()) return false;
log(
'WorkoutApp: a break service was still running with no workout in '
'progress — stopping it. Its notification was counting down a session '
'that had already ended.',
level: 900,
);
await client.stop();
return true;
}
/// Starts the service, keeps it fed, and applies what the user pressed.
///
/// Pulled out of `WorkoutScreen` so the permission handling, the failure
/// reporting and the drain scheduling can be tested without a device — the
/// screen keeps only the parts that need `setState`.
class BreakServiceController {
/// Creates a controller over [client] and [queue].
BreakServiceController(this._client, this._queue);
final ForegroundBreakClient _client;
final BreakIntentQueue _queue;
var _started = false;
/// True once the service has been started for this workout.
bool get isStarted => _started;
/// Starts the service for [snapshot] and begins listening for nudges.
///
/// Returns what actually happened, so the screen can tell the user when the
/// notification will not appear. A denied permission does NOT stop the
/// service: its isolate still holds the wake lock and still plays the
/// break-end sound, so the alert survives even when the status bar is empty.
Future<BreakServiceStartResult> start(
BreakSnapshot snapshot, {
required void Function() onDrainNudge,
}) async {
if (!_client.isSupported) return BreakServiceStartResult.unsupported;
await _client.init();
var notificationsAllowed = await _client.hasNotificationPermission();
if (!notificationsAllowed) {
notificationsAllowed = await _client.requestNotificationPermission();
}
if (!notificationsAllowed) {
log(
'WorkoutScreen: notification permission denied. The rest timer still '
'runs and the break-end sound still plays, but the status-bar '
'countdown and its Done / − 1 rep / Skip buttons cannot be shown. '
'Grant it in Settings > Apps > Workout Tracker > Notifications.',
level: 1000,
);
}
_client.listenForDrainNudges(onDrainNudge);
final ok = await _client.start(snapshot);
if (!ok) {
_client.stopListeningForDrainNudges();
log(
'WorkoutScreen: the foreground break service refused to start. The '
'in-app countdown still works, but it will stall if the phone sleeps '
'— keep the app open for this workout.',
level: 1000,
);
return BreakServiceStartResult.failed;
}
_started = true;
return notificationsAllowed
? BreakServiceStartResult.started
: BreakServiceStartResult.startedWithoutNotification;
}
/// Sends the service the current state of the workout.
Future<void> push(BreakSnapshot snapshot) async {
if (!_started) return;
await _client.push(snapshot);
}
/// Stops the service and forgets any presses that were never applied.
Future<void> stop() async {
if (!_client.isSupported) return;
_client.stopListeningForDrainNudges();
if (_started) {
await _client.stop();
_started = false;
}
await _queue.clear();
}
/// Applies every press the screen has not seen yet, via [apply].
///
/// A platform with no foreground service has no notification to press, so
/// there is nothing to drain and no reason to touch the queue's storage.
Future<void> drain(Future<void> Function(BreakIntent intent) apply) async {
if (!_client.isSupported) return;
await _queue.drain(apply);
}
}

View File

@ -0,0 +1,59 @@
/// Everything the break task handler is allowed to do to the outside world.
library;
import 'package:workout_app/services/break_notification_text.dart';
/// Notification action button ids, as Android hands them back.
abstract final class BreakNotificationAction {
/// Record the next set at its full target reps.
static const done = 'done';
/// Knock one rep off the set that was recorded last.
static const minusRep = 'minus_rep';
/// End the running rest early.
static const skipBreak = 'skip_break';
/// Every id, in the order the buttons appear on the notification.
///
/// Android allows at most three, which is why `Done` records the full target
/// reps and `− 1 rep` walks down from there instead of there being a button
/// per rep count: targets range from 5 to 30 across the plan.
static List<String> get inButtonOrder => const [done, minusRep, skipBreak];
}
/// The side effects available inside the foreground-service isolate.
///
/// An interface so the task handler's decisions — when to redraw, when to
/// alert, when to stop — can be tested on a machine with no Android on it. The
/// real implementation is the only code in this feature that touches a
/// platform channel.
///
/// Deliberately has no storage method beyond the intent queue's own: the
/// service isolate must never write to sqflite. The CRDT sync layer sits on top
/// of that database and stamps records with a clock the UI isolate owns; a
/// second writer would order its writes outside that sequence.
abstract class BreakServicePort {
/// Registers plugins in this isolate. Must run before anything else.
///
/// A background isolate starts with no plugin registrations at all, so
/// without this every later call fails with `MissingPluginException` — and
/// the break-end sound fails exactly as silently as the bug being fixed.
Future<void> ensureIsolateReady();
/// Redraws the ongoing notification.
Future<void> updateNotification(BreakNotificationCopy copy);
/// Fires the break-end alert: the sound, the haptic, and the heads-up.
Future<void> fireBreakEndAlert();
/// Nudges the UI isolate to drain the intent queue.
///
/// Carries no payload on purpose. The queue is the only path a press takes,
/// so a nudge that is lost costs nothing and a nudge that arrives twice
/// cannot apply anything twice.
void nudgeMainToDrain();
/// Shows the terminal "workout complete" notification and stops the service.
Future<void> finishAndStop();
}

View File

@ -0,0 +1,136 @@
/// The one file in the break feature that touches a platform channel.
library;
import 'dart:developer';
import 'dart:ui';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:vibration/vibration.dart';
import 'package:workout_app/services/break_notification_text.dart';
import 'package:workout_app/services/break_service_port.dart';
/// Channel the break-end alert is posted on.
///
/// VERSIONED ON PURPOSE. Android freezes a channel's importance, sound and
/// vibration the first time it is created, and neither reinstalling nor
/// `adb install -r` resets that. If this channel ever lands with the wrong
/// settings on a device it can only be fixed by creating a NEW one — bump the
/// suffix, never edit `_v1` and hope. The symptom of getting this wrong is a
/// silent alert that looks exactly like a code bug.
const kBreakEndChannelId = 'break_end_v1';
/// Notification id of the break-end alert.
const kBreakEndNotificationId = 8801;
/// Notification id of the terminal "workout complete" message.
const kWorkoutDoneNotificationId = 8802;
/// The real [BreakServicePort], running inside the foreground-service isolate.
class FlutterBreakServicePort implements BreakServicePort {
/// Creates a port. Cheap: nothing happens until [ensureIsolateReady].
FlutterBreakServicePort();
final _notifications = FlutterLocalNotificationsPlugin();
AudioPlayer? _player;
// Every method below is a platform-channel passthrough from a BACKGROUND
// isolate. `flutter test` has no such isolate and no such channels, so none
// of this can run on the test host; the decisions that lead here all live in
// break_task_handler.dart, which is covered against a fake port.
// coverage:ignore-start
@override
Future<void> ensureIsolateReady() async {
// A background isolate starts with no plugin registrations. Without this
// the sound, the haptic and the notification all fail with
// MissingPluginException -- silently, because they are fire-and-forget.
DartPluginRegistrant.ensureInitialized();
_player ??= AudioPlayer();
const settings = InitializationSettings(
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
);
await _notifications.initialize(settings: settings);
await _notifications
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>()
?.createNotificationChannel(
const AndroidNotificationChannel(
kBreakEndChannelId,
'Break finished',
description: 'Sounds when a rest period between sets is over.',
importance: Importance.max,
sound: RawResourceAndroidNotificationSound('break_end'),
),
);
}
@override
Future<void> updateNotification(BreakNotificationCopy copy) =>
FlutterForegroundTask.updateService(
notificationTitle: copy.title,
notificationText: copy.body,
);
@override
Future<void> fireBreakEndAlert() async {
// Two routes on purpose. The mp3 goes out on the MEDIA stream, so it is
// heard even with the phone on vibrate; the notification goes out on its
// own max-importance channel, so it still fires if this isolate is busy.
try {
await _player?.play(AssetSource('sounds/break_end.mp3'));
} on Exception catch (error) {
log(
'BreakService: the break-end sound failed to play ($error). The '
'notification alert below is the only cue the user will get.',
level: 1000,
);
}
if (await Vibration.hasVibrator()) {
await Vibration.vibrate(duration: 800);
}
await _notifications.show(
id: kBreakEndNotificationId,
title: 'Break over',
body: 'Back to the bar.',
notificationDetails: const NotificationDetails(
android: AndroidNotificationDetails(
kBreakEndChannelId,
'Break finished',
importance: Importance.max,
priority: Priority.max,
category: AndroidNotificationCategory.alarm,
fullScreenIntent: true,
),
),
);
}
@override
void nudgeMainToDrain() =>
FlutterForegroundTask.sendDataToMain(const {'kind': 'drain'});
@override
Future<void> finishAndStop() async {
await _notifications.show(
id: kWorkoutDoneNotificationId,
title: 'Workout complete',
body: 'Open the app to save it.',
notificationDetails: const NotificationDetails(
android: AndroidNotificationDetails(
kBreakEndChannelId,
'Break finished',
importance: Importance.high,
priority: Priority.high,
),
),
);
await FlutterForegroundTask.stopService();
}
// coverage:ignore-end
}

View File

@ -0,0 +1,226 @@
/// The workout's foreground-service brain, minus every platform call.
library;
import 'dart:async';
import 'dart:developer';
import 'package:workout_app/models/break_intent.dart';
import 'package:workout_app/models/break_snapshot.dart';
import 'package:workout_app/services/break_clock.dart';
import 'package:workout_app/services/break_intent_queue.dart';
import 'package:workout_app/services/break_notification_text.dart';
import 'package:workout_app/services/break_service_port.dart';
/// Drives the ongoing notification and the break-end alert.
///
/// Lives in its own isolate with no access to the workout screen, so it works
/// from a snapshot the UI pushes and records what the user presses into a
/// durable queue for the UI to apply whenever it next exists.
class BreakTaskHandler {
/// Creates a handler over [port] and [queue].
BreakTaskHandler(this._port, this._queue);
final BreakServicePort _port;
final BreakIntentQueue _queue;
BreakSnapshot? _snapshot;
BreakNotificationCopy? _lastDrawn;
int _alertedEndMs = 0;
/// The snapshot currently driving the notification; for tests.
BreakSnapshot? get snapshot => _snapshot;
/// Prepares the isolate. Call from `TaskHandler.onStart`.
///
/// [now] is passed in rather than read here so the handler has no hidden
/// clock: every time-dependent decision it makes is reproducible.
Future<void> start(Object? initialData, DateTime now) async {
await _port.ensureIsolateReady();
_applyData(initialData);
await _redraw(now);
}
/// Handles a fresh snapshot pushed by the UI isolate.
Future<void> receiveData(Object? data, DateTime now) async {
_applyData(data);
await _redraw(now);
}
/// The once-a-second tick: redraw if the text moved, alert if the rest ended.
Future<void> tick(DateTime now) async {
final snapshot = _snapshot;
if (snapshot == null) return;
if (snapshot.hasBreak && snapshot.breakEndMs != _alertedEndMs) {
final clock = BreakClock(
endTime: DateTime.fromMillisecondsSinceEpoch(snapshot.breakEndMs),
durationSecs: snapshot.breakDurationSecs,
);
if (clock.expiredAt(now)) {
// Stamped before the alert, not after: if the alert throws, the user
// gets one failed attempt rather than the same sound every second.
_alertedEndMs = snapshot.breakEndMs;
await _port.fireBreakEndAlert();
}
}
await _redraw(now);
}
/// Records a notification button press and nudges the UI to apply it.
Future<void> pressButton(String id, DateTime now) async {
final snapshot = _snapshot;
if (snapshot == null) {
log(
'BreakTaskHandler: ignored notification button "$id" — the service has '
'no workout snapshot yet, so there is no set it could refer to.',
level: 900,
);
return;
}
final resolved = _resolve(id, snapshot);
if (resolved == null) return;
await _queue.enqueue(
kind: resolved.kind,
exIdx: resolved.exIdx,
setIdx: resolved.setIdx,
now: now,
);
_snapshot = _predict(resolved.kind, snapshot, now);
_port.nudgeMainToDrain();
if (_snapshot!.setsRemaining <= 0) {
// Nothing left to record, and the UI may never come back to stop us --
// the user can finish a whole workout from the notification. Stopping
// here is what keeps the service from outliving the workout.
await _port.finishAndStop();
return;
}
await _redraw(now);
}
void _applyData(Object? data) {
if (data is! Map) {
log(
'BreakTaskHandler: ignored task data of unexpected type '
'${data.runtimeType} — the notification still shows the previous '
'workout state.',
level: 900,
);
return;
}
final snapshot = BreakSnapshot.tryFromMap(data.cast<Object?, Object?>());
if (snapshot == null) {
log(
'BreakTaskHandler: ignored a malformed workout snapshot — the '
'notification still shows the previous state. Payload: $data',
level: 900,
);
return;
}
_snapshot = snapshot;
}
_ResolvedPress? _resolve(String id, BreakSnapshot s) {
switch (id) {
case BreakNotificationAction.done:
if (!s.hasNextSet) {
log(
'BreakTaskHandler: ignored "Done" — every set is already '
'recorded. Open the app to finish the workout.',
level: 900,
);
return null;
}
return _ResolvedPress(BreakIntentKind.done, s.nextExIdx, s.nextSetIdx);
case BreakNotificationAction.minusRep:
if (s.lastExIdx < 0 || s.lastSetIdx < 0) {
log(
'BreakTaskHandler: ignored "− 1 rep" — no set has been recorded '
'yet, so there is nothing to take a rep off.',
level: 900,
);
return null;
}
return _ResolvedPress(
BreakIntentKind.minusRep,
s.lastExIdx,
s.lastSetIdx,
);
case BreakNotificationAction.skipBreak:
if (!s.hasBreak) {
log(
'BreakTaskHandler: ignored "Skip break" — no rest period is '
'running.',
level: 900,
);
return null;
}
return _ResolvedPress(
BreakIntentKind.skipBreak,
s.breakForExIdx,
s.breakForSetIdx,
);
default:
log(
'BreakTaskHandler: ignored unknown notification button id "$id".',
level: 900,
);
return null;
}
}
/// Guesses the new state so the notification reacts to the press at once.
///
/// The UI overwrites this with the truth as soon as it drains the queue —
/// but it may be dead, and a button that visibly does nothing reads as
/// broken. Only the fields the press certainly changes are moved.
BreakSnapshot _predict(
BreakIntentKind kind,
BreakSnapshot s,
DateTime now,
) {
switch (kind) {
case BreakIntentKind.skipBreak:
return s.copyWith(breakEndMs: 0);
case BreakIntentKind.done:
// A rest starts, but only the screen knows whether this was the
// exercise's last set. Clear the break and let the UI's snapshot set
// the real deadline a moment later.
return s.copyWith(breakEndMs: 0, setsRemaining: s.setsRemaining - 1);
case BreakIntentKind.minusRep:
if (!s.hasBreak || s.breakForSetIdx < 0) return s;
// A decrement turns a success into a failure, which is the longer
// rest. Re-cut from the start, exactly as the screen does.
const failSecs = 300;
final clock = BreakClock(
endTime: DateTime.fromMillisecondsSinceEpoch(s.breakEndMs),
durationSecs: s.breakDurationSecs,
).withDuration(failSecs);
return s.copyWith(
breakEndMs: clock.endTime.millisecondsSinceEpoch,
breakDurationSecs: failSecs,
breakLabel: 'Rest (5 min — keep going!)',
);
}
}
Future<void> _redraw(DateTime now) async {
final snapshot = _snapshot;
if (snapshot == null) return;
final copy = BreakNotificationText.render(snapshot, now);
// Only when the words changed. An unconditional per-second update makes
// the notification flicker and costs battery for nothing.
if (copy == _lastDrawn) return;
_lastDrawn = copy;
await _port.updateNotification(copy);
}
}
class _ResolvedPress {
const _ResolvedPress(this.kind, this.exIdx, this.setIdx);
final BreakIntentKind kind;
final int exIdx;
final int setIdx;
}

View File

@ -0,0 +1,69 @@
/// The workout screen's side of the foreground-service conversation.
library;
import 'package:workout_app/models/break_snapshot.dart';
/// Why the foreground service could not be started.
enum BreakServiceStartResult {
/// The service is running and the notification is visible.
started,
/// Started, but the user denied notifications so nothing is on screen.
startedWithoutNotification,
/// The platform refused to start it.
failed,
/// This platform has no foreground services (Linux desktop, tests).
unsupported,
}
/// The two questions the workout screen asks of a [BreakServiceStartResult].
extension BreakServiceStartResultX on BreakServiceStartResult {
/// True when a service is now running and will hold the rest deadline.
bool get serviceRunning =>
this == BreakServiceStartResult.started ||
this == BreakServiceStartResult.startedWithoutNotification;
/// True when the user must be told the status bar will stay empty.
bool get needsPermissionWarning =>
this == BreakServiceStartResult.startedWithoutNotification;
}
/// Starting, feeding and stopping the workout's foreground service.
///
/// An interface so the workout screen's wiring is testable without Android,
/// and so the one file that touches `flutter_foreground_task` stays small
/// enough to review by eye.
abstract class ForegroundBreakClient {
/// False on platforms with no foreground service — Linux desktop, and the
/// test host. Every other method is a no-op when this is false.
bool get isSupported;
/// Configures the notification channel. Safe to call more than once.
Future<void> init();
/// True when a break service is running right now, from any past launch.
Future<bool> isRunning();
/// True when the app may post notifications.
Future<bool> hasNotificationPermission();
/// Asks for notification permission, returning whether it was granted.
Future<bool> requestNotificationPermission();
/// Starts the service showing [snapshot].
Future<bool> start(BreakSnapshot snapshot);
/// Pushes a fresh [snapshot] to the running service.
Future<void> push(BreakSnapshot snapshot);
/// Stops the service and removes its notification.
Future<void> stop();
/// Registers [onNudge], called when the service wants the queue drained.
void listenForDrainNudges(void Function() onNudge);
/// Unregisters the callback registered by [listenForDrainNudges].
void stopListeningForDrainNudges();
}

View File

@ -0,0 +1,175 @@
/// The real foreground-service client, and the service's entry point.
library;
import 'dart:io' show Platform;
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:workout_app/models/break_snapshot.dart';
import 'package:workout_app/services/break_intent_queue.dart';
import 'package:workout_app/services/break_intent_store.dart';
import 'package:workout_app/services/break_service_port.dart';
import 'package:workout_app/services/break_service_port_flutter.dart';
import 'package:workout_app/services/break_task_handler.dart';
import 'package:workout_app/services/foreground_break_client.dart';
/// Channel the ongoing workout notification lives on.
///
/// Separate from `break_end_v1` and deliberately LOW importance: this one is on
/// screen for the whole workout, so it must never buzz. The alert is the other
/// channel's job. Versioned for the same reason — channel settings freeze on
/// first creation and cannot be edited afterwards.
const kWorkoutOngoingChannelId = 'workout_ongoing_v1';
/// Button labels, parallel to [BreakNotificationAction.inButtonOrder].
const _buttonLabels = ['✓ Done', '− 1 rep', 'Skip break'];
/// Entry point the plugin calls in the background isolate.
// coverage:ignore-start
@pragma('vm:entry-point')
void breakServiceStartCallback() {
// Only ever invoked by flutter_foreground_task's isolate bootstrap; there is
// no isolate in `flutter test` that can reach it. Everything it builds is
// covered in break_task_handler_test.dart against a fake port.
FlutterForegroundTask.setTaskHandler(
_BreakServiceTaskHandler(
BreakTaskHandler(
FlutterBreakServicePort(),
BreakIntentQueue(PrefsBreakIntentStore()),
),
),
);
}
/// Adapts the plugin's callback shape onto the testable [BreakTaskHandler].
///
/// Only the background isolate constructs or calls this. Each override is a
/// single delegation; the logic behind it is covered against a fake port.
class _BreakServiceTaskHandler extends TaskHandler {
_BreakServiceTaskHandler(this._handler);
final BreakTaskHandler _handler;
@override
Future<void> onStart(DateTime timestamp, TaskStarter starter) =>
_handler.start(null, timestamp);
@override
void onRepeatEvent(DateTime timestamp) => _handler.tick(timestamp);
@override
void onReceiveData(Object data) =>
_handler.receiveData(data, DateTime.now());
@override
void onNotificationButtonPressed(String id) =>
_handler.pressButton(id, DateTime.now());
@override
void onNotificationPressed() => FlutterForegroundTask.launchApp();
@override
Future<void> onDestroy(DateTime timestamp, bool isTimeout) async {}
}
// coverage:ignore-end
/// The real [ForegroundBreakClient], driving `flutter_foreground_task`.
class FlutterForegroundBreakClient implements ForegroundBreakClient {
/// Creates a client. Cheap: nothing happens until [init].
FlutterForegroundBreakClient();
void Function()? _onNudge;
@override
bool get isSupported => Platform.isAndroid;
// Platform-channel passthroughs. `flutter test` runs on Linux, where
// isSupported is false and none of this is reachable; the decisions that
// lead here live in break_service_controller.dart, covered against a fake.
// coverage:ignore-start
@override
Future<void> init() async {
FlutterForegroundTask.init(
androidNotificationOptions: AndroidNotificationOptions(
channelId: kWorkoutOngoingChannelId,
channelName: 'Workout in progress',
channelDescription:
'Shows the rest countdown and the next set while a workout '
'runs. Kept silent on purpose: the break-end alert has its own '
'channel.',
onlyAlertOnce: true,
),
iosNotificationOptions: const IOSNotificationOptions(),
foregroundTaskOptions: ForegroundTaskOptions(
eventAction: ForegroundTaskEventAction.repeat(1000),
// NOTE: allowWakeLock and allowAutoRestart both default to true and
// the linter rejects restating them, but they are load-bearing.
// The wake lock is why the deadline still fires with the screen
// off; without it this whole feature is the bug it replaces.
),
);
}
@override
Future<bool> isRunning() => FlutterForegroundTask.isRunningService;
@override
Future<bool> hasNotificationPermission() async =>
await FlutterForegroundTask.checkNotificationPermission() ==
NotificationPermission.granted;
@override
Future<bool> requestNotificationPermission() async =>
await FlutterForegroundTask.requestNotificationPermission() ==
NotificationPermission.granted;
@override
Future<bool> start(BreakSnapshot snapshot) async {
if (await FlutterForegroundTask.isRunningService) {
await FlutterForegroundTask.stopService();
}
final result = await FlutterForegroundTask.startService(
serviceTypes: [ForegroundServiceTypes.dataSync],
notificationTitle: 'Workout ${snapshot.workoutType}',
notificationText: 'Starting…',
notificationButtons: [
for (final (i, id) in BreakNotificationAction.inButtonOrder.indexed)
NotificationButton(id: id, text: _buttonLabels[i]),
],
callback: breakServiceStartCallback,
);
if (result is! ServiceRequestSuccess) return false;
await push(snapshot);
return true;
}
@override
Future<void> push(BreakSnapshot snapshot) async =>
FlutterForegroundTask.sendDataToTask(snapshot.toMap());
@override
Future<void> stop() async {
if (await FlutterForegroundTask.isRunningService) {
await FlutterForegroundTask.stopService();
}
}
@override
void listenForDrainNudges(void Function() onNudge) {
stopListeningForDrainNudges();
_onNudge = onNudge;
FlutterForegroundTask.addTaskDataCallback(_handleTaskData);
}
@override
void stopListeningForDrainNudges() {
FlutterForegroundTask.removeTaskDataCallback(_handleTaskData);
_onNudge = null;
}
/// The service's nudge carries no payload -- see [BreakServicePort]. Any
/// message from the task isolate means "the queue has something in it".
void _handleTaskData(Object data) => _onNudge?.call();
// coverage:ignore-end
}

View File

@ -154,6 +154,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.0.7"
dbus:
dependency: transitive
description:
name: dbus
sha256: a48d5da28e89bd02196e80d81ed8d7954923d00a0f4a68cc20b575038f023383
url: "https://pub.dev"
source: hosted
version: "0.7.15"
device_info_plus:
dependency: transitive
description:
@ -215,6 +223,14 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
flutter_foreground_task:
dependency: "direct main"
description:
name: flutter_foreground_task
sha256: fe0e8c88fbdeb703161e20c54ffd10593fb112ccfa068c989ad2a93d28e4b976
url: "https://pub.dev"
source: hosted
version: "11.0.3"
flutter_launcher_icons:
dependency: "direct dev"
description:
@ -231,6 +247,46 @@ packages:
url: "https://pub.dev"
source: hosted
version: "6.0.0"
flutter_local_notifications:
dependency: "direct main"
description:
name: flutter_local_notifications
sha256: "357be7ff996dc272e2037c69c1bdd5d1bd21172219d55f8bd2e11aeea602e6d3"
url: "https://pub.dev"
source: hosted
version: "22.3.1"
flutter_local_notifications_linux:
dependency: transitive
description:
name: flutter_local_notifications_linux
sha256: "9ca97e63776f29ab1b955725c09999fc2c150523269db150c39274f2a43c5a8b"
url: "https://pub.dev"
source: hosted
version: "8.0.1"
flutter_local_notifications_platform_interface:
dependency: transitive
description:
name: flutter_local_notifications_platform_interface
sha256: "43c3761d916c9bd3d5c7ebbc44d82f4990329840c0c5d62ad5260cc1b5d399bd"
url: "https://pub.dev"
source: hosted
version: "12.2.0"
flutter_local_notifications_web:
dependency: transitive
description:
name: flutter_local_notifications_web
sha256: "516afaf97a2d1e67a036c6617321b00d205d72f7a67b6eccf936cd565f985878"
url: "https://pub.dev"
source: hosted
version: "1.0.0"
flutter_local_notifications_windows:
dependency: transitive
description:
name: flutter_local_notifications_windows
sha256: "6f43bdd03b171b7a90f22647506fea33e2bb12294b7c7c7a3d690e960a382945"
url: "https://pub.dev"
source: hosted
version: "3.1.1"
flutter_secure_storage:
dependency: "direct main"
description:
@ -538,7 +594,7 @@ packages:
source: hosted
version: "2.2.2"
path_provider_platform_interface:
dependency: transitive
dependency: "direct dev"
description:
name: path_provider_platform_interface
sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda"
@ -601,6 +657,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.2.2"
petitparser:
dependency: transitive
description:
name: petitparser
sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675"
url: "https://pub.dev"
source: hosted
version: "7.0.2"
platform:
dependency: transitive
description:
@ -823,6 +887,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.7.12"
timezone:
dependency: transitive
description:
name: timezone
sha256: "981d1020d6ef8fe1e7b3de5054e5b25579ae7c403d7734adc508ffc47668e9cb"
url: "https://pub.dev"
source: hosted
version: "0.11.1"
typed_data:
dependency: transitive
description:
@ -975,6 +1047,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.0"
xml:
dependency: transitive
description:
name: xml
sha256: "67f0aff7be013d107995e9b75bf4e7f2c3ef2dfdb2c8e68024bba0a7fd5756a4"
url: "https://pub.dev"
source: hosted
version: "7.0.1"
yaml:
dependency: transitive
description:

View File

@ -16,6 +16,14 @@ dependencies:
path: crdt_sync_dart
flutter:
sdk: flutter
# Keeps the rest-period deadline ticking with the screen off, and owns the
# ongoing status-bar notification the user records sets from. A Dart timer
# in the UI isolate cannot do this: Android throttles it and Doze suspends
# it, which is why the break-end cue used to just never fire.
flutter_foreground_task: 11.0.3
# The break-end alert itself, on its own high-importance channel so the OS
# rings even if the Flutter isolate is busy.
flutter_local_notifications: 22.3.1
flutter_secure_storage: 11.1.1
# One-tap sign-in for the sync account. App-side only: crdt_sync stays pure
@ -47,6 +55,11 @@ dev_dependencies:
flutter_lints: ^6.0.0
flutter_test:
sdk: flutter
# audioplayers copies an AssetSource into the temp dir before playing it,
# so a widget test that asserts the break-end cue actually sounded needs
# path_provider faked as well. Without it the play fails with
# MissingPluginException and is swallowed by _playBreakEndCue's catch.
path_provider_platform_interface: 2.1.3
very_good_analysis: ^11.0.0
flutter:

View File

@ -8,8 +8,37 @@ import 'dart:typed_data';
import 'package:audioplayers_platform_interface/audioplayers_platform_interface.dart';
import 'fake_path_provider.dart';
/// What the fake actually saw, so a test can assert the cue really played.
///
/// `AudioPlayer.play(AssetSource(...))` lands here as `setSourceUrl` followed
/// by `resume`, so a non-empty [resumedSources] is proof the break-end sound
/// was triggered — not merely that the code path compiled.
class FakeAudioRecorder {
/// Sources handed to the player, in order.
final sources = <String>[];
/// Sources that were actually played.
final resumedSources = <String>[];
/// When set, the next `play` fails — for exercising the cue's error path,
/// which is otherwise only reachable on a device with no audio route.
var failNextPlay = false;
/// Forgets everything recorded so far.
void clear() {
sources.clear();
resumedSources.clear();
}
}
class _FakeAudioplayersPlatform extends AudioplayersPlatformInterface {
_FakeAudioplayersPlatform(this.recorder);
final FakeAudioRecorder recorder;
final _controllers = <String, StreamController<AudioEvent>>{};
final _lastSource = <String, String>{};
StreamController<AudioEvent> _controllerFor(String playerId) =>
_controllers.putIfAbsent(
@ -32,7 +61,29 @@ class _FakeAudioplayersPlatform extends AudioplayersPlatformInterface {
Future<void> stop(String playerId) async {}
@override
Future<void> resume(String playerId) async {}
Future<void> resume(String playerId) async {
if (recorder.failNextPlay) {
recorder.failNextPlay = false;
throw Exception('no audio route');
}
recorder.resumedSources.add(_lastSource[playerId] ?? '');
// Complete immediately. A real play starts audioplayers'
// FramePositionUpdater, which registers a persistent frame callback and
// keeps ticking after the widget tree is torn down -- the test framework
// reports that as "An animation is still running even after the widget
// tree was disposed". The cue is a one-shot sound, so finishing it the
// instant it starts is both harmless and what the real thing does a
// second later.
//
// Emitted off the current microtask: audioplayers is still inside its own
// `addStream` when `resume` returns, and adding synchronously there throws
// "Bad state: Cannot add event while adding stream".
scheduleMicrotask(
() => _controllerFor(
playerId,
).add(const AudioEvent(eventType: AudioEventType.complete)),
);
}
@override
Future<void> release(String playerId) async {}
@ -62,6 +113,8 @@ class _FakeAudioplayersPlatform extends AudioplayersPlatformInterface {
bool? isLocal,
String? mimeType,
}) async {
_lastSource[playerId] = url;
recorder.sources.add(url);
_controllerFor(
playerId,
).add(const AudioEvent(eventType: AudioEventType.prepared, isPrepared: true));
@ -124,10 +177,16 @@ class _FakeGlobalAudioplayersPlatform
Stream<GlobalAudioEvent> getGlobalEventStream() => _controller.stream;
}
/// Installs fake `audioplayers` platform implementations. Call once from a
/// test's `setUp` before pumping any widget that creates an [AudioPlayer].
void installFakeAudioPlatform() {
AudioplayersPlatformInterface.instance = _FakeAudioplayersPlatform();
/// Installs fake `audioplayers` platform implementations and returns the
/// recorder they write to. Call once from a test's `setUp` before pumping
/// any widget that creates an [AudioPlayer].
FakeAudioRecorder installFakeAudioPlatform() {
// AssetSource playback goes through the temp directory, so the audio fake
// is not enough on its own -- see fake_path_provider.dart.
installFakePathProvider();
final recorder = FakeAudioRecorder();
AudioplayersPlatformInterface.instance = _FakeAudioplayersPlatform(recorder);
GlobalAudioplayersPlatformInterface.instance =
_FakeGlobalAudioplayersPlatform();
return recorder;
}

View File

@ -0,0 +1,132 @@
/// Recording fakes for the two break-service seams.
///
/// Both stand in for a platform channel, so they record calls rather than
/// performing them — the assertions are about what the handler and the
/// controller DECIDED, which is the part that has to be right.
library;
import 'package:workout_app/models/break_snapshot.dart';
import 'package:workout_app/services/break_notification_text.dart';
import 'package:workout_app/services/break_service_port.dart';
import 'package:workout_app/services/foreground_break_client.dart';
/// Stands in for the real service-isolate side effects.
class FakeBreakServicePort implements BreakServicePort {
/// Notification redraws, in order.
final drawn = <BreakNotificationCopy>[];
/// How many times the break-end alert fired.
var alerts = 0;
/// How many times the UI was nudged to drain.
var nudges = 0;
/// True once the service stopped itself.
var stopped = false;
/// True once plugins were registered in this isolate.
var ready = false;
@override
Future<void> ensureIsolateReady() async => ready = true;
@override
Future<void> updateNotification(BreakNotificationCopy copy) async =>
drawn.add(copy);
@override
Future<void> fireBreakEndAlert() async => alerts++;
@override
void nudgeMainToDrain() => nudges++;
@override
Future<void> finishAndStop() async => stopped = true;
}
/// Stands in for `flutter_foreground_task` on the UI side.
class FakeForegroundBreakClient implements ForegroundBreakClient {
/// Creates a fake. Defaults describe a healthy Android device.
FakeForegroundBreakClient({
this.isSupported = true,
this.permissionGranted = true,
this.grantOnRequest = true,
this.startSucceeds = true,
});
@override
bool isSupported;
/// Whether the permission is already held.
bool permissionGranted;
/// Whether asking for it succeeds.
bool grantOnRequest;
/// Whether `startService` reports success.
bool startSucceeds;
/// Snapshots pushed to the service, in order.
final pushed = <BreakSnapshot>[];
/// Calls recorded in order, for asserting sequencing.
final calls = <String>[];
/// The currently registered drain callback, if any.
void Function()? onNudge;
/// Whether a service from a previous launch is still alive.
var running = false;
@override
Future<void> init() async => calls.add('init');
@override
Future<bool> isRunning() async {
calls.add('isRunning');
return running;
}
@override
Future<bool> hasNotificationPermission() async {
calls.add('hasPermission');
return permissionGranted;
}
@override
Future<bool> requestNotificationPermission() async {
calls.add('requestPermission');
return permissionGranted = grantOnRequest;
}
@override
Future<bool> start(BreakSnapshot snapshot) async {
calls.add('start');
if (startSucceeds) pushed.add(snapshot);
return startSucceeds;
}
@override
Future<void> push(BreakSnapshot snapshot) async {
calls.add('push');
pushed.add(snapshot);
}
@override
Future<void> stop() async {
calls.add('stop');
running = false;
}
@override
void listenForDrainNudges(void Function() onNudge) {
calls.add('listen');
this.onNudge = onNudge;
}
@override
void stopListeningForDrainNudges() {
calls.add('unlisten');
onNudge = null;
}
}

View File

@ -0,0 +1,55 @@
/// Fakes `path_provider` so `AssetSource` playback works in widget tests.
///
/// `audioplayers` copies an asset into the temporary directory before it can
/// play it, so without this every break-end cue in a widget test dies with
/// `MissingPluginException` — swallowed by `_playBreakEndCue`'s catch, which
/// means the sound silently never played and no test could tell.
library;
import 'dart:io';
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
class _FakePathProvider extends PathProviderPlatform {
_FakePathProvider(this._root);
final String _root;
@override
Future<String?> getTemporaryPath() async => _root;
@override
Future<String?> getApplicationSupportPath() async => _root;
@override
Future<String?> getApplicationDocumentsPath() async => _root;
@override
Future<String?> getApplicationCachePath() async => _root;
@override
Future<String?> getLibraryPath() async => _root;
@override
Future<String?> getDownloadsPath() async => _root;
@override
Future<String?> getExternalStoragePath() async => _root;
@override
Future<List<String>?> getExternalCachePaths() async => [_root];
@override
Future<List<String>?> getExternalStoragePaths({
StorageDirectory? type,
}) async => [_root];
}
/// Points every `path_provider` lookup at a throwaway directory.
///
/// Returns the directory so a test can inspect what was written there.
Directory installFakePathProvider() {
final dir = Directory.systemTemp.createTempSync('workout_app_test_');
PathProviderPlatform.instance = _FakePathProvider(dir.path);
return dir;
}

View File

@ -0,0 +1,57 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/break_intent.dart';
void main() {
group('BreakIntentKind.tryParse', () {
test('round-trips every kind by name', () {
for (final kind in BreakIntentKind.values) {
expect(BreakIntentKind.tryParse(kind.name), kind);
}
});
test('returns null for anything else', () {
expect(BreakIntentKind.tryParse('finishWorkout'), isNull);
expect(BreakIntentKind.tryParse(''), isNull);
});
});
group('BreakIntent', () {
const intent = BreakIntent(
seq: 7,
kind: BreakIntentKind.minusRep,
exIdx: 1,
setIdx: 2,
tsMs: 1789432100123,
);
test('survives an encode/decode round trip', () {
final decoded = BreakIntent.tryDecode(intent.encode())!;
expect(decoded.seq, 7);
expect(decoded.kind, BreakIntentKind.minusRep);
expect(decoded.exIdx, 1);
expect(decoded.setIdx, 2);
expect(decoded.tsMs, 1789432100123);
expect(decoded.toString(), contains('#7'));
});
// Total rather than throwing: one bad entry must not wedge the drain loop
// and swallow every press behind it.
test('returns null for anything it cannot read', () {
const cases = <String>[
'not json at all',
'[]',
'"a string"',
'{"seq":"7","kind":"done","exIdx":0,"setIdx":0,"tsMs":1}',
'{"seq":7,"kind":7,"exIdx":0,"setIdx":0,"tsMs":1}',
'{"seq":7,"kind":"done","exIdx":"x","setIdx":0,"tsMs":1}',
'{"seq":7,"kind":"done","exIdx":0,"setIdx":null,"tsMs":1}',
'{"seq":7,"kind":"done","exIdx":0,"setIdx":0,"tsMs":"x"}',
'{"seq":7,"kind":"nope","exIdx":0,"setIdx":0,"tsMs":1}',
'{"kind":"done","exIdx":0,"setIdx":0,"tsMs":1}',
];
for (final raw in cases) {
expect(BreakIntent.tryDecode(raw), isNull, reason: raw);
}
});
});
}

View File

@ -0,0 +1,118 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/break_snapshot.dart';
const _full = BreakSnapshot(
workoutType: 'B',
breakEndMs: 1789432100123,
breakDurationSecs: 180,
breakLabel: 'Rest (3 min — well done!)',
breakForExIdx: 0,
breakForSetIdx: 1,
nextExIdx: 0,
nextSetIdx: 2,
nextExName: 'Squat',
nextSetNumber: 3,
nextTotalSets: 5,
nextReps: 5,
nextWeight: 42.5,
lastExIdx: 0,
lastSetIdx: 1,
setsRemaining: 7,
finished: true,
);
void main() {
test('survives the trip across the isolate boundary', () {
final decoded = BreakSnapshot.tryFromMap(_full.toMap())!;
expect(decoded.workoutType, 'B');
expect(decoded.breakEndMs, 1789432100123);
expect(decoded.breakLabel, contains('well done'));
expect(decoded.nextWeight, 42.5);
expect(decoded.setsRemaining, 7);
expect(decoded.finished, isTrue);
});
test('accepts an int weight — the channel may narrow a whole number', () {
final map = _full.toMap()..['nextWeight'] = 40;
expect(BreakSnapshot.tryFromMap(map)!.nextWeight, 40.0);
});
// Returning null rather than throwing keeps a bad payload from taking the
// foreground service isolate down mid-workout.
test('returns null rather than throwing on a malformed payload', () {
expect(BreakSnapshot.tryFromMap(const {}), isNull);
for (final key in _full.toMap().keys) {
if (key == 'finished') continue; // absent means false, by design
final map = _full.toMap()..remove(key);
expect(BreakSnapshot.tryFromMap(map), isNull, reason: 'missing $key');
}
expect(
BreakSnapshot.tryFromMap(_full.toMap()..['workoutType'] = 1),
isNull,
);
expect(
BreakSnapshot.tryFromMap(_full.toMap()..['nextExName'] = 1),
isNull,
);
expect(BreakSnapshot.tryFromMap(_full.toMap()..['breakLabel'] = 1), isNull);
expect(BreakSnapshot.tryFromMap(_full.toMap()..['nextWeight'] = 'x'), isNull);
expect(BreakSnapshot.tryFromMap(_full.toMap()..['breakEndMs'] = 'x'), isNull);
});
test('a missing finished flag reads as not finished', () {
final map = _full.toMap()..remove('finished');
expect(BreakSnapshot.tryFromMap(map)!.finished, isFalse);
});
test('hasBreak and hasNextSet describe what the buttons can do', () {
expect(_full.hasBreak, isTrue);
expect(_full.copyWith(breakEndMs: 0).hasBreak, isFalse);
expect(_full.hasNextSet, isTrue);
});
test('copyWith replaces only what it is given', () {
final recut = _full.copyWith(
breakEndMs: 1,
breakDurationSecs: 300,
breakLabel: 'Rest (5 min — keep going!)',
setsRemaining: 6,
finished: false,
);
expect(recut.breakEndMs, 1);
expect(recut.breakDurationSecs, 300);
expect(recut.breakLabel, contains('keep going'));
expect(recut.setsRemaining, 6);
expect(recut.finished, isFalse);
expect(recut.nextExName, 'Squat', reason: 'untouched fields carry over');
final same = _full.copyWith();
expect(same.breakEndMs, _full.breakEndMs);
expect(same.breakLabel, _full.breakLabel);
expect(same.breakDurationSecs, _full.breakDurationSecs);
expect(same.setsRemaining, _full.setsRemaining);
expect(same.finished, _full.finished);
});
test('no next set is representable', () {
const done = BreakSnapshot(
workoutType: 'A',
breakEndMs: 0,
breakDurationSecs: 0,
breakLabel: '',
breakForExIdx: -1,
breakForSetIdx: -1,
nextExIdx: -1,
nextSetIdx: -1,
nextExName: '',
nextSetNumber: 0,
nextTotalSets: 0,
nextReps: 0,
nextWeight: 0,
lastExIdx: -1,
lastSetIdx: -1,
setsRemaining: 0,
);
expect(done.hasNextSet, isFalse);
expect(done.hasBreak, isFalse);
});
}

View File

@ -8,6 +8,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/screens/workout_screen.dart';
import 'package:workout_app/services/foreground_break_client.dart';
import 'package:workout_app/ui/theme.dart';
Map<String, dynamic> completeSaved() => {
@ -24,6 +25,33 @@ Map<String, dynamic> completeSaved() => {
'warmupTapped': [false, false],
};
/// A saved session parked mid-rest, [secondsFromNow] from its deadline.
///
/// Negative values describe a break that ended while the app was away — the
/// case that used to be dropped in silence.
Map<String, dynamic> savedWithBreak(int secondsFromNow, {int durationSecs = 180}) => {
'workoutType': 'A',
'startTimeMs': DateTime.now()
.subtract(const Duration(minutes: 5))
.millisecondsSinceEpoch,
'tapped': [
[true, false, false],
[false, false, false],
],
'doneReps': [
[5, 5, 5],
[5, 5, 5],
],
'warmupTapped': [false, false],
'breakForExIdx': 0,
'breakForSetIdx': 0,
'breakLabel': 'Rest (3 min — well done!)',
'breakDurationSecs': durationSecs,
'breakEndMs': DateTime.now()
.add(Duration(seconds: secondsFromNow))
.millisecondsSinceEpoch,
};
const testExercises = [
Exercise(name: 'Squat', sets: 3, reps: 5, weight: 20.0),
Exercise(name: 'Press', sets: 3, reps: 5, weight: 15.0),
@ -33,12 +61,14 @@ Widget wrapWorkout({
String type = 'A',
List<Exercise> exercises = testExercises,
Map<String, dynamic>? savedState,
ForegroundBreakClient? breakClient,
}) => MaterialApp(
theme: buildAppTheme(),
home: WorkoutScreen(
workoutType: type,
exercises: exercises,
savedState: savedState,
breakClient: breakClient,
),
);

View File

@ -0,0 +1,146 @@
// Restoring a workout whose rest period was running -- or had already ended --
// while the app was not.
//
// Split out of workout_breaks_test.dart to stay under the repo's 250-line cap.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/widgets/break_banner.dart';
import '../fake_audio_platform.dart';
import '../fake_secure_storage.dart';
import '_workout_screen_test_fixtures.dart';
void main() {
late FakeAudioRecorder audio;
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
StorageService.resetForTesting();
await StorageService.init();
installFakeSecureStorage();
audio = installFakeAudioPlatform();
});
// ── Restoring a session whose rest period already ended ────────────────────
//
// This branch used to be an implicit no-op: `_restoreFromSaved` rearmed the
// ticker only `if (remaining > 0)`, so a break that ended while the app was
// dead produced no cue and — worse — no log. "The break never rang" was
// indistinguishable from "there was no break".
testWidgets('a break that ended while the app was away still plays its cue', (
tester,
) async {
await pumpWorkout(tester, wrapWorkout(savedState: savedWithBreak(-45)));
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 300)),
);
await tester.pump();
expect(
audio.resumedSources.where((s) => s.contains('break_end')),
isNotEmpty,
reason: 'the rest ended 45s ago, inside the grace window, so the user '
'should hear the cue they were waiting for',
);
expect(find.byType(BreakBanner), findsNothing);
});
testWidgets('a long-expired break is not replayed, only logged', (
tester,
) async {
await pumpWorkout(tester, wrapWorkout(savedState: savedWithBreak(-7200)));
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 300)),
);
await tester.pump();
expect(
audio.resumedSources.where((s) => s.contains('break_end')),
isEmpty,
reason: 'two hours late is past the grace window — replaying the sound '
'would just be startling',
);
expect(find.byType(BreakBanner), findsNothing);
});
testWidgets('a break still running is restored and keeps counting', (
tester,
) async {
await pumpWorkout(tester, wrapWorkout(savedState: savedWithBreak(90)));
expect(find.byType(BreakBanner), findsOneWidget);
expect(find.textContaining('well done'), findsOneWidget);
expect(
audio.resumedSources.where((s) => s.contains('break_end')),
isEmpty,
reason: 'the rest has not ended yet',
);
});
testWidgets('resuming re-reads the deadline and ends a rest that is due', (
tester,
) async {
// A backgrounded app gets no ticks, so the countdown is stale the instant
// it comes back. Waiting for the next tick would delay the cue by a second
// on a good day and forever on a Dozing phone.
await pumpWorkout(tester, wrapWorkout(savedState: savedWithBreak(1)));
expect(find.byType(BreakBanner), findsOneWidget);
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 1200)),
);
audio.clear();
await tester.runAsync(() async {
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await Future<void>.delayed(const Duration(milliseconds: 300));
});
await tester.pump();
expect(find.byType(BreakBanner), findsNothing);
});
testWidgets('resuming with no rest running is harmless', (tester) async {
await pumpWorkout(tester, wrapWorkout());
await tester.runAsync(() async {
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await Future<void>.delayed(const Duration(milliseconds: 200));
});
await tester.pump();
expect(find.byType(BreakBanner), findsNothing);
});
testWidgets('a dead audio route does not take the workout down with it', (
tester,
) async {
// The cue is fire-and-forget, but it must still SAY it failed -- a rest
// that ends in silence is indistinguishable from a timer that never fired.
final logged = <String>[];
final previous = debugPrint;
// Restored inside the body, not in a tearDown: flutter_test asserts that
// no foundation debug variable is still overridden when the body returns.
debugPrint = (message, {wrapWidth}) => logged.add(message ?? '');
audio.failNextPlay = true;
await pumpWorkout(tester, wrapWorkout(savedState: savedWithBreak(-30)));
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 300)),
);
await tester.pump();
debugPrint = previous;
expect(
logged.where((m) => m.contains('break-end sound failed to play')),
isNotEmpty,
reason: 'a cue that cannot sound must say so, not fail in silence',
);
expect(find.byType(BreakBanner), findsNothing);
expect(tester.takeException(), isNull);
});
}

View File

@ -20,6 +20,8 @@ import '../fake_secure_storage.dart';
import '_workout_screen_test_fixtures.dart';
void main() {
late FakeAudioRecorder audio;
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
@ -34,8 +36,9 @@ void main() {
// MissingPluginException as an unhandled Future error.
installFakeSecureStorage();
// The break-end sound creates a real AudioPlayer; fake its platform
// channels too, for the same reason as above.
installFakeAudioPlatform();
// channels too, for the same reason as above. The recorder is what
// makes "the cue actually played" an assertion rather than a hope.
audio = installFakeAudioPlatform();
});
// Interaction taps trigger `unawaited(_saveActiveSession())` (a sqflite write)

View File

@ -0,0 +1,193 @@
// Notification presses the workout has already moved past, and the service's
// lifetime rules.
//
// Split out of workout_screen_intents_test.dart to stay under the repo's
// 250-line cap; the shared setup is duplicated rather than exported because
// each test file owns its own fakes.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/break_intent.dart';
import 'package:workout_app/models/break_snapshot.dart';
import 'package:workout_app/services/break_intent_queue.dart';
import 'package:workout_app/services/break_intent_store.dart';
import 'package:workout_app/services/storage_service.dart';
import '../fake_audio_platform.dart';
import '../fake_break_service.dart';
import '../fake_secure_storage.dart';
import '_workout_screen_test_fixtures.dart';
void main() {
late FakeForegroundBreakClient client;
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
StorageService.resetForTesting();
await StorageService.init();
installFakeSecureStorage();
installFakeAudioPlatform();
SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync
.empty();
client = FakeForegroundBreakClient();
});
Future<void> seed(List<(BreakIntentKind, int, int)> presses) async {
final queue = BreakIntentQueue(PrefsBreakIntentStore());
for (final (kind, ex, set) in presses) {
await queue.enqueue(
kind: kind,
exIdx: ex,
setIdx: set,
now: DateTime.now(),
);
}
}
Future<void> pump(WidgetTester tester, {Map<String, dynamic>? saved}) =>
pumpWorkout(tester, wrapWorkout(savedState: saved, breakClient: client));
BreakSnapshot lastPushed() => client.pushed.last;
Future<void> nudge(WidgetTester tester) async {
await tester.runAsync(() async {
client.onNudge!();
await Future<void>.delayed(const Duration(milliseconds: 400));
});
await tester.pump();
}
group('presses the workout has moved past are dropped, not forced', () {
Future<void> expectNoChange(
WidgetTester tester,
List<(BreakIntentKind, int, int)> presses,
) async {
final before = lastPushed().setsRemaining;
await seed(presses);
await nudge(tester);
expect(lastPushed().setsRemaining, before);
}
testWidgets('an exercise index this workout does not have', (tester) async {
await pump(tester);
await expectNoChange(tester, [(BreakIntentKind.done, 99, 0)]);
});
testWidgets('a set index this exercise does not have', (tester) async {
await pump(tester);
await expectNoChange(tester, [(BreakIntentKind.done, 0, 99)]);
});
testWidgets('a negative index', (tester) async {
await pump(tester);
await expectNoChange(tester, [(BreakIntentKind.minusRep, -1, 0)]);
});
testWidgets('Done on a set that is already recorded', (tester) async {
await pump(tester, saved: savedWithBreak(90));
await expectNoChange(tester, [(BreakIntentKind.done, 0, 0)]);
});
testWidgets('− 1 rep on a set that was never recorded', (tester) async {
await pump(tester);
await expectNoChange(tester, [(BreakIntentKind.minusRep, 1, 2)]);
});
testWidgets('Skip break with no rest running', (tester) async {
await pump(tester);
await expectNoChange(tester, [(BreakIntentKind.skipBreak, 0, 0)]);
});
});
testWidgets('warns on screen when notifications were refused', (
tester,
) async {
// A foreground service whose POST_NOTIFICATIONS is denied still RUNS but
// shows nothing -- no alert, no status bar, no error. That is the exact
// silent failure this whole feature exists to remove, so the user is told.
client
..permissionGranted = false
..grantOnRequest = false;
await pump(tester);
expect(
find.textContaining('Notifications are off'),
findsOneWidget,
);
});
testWidgets('no warning when notifications were allowed', (tester) async {
await pump(tester);
expect(find.textContaining('Notifications are off'), findsNothing);
});
testWidgets('a press that arrives after the workout is finished is dropped', (
tester,
) async {
await pump(tester, saved: completeSaved());
// Whole flow on the real loop: _confirmFinish's showDialog resumes into
// _finishWorkout, which does several sqflite writes.
await tester.runAsync(() async {
await tester.tap(find.widgetWithText(TextButton, 'Finish'));
await Future<void>.delayed(const Duration(milliseconds: 200));
await tester.pump();
await tester.tap(find.widgetWithText(TextButton, 'Finish').last);
await Future<void>.delayed(const Duration(milliseconds: 800));
await tester.pump();
});
await tester.pump();
// Finishing stops the service, so there is no nudge callback left to
// fire -- a press can now only arrive via the resume path, e.g. one made
// moments before the user hit Finish.
expect(client.onNudge, isNull, reason: 'the service was stopped');
await seed([(BreakIntentKind.done, 0, 0)]);
await tester.runAsync(() async {
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await Future<void>.delayed(const Duration(milliseconds: 400));
});
await tester.pump();
expect(tester.takeException(), isNull);
});
testWidgets('leaving the screen does NOT stop the service', (tester) async {
// The back button pops this screen while the workout carries on in the
// database. Stopping the service here killed the countdown and the
// notification with it -- silently restoring the original bug. Verified
// on-device 2026-09-12: BACK took the service down.
await pump(tester);
expect(client.calls, contains('start'));
await tester.runAsync(() async {
await tester.pumpWidget(const SizedBox.shrink());
await Future<void>.delayed(const Duration(milliseconds: 300));
});
expect(
client.calls,
isNot(contains('stop')),
reason: 'the rest deadline must survive leaving the workout screen',
);
});
testWidgets('finishing the workout DOES stop the service', (tester) async {
await pump(tester, saved: completeSaved());
await tester.runAsync(() async {
await tester.tap(find.widgetWithText(TextButton, 'Finish'));
await Future<void>.delayed(const Duration(milliseconds: 200));
await tester.pump();
await tester.tap(find.widgetWithText(TextButton, 'Finish').last);
await Future<void>.delayed(const Duration(milliseconds: 800));
await tester.pump();
});
await tester.pump();
expect(client.calls, contains('stop'));
});
}

View File

@ -0,0 +1,145 @@
// The screen side of the status-bar notification: describing the workout for
// the service, and applying the presses that come back from it.
//
// The real client reports isSupported == false off Android, so these inject a
// fake one -- otherwise the whole notification path is dead code on the test
// host and none of these rules would ever be exercised.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/break_intent.dart';
import 'package:workout_app/models/break_snapshot.dart';
import 'package:workout_app/services/break_intent_queue.dart';
import 'package:workout_app/services/break_intent_store.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/widgets/break_banner.dart';
import 'package:workout_app/widgets/rep_circle.dart';
import '../fake_audio_platform.dart';
import '../fake_break_service.dart';
import '../fake_secure_storage.dart';
import '_workout_screen_test_fixtures.dart';
void main() {
late FakeForegroundBreakClient client;
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
StorageService.resetForTesting();
await StorageService.init();
installFakeSecureStorage();
installFakeAudioPlatform();
SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync
.empty();
client = FakeForegroundBreakClient();
});
/// Queues presses exactly as the foreground service isolate would.
Future<void> seed(List<(BreakIntentKind, int, int)> presses) async {
final queue = BreakIntentQueue(PrefsBreakIntentStore());
for (final (kind, ex, set) in presses) {
await queue.enqueue(
kind: kind,
exIdx: ex,
setIdx: set,
now: DateTime.now(),
);
}
}
Future<void> pump(WidgetTester tester, {Map<String, dynamic>? saved}) =>
pumpWorkout(tester, wrapWorkout(savedState: saved, breakClient: client));
BreakSnapshot lastPushed() => client.pushed.last;
/// Fires the service's drain nudge and lets the resulting work finish.
///
/// The screen's handler is `unawaited(_drainIntents())`, and draining does
/// real sqflite and prefs I/O -- so the pump has to happen on the real clock
/// inside runAsync, exactly like the tap helpers in the fixtures file.
Future<void> nudge(WidgetTester tester) async {
await tester.runAsync(() async {
client.onNudge!();
await Future<void>.delayed(const Duration(milliseconds: 400));
});
await tester.pump();
}
testWidgets('describes the workout for the notification on every save', (
tester,
) async {
await pump(tester);
expect(client.pushed, isNotEmpty, reason: 'pushed as the service starts');
var snap = lastPushed();
expect(snap.workoutType, 'A');
expect(snap.nextExName, 'Squat');
expect(snap.nextSetNumber, 1);
expect(snap.nextTotalSets, 3);
expect(snap.nextReps, 5);
expect(snap.setsRemaining, 6);
expect(snap.hasBreak, isFalse);
expect(snap.lastExIdx, -1, reason: 'nothing recorded yet');
await tapReal(tester, find.byType(RepCircle).first);
snap = lastPushed();
expect(snap.hasBreak, isTrue);
expect(snap.setsRemaining, 5);
expect(snap.nextSetNumber, 2, reason: 'next set of the same exercise');
expect(snap.lastExIdx, 0);
expect(snap.lastSetIdx, 0);
});
testWidgets('Done from the notification records the set and starts a rest', (
tester,
) async {
await pump(tester);
await seed([(BreakIntentKind.done, 0, 0)]);
await nudge(tester);
expect(find.byType(BreakBanner), findsOneWidget);
expect(lastPushed().setsRemaining, 5);
});
testWidgets('Done during a rest ends the rest first, then records', (
tester,
) async {
await pump(tester, saved: savedWithBreak(90));
expect(find.byType(BreakBanner), findsOneWidget);
// In-app, tapping a NEW set mid-break is refused. From the notification it
// means "I am done resting and done with the set" -- both taps at once.
await seed([(BreakIntentKind.done, 0, 1)]);
await nudge(tester);
expect(lastPushed().setsRemaining, lessThan(5));
});
testWidgets('− 1 rep stretches the rest from 3 minutes to 5', (tester) async {
await pump(tester, saved: savedWithBreak(170));
expect(find.textContaining('well done'), findsOneWidget);
await seed([(BreakIntentKind.minusRep, 0, 0)]);
await nudge(tester);
expect(find.textContaining('keep going'), findsOneWidget);
expect(lastPushed().breakDurationSecs, 300);
});
testWidgets('Skip break from the notification ends the rest', (tester) async {
await pump(tester, saved: savedWithBreak(90));
expect(find.byType(BreakBanner), findsOneWidget);
await seed([(BreakIntentKind.skipBreak, 0, 0)]);
await nudge(tester);
expect(find.byType(BreakBanner), findsNothing);
});
}

View File

@ -0,0 +1,71 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/break_clock.dart';
void main() {
final start = DateTime(2026, 9, 12, 14);
group('BreakClock', () {
test('reports the full duration for its whole first second', () {
final clock = BreakClock.startingAt(start, 180);
// Rounded up, matching what the old decrementing counter displayed.
expect(clock.remainingSecsAt(start), 180);
expect(
clock.remainingSecsAt(start.add(const Duration(milliseconds: 500))),
180,
);
expect(clock.remainingSecsAt(start.add(const Duration(seconds: 1))), 179);
});
test('floors at zero rather than going negative', () {
final clock = BreakClock.startingAt(start, 60);
expect(clock.remainingSecsAt(start.add(const Duration(seconds: 60))), 0);
expect(clock.remainingSecsAt(start.add(const Duration(hours: 3))), 0);
});
test('expires exactly at the deadline, not a tick later', () {
final clock = BreakClock.startingAt(start, 60);
final end = start.add(const Duration(seconds: 60));
expect(clock.expiredAt(end.subtract(const Duration(microseconds: 1))),
isFalse);
expect(clock.expiredAt(end), isTrue);
});
test('reports how late it is, and zero while still running', () {
final clock = BreakClock.startingAt(start, 60);
expect(clock.secondsOverdueAt(start.add(const Duration(seconds: 30))), 0);
expect(clock.secondsOverdueAt(start.add(const Duration(seconds: 105))), 45);
});
test('withDuration re-cuts from the original start, not from now', () {
// This is the 3-min -> 5-min switch. A restart would hand the user two
// extra minutes of rest they never earned.
final clock = BreakClock.startingAt(start, 180);
final longer = clock.withDuration(300);
expect(longer.startTime, start);
expect(longer.endTime, start.add(const Duration(seconds: 300)));
expect(
longer.remainingSecsAt(start.add(const Duration(seconds: 21))),
279,
);
});
test('startTime is derived from the deadline', () {
final clock = BreakClock(
endTime: start.add(const Duration(seconds: 180)),
durationSecs: 180,
);
expect(clock.startTime, start);
});
test('value equality and hashCode track both fields', () {
final a = BreakClock.startingAt(start, 180);
final b = BreakClock.startingAt(start, 180);
final c = BreakClock.startingAt(start, 300);
expect(a, b);
expect(a.hashCode, b.hashCode);
expect(a, isNot(c));
expect(a, isNot(Object()));
expect(a.toString(), contains('180s'));
});
});
}

View File

@ -0,0 +1,202 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/break_intent.dart';
import 'package:workout_app/services/break_intent_queue.dart';
import 'package:workout_app/services/break_intent_store.dart';
/// An in-memory [BreakIntentStore] that can also be corrupted on purpose.
class _MemStore implements BreakIntentStore {
final ints = <String, int>{};
final lists = <String, List<String>>{};
@override
Future<int> readInt(String key) async => ints[key] ?? 0;
@override
Future<void> writeInt(String key, int value) async => ints[key] = value;
@override
Future<List<String>> readStringList(String key) async =>
lists[key] ?? const [];
@override
Future<void> writeStringList(String key, List<String> value) async =>
lists[key] = List.of(value);
}
void main() {
late _MemStore store;
late BreakIntentQueue queue;
final now = DateTime(2026, 9, 12, 14);
setUp(() {
store = _MemStore();
queue = BreakIntentQueue(store);
});
Future<List<BreakIntent>> drainCollecting() async {
final applied = <BreakIntent>[];
await queue.drain((intent) async => applied.add(intent));
return applied;
}
test('allocates sequence numbers from one, upward', () async {
final a = await queue.enqueue(
kind: BreakIntentKind.done,
exIdx: 0,
setIdx: 0,
now: now,
);
final b = await queue.enqueue(
kind: BreakIntentKind.skipBreak,
exIdx: 0,
setIdx: 1,
now: now,
);
expect(a.seq, 1);
expect(b.seq, 2);
expect(store.ints[BreakIntentQueue.seqKey], 2);
});
test('applies pending presses oldest first and then prunes them', () async {
await queue.enqueue(
kind: BreakIntentKind.done,
exIdx: 0,
setIdx: 0,
now: now,
);
await queue.enqueue(
kind: BreakIntentKind.skipBreak,
exIdx: 0,
setIdx: 1,
now: now,
);
final applied = await drainCollecting();
expect(applied.map((i) => i.seq), [1, 2]);
expect(store.ints[BreakIntentQueue.lastAppliedKey], 2);
expect(store.lists[BreakIntentQueue.intentsKey], isEmpty);
});
test('a second drain applies nothing — presses are exactly-once', () async {
await queue.enqueue(
kind: BreakIntentKind.done,
exIdx: 0,
setIdx: 0,
now: now,
);
expect((await drainCollecting()).length, 1);
expect(await drainCollecting(), isEmpty);
});
// Two presses of the same button are two user actions, not a duplicate.
test('two identical minusRep presses both apply, in order', () async {
for (var i = 0; i < 2; i++) {
await queue.enqueue(
kind: BreakIntentKind.minusRep,
exIdx: 0,
setIdx: 1,
now: now,
);
}
final applied = await drainCollecting();
expect(applied.length, 2);
expect(applied.map((i) => i.seq), [1, 2]);
});
test('commits lastApplied per intent, so a crash mid-drain resumes',
() async {
for (var i = 0; i < 3; i++) {
await queue.enqueue(
kind: BreakIntentKind.done,
exIdx: 0,
setIdx: i,
now: now,
);
}
// Blow up on the second one, as a process death would.
await expectLater(
queue.drain((intent) async {
if (intent.seq == 2) throw StateError('killed mid-drain');
}),
throwsStateError,
);
expect(store.ints[BreakIntentQueue.lastAppliedKey], 1);
final applied = await drainCollecting();
expect(applied.map((i) => i.seq), [2, 3], reason: 'resumes, never replays');
});
test('skips an unreadable entry without losing the ones behind it', () async {
await queue.enqueue(
kind: BreakIntentKind.done,
exIdx: 0,
setIdx: 0,
now: now,
);
store.lists[BreakIntentQueue.intentsKey] = [
'not json',
...store.lists[BreakIntentQueue.intentsKey]!,
];
final applied = await drainCollecting();
expect(applied.map((i) => i.seq), [1]);
expect(store.lists[BreakIntentQueue.intentsKey], isEmpty);
});
test('drops the oldest presses once the queue overflows', () async {
for (var i = 0; i < BreakIntentQueue.maxEntries + 3; i++) {
await queue.enqueue(
kind: BreakIntentKind.done,
exIdx: 0,
setIdx: 0,
now: now,
);
}
final entries = store.lists[BreakIntentQueue.intentsKey]!;
expect(entries.length, BreakIntentQueue.maxEntries);
expect(BreakIntent.tryDecode(entries.first)!.seq, 4);
});
test('a nudge arriving mid-drain schedules one more pass, not a nested one',
() async {
await queue.enqueue(
kind: BreakIntentKind.done,
exIdx: 0,
setIdx: 0,
now: now,
);
final applied = <int>[];
var reentered = false;
await queue.drain((intent) async {
applied.add(intent.seq);
if (reentered) return;
reentered = true;
// Arrives while the first drain is still running.
await queue.enqueue(
kind: BreakIntentKind.minusRep,
exIdx: 0,
setIdx: 0,
now: now,
);
await queue.drain((i) async => applied.add(i.seq));
});
expect(applied, [1, 2], reason: 'each press applied exactly once');
});
test('an empty queue drains without touching lastApplied', () async {
expect(await drainCollecting(), isEmpty);
expect(store.ints[BreakIntentQueue.lastAppliedKey], isNull);
});
test('clear forgets pending presses and skips them forever after', () async {
await queue.enqueue(
kind: BreakIntentKind.done,
exIdx: 0,
setIdx: 0,
now: now,
);
await queue.clear();
expect(await drainCollecting(), isEmpty);
expect(store.lists[BreakIntentQueue.intentsKey], isEmpty);
expect(store.ints[BreakIntentQueue.lastAppliedKey], 1);
});
}

View File

@ -0,0 +1,44 @@
// Exercises the REAL PrefsBreakIntentStore, not a fake: the point of this file
// is to prove the SharedPreferencesAsync wiring works, since getting it wrong
// (the legacy cached API) would make every notification button silently dead.
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
import 'package:workout_app/services/break_intent_store.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late PrefsBreakIntentStore store;
setUp(() {
SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync
.empty();
store = PrefsBreakIntentStore();
});
test('an unwritten int reads as zero, not null', () async {
expect(await store.readInt('workout.break.seq'), 0);
});
test('an unwritten list reads as empty, not null', () async {
expect(await store.readStringList('workout.break.intents'), isEmpty);
});
test('ints round-trip', () async {
await store.writeInt('workout.break.seq', 42);
expect(await store.readInt('workout.break.seq'), 42);
});
test('string lists round-trip', () async {
await store.writeStringList('workout.break.intents', ['a', 'b']);
expect(await store.readStringList('workout.break.intents'), ['a', 'b']);
});
test('accepts an injected SharedPreferencesAsync', () async {
final injected = PrefsBreakIntentStore(SharedPreferencesAsync());
await injected.writeInt('k', 3);
expect(await injected.readInt('k'), 3);
});
}

View File

@ -0,0 +1,107 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/break_snapshot.dart';
import 'package:workout_app/services/break_notification_text.dart';
BreakSnapshot snap({
int breakEndMs = 0,
int breakDurationSecs = 0,
int nextExIdx = 0,
int nextSetIdx = 2,
String nextExName = 'Squat',
int nextSetNumber = 3,
int nextTotalSets = 5,
int nextReps = 5,
double nextWeight = 40,
int setsRemaining = 3,
bool finished = false,
}) => BreakSnapshot(
workoutType: 'A',
breakEndMs: breakEndMs,
breakDurationSecs: breakDurationSecs,
breakLabel: 'Rest',
breakForExIdx: 0,
breakForSetIdx: 1,
nextExIdx: nextExIdx,
nextSetIdx: nextSetIdx,
nextExName: nextExName,
nextSetNumber: nextSetNumber,
nextTotalSets: nextTotalSets,
nextReps: nextReps,
nextWeight: nextWeight,
lastExIdx: 0,
lastSetIdx: 1,
setsRemaining: setsRemaining,
finished: finished,
);
void main() {
final now = DateTime(2026, 9, 12, 14);
test('shows the countdown in the title, which Android shows collapsed', () {
final copy = BreakNotificationText.render(
snap(
breakEndMs: now.add(const Duration(seconds: 107)).millisecondsSinceEpoch,
breakDurationSecs: 180,
),
now,
);
expect(copy.title, 'Workout A · break 1:47');
expect(copy.body, 'Next: Squat — set 3/5\n5 reps @ 40 kg');
});
test('says the break is over once the deadline has passed', () {
final copy = BreakNotificationText.render(
snap(
breakEndMs: now.subtract(const Duration(seconds: 5)).millisecondsSinceEpoch,
breakDurationSecs: 180,
),
now,
);
expect(copy.title, 'Workout A · break over');
});
test('says lift when no rest is running', () {
expect(BreakNotificationText.render(snap(), now).title, 'Workout A · lift');
});
test('says so when every set is recorded', () {
final copy = BreakNotificationText.render(
snap(nextExIdx: -1, nextSetIdx: -1, setsRemaining: 0),
now,
);
expect(copy.body, 'Every set is done — finish the workout.');
});
test('a finished workout asks to be saved', () {
final copy = BreakNotificationText.render(snap(finished: true), now);
expect(copy.title, 'Workout complete');
expect(copy.body, 'Open the app to save it.');
});
test('drops a pointless trailing zero from the weight', () {
expect(BreakNotificationText.formatWeight(40), '40');
expect(BreakNotificationText.formatWeight(22.5), '22.5');
expect(BreakNotificationText.formatWeight(7.5), '7.5');
expect(BreakNotificationText.formatWeight(0), '0');
});
test('formats the countdown as m:ss', () {
expect(BreakNotificationText.formatMmSs(0), '0:00');
expect(BreakNotificationText.formatMmSs(9), '0:09');
expect(BreakNotificationText.formatMmSs(60), '1:00');
expect(BreakNotificationText.formatMmSs(107), '1:47');
expect(BreakNotificationText.formatMmSs(300), '5:00');
});
// The service only redraws when the text changed, so equality is what keeps
// the notification from flickering once a second.
test('copy compares by value', () {
const a = BreakNotificationCopy('t', 'b');
const b = BreakNotificationCopy('t', 'b');
expect(a, b);
expect(a.hashCode, b.hashCode);
expect(a, isNot(const BreakNotificationCopy('t', 'other')));
expect(a, isNot(Object()));
expect(a.toString(), contains('t | b'));
});
}

View File

@ -0,0 +1,69 @@
// The two plugin-backed implementations are almost entirely `coverage:ignore`d
// -- every method body is a platform-channel call that cannot run on the test
// host. Their CONSTRUCTORS are deliberately outside those blocks, and this file
// exists to execute them: that gives each file a genuinely-hit line in
// lcov.info, so `check_flutter_coverage.sh`'s "every lib file must appear"
// guard is satisfied by real coverage rather than by an empty record.
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/break_service_port.dart';
import 'package:workout_app/services/break_service_port_flutter.dart';
import 'package:workout_app/services/foreground_break_client.dart';
import 'package:workout_app/services/foreground_break_client_flutter.dart';
void main() {
test('the service-isolate port can be constructed', () {
expect(FlutterBreakServicePort(), isNotNull);
});
test('the UI-side client can be constructed', () {
final client = FlutterForegroundBreakClient();
expect(client, isNotNull);
// Linux test host: there is no foreground service here, which is exactly
// why every other method on this class is unreachable from a test.
expect(client.isSupported, isFalse);
});
test('the alert channel id is versioned', () {
// Android freezes a channel's sound and importance on first creation, so
// a wrong setting can only ever be fixed by moving to a new id.
expect(kBreakEndChannelId, endsWith('_v1'));
expect(kWorkoutOngoingChannelId, endsWith('_v1'));
expect(kBreakEndNotificationId, isNot(kWorkoutDoneNotificationId));
});
test('the three button ids are distinct and in display order', () {
// Android allows at most three action buttons, which is why Done records
// the full target and − 1 rep walks down from there: rep targets run from
// 5 to 30 across the plan, so a button per count is impossible.
expect(BreakNotificationAction.inButtonOrder, [
BreakNotificationAction.done,
BreakNotificationAction.minusRep,
BreakNotificationAction.skipBreak,
]);
expect(BreakNotificationAction.inButtonOrder.toSet(), hasLength(3));
});
test('start results answer the two questions the screen asks', () {
expect(BreakServiceStartResult.started.serviceRunning, isTrue);
expect(
BreakServiceStartResult.startedWithoutNotification.serviceRunning,
isTrue,
reason: 'the isolate still holds the wake lock and still plays the cue',
);
expect(BreakServiceStartResult.failed.serviceRunning, isFalse);
expect(BreakServiceStartResult.unsupported.serviceRunning, isFalse);
expect(
BreakServiceStartResult.startedWithoutNotification
.needsPermissionWarning,
isTrue,
);
for (final other in [
BreakServiceStartResult.started,
BreakServiceStartResult.failed,
BreakServiceStartResult.unsupported,
]) {
expect(other.needsPermissionWarning, isFalse);
}
});
}

View File

@ -0,0 +1,217 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/break_intent.dart';
import 'package:workout_app/models/break_snapshot.dart';
import 'package:workout_app/services/break_intent_queue.dart';
import 'package:workout_app/services/break_intent_store.dart';
import 'package:workout_app/services/break_service_controller.dart';
import 'package:workout_app/services/foreground_break_client.dart';
import '../fake_break_service.dart';
class _MemStore implements BreakIntentStore {
final ints = <String, int>{};
final lists = <String, List<String>>{};
@override
Future<int> readInt(String key) async => ints[key] ?? 0;
@override
Future<void> writeInt(String key, int value) async => ints[key] = value;
@override
Future<List<String>> readStringList(String key) async =>
lists[key] ?? const [];
@override
Future<void> writeStringList(String key, List<String> value) async =>
lists[key] = List.of(value);
}
const _snapshot = BreakSnapshot(
workoutType: 'A',
breakEndMs: 0,
breakDurationSecs: 0,
breakLabel: '',
breakForExIdx: -1,
breakForSetIdx: -1,
nextExIdx: 0,
nextSetIdx: 0,
nextExName: 'Squat',
nextSetNumber: 1,
nextTotalSets: 5,
nextReps: 5,
nextWeight: 40,
lastExIdx: -1,
lastSetIdx: -1,
setsRemaining: 5,
);
void main() {
late FakeForegroundBreakClient client;
late _MemStore store;
late BreakIntentQueue queue;
late BreakServiceController controller;
setUp(() {
client = FakeForegroundBreakClient();
store = _MemStore();
queue = BreakIntentQueue(store);
controller = BreakServiceController(client, queue);
});
Future<BreakServiceStartResult> start() =>
controller.start(_snapshot, onDrainNudge: () {});
test('starts and reports success when the permission is already held',
() async {
expect(await start(), BreakServiceStartResult.started);
expect(controller.isStarted, isTrue);
expect(client.calls, ['init', 'hasPermission', 'listen', 'start']);
});
test('asks for the permission when it is not held yet', () async {
client.permissionGranted = false;
expect(await start(), BreakServiceStartResult.started);
expect(client.calls, contains('requestPermission'));
});
// A denied permission must NOT block the service: its isolate still holds
// the wake lock and still plays the break-end sound. Only the visible
// surface is lost, and the caller is told so it can say so on screen.
test('still starts when the permission is denied, and says so', () async {
client
..permissionGranted = false
..grantOnRequest = false;
expect(await start(), BreakServiceStartResult.startedWithoutNotification);
expect(controller.isStarted, isTrue);
});
test('reports failure and stops listening when the service refuses to start',
() async {
client.startSucceeds = false;
expect(await start(), BreakServiceStartResult.failed);
expect(controller.isStarted, isFalse);
expect(client.calls.last, 'unlisten');
});
test('does nothing at all on a platform with no foreground service',
() async {
client.isSupported = false;
expect(await start(), BreakServiceStartResult.unsupported);
expect(client.calls, isEmpty);
expect(controller.isStarted, isFalse);
});
test('push is a no-op until the service has started', () async {
await controller.push(_snapshot);
expect(client.calls, isEmpty);
await start();
await controller.push(_snapshot);
expect(client.calls, contains('push'));
});
test('stop tears the service down and forgets pending presses', () async {
await start();
await queue.enqueue(
kind: BreakIntentKind.done,
exIdx: 0,
setIdx: 0,
now: DateTime(2026, 9, 12),
);
await controller.stop();
expect(controller.isStarted, isFalse);
expect(client.calls, contains('stop'));
expect(store.lists[BreakIntentQueue.intentsKey], isEmpty);
final applied = <BreakIntent>[];
await controller.drain((i) async => applied.add(i));
expect(applied, isEmpty);
});
test('stop is inert on an unsupported platform', () async {
client.isSupported = false;
await controller.stop();
expect(client.calls, isEmpty);
});
// No notification means no button to press, so the queue's storage -- which
// needs a platform SharedPreferences -- must never be touched there.
test('drain never reads storage on an unsupported platform', () async {
client.isSupported = false;
var applied = 0;
await controller.drain((_) async => applied++);
expect(applied, 0);
expect(store.lists, isEmpty);
expect(store.ints, isEmpty);
});
test('drain applies queued presses once the service is running', () async {
await start();
await queue.enqueue(
kind: BreakIntentKind.minusRep,
exIdx: 1,
setIdx: 2,
now: DateTime(2026, 9, 12),
);
final applied = <BreakIntent>[];
await controller.drain((i) async => applied.add(i));
expect(applied.single.exIdx, 1);
expect(applied.single.setIdx, 2);
});
test('the registered nudge callback is the one the caller passed', () async {
var nudged = 0;
await controller.start(_snapshot, onDrainNudge: () => nudged++);
client.onNudge!();
expect(nudged, 1);
});
// The service is meant to outlive its screen -- the back button pops the
// workout while it carries on, and stopWithTask="false" survives a swipe.
// That makes a startup reaper the only thing standing between a crash and a
// notification counting down a workout that ended hours ago.
group('stopStaleBreakService', () {
test('stops a service whose workout no longer exists', () async {
client.running = true;
final stopped = await stopStaleBreakService(
client,
hasActiveWorkout: () async => false,
);
expect(stopped, isTrue);
expect(client.calls, contains('stop'));
});
test('leaves a service alone while its workout is still in progress',
() async {
client.running = true;
final stopped = await stopStaleBreakService(
client,
hasActiveWorkout: () async => true,
);
expect(stopped, isFalse);
expect(client.calls, isNot(contains('stop')));
});
test('does nothing when no service is running', () async {
client.running = false;
expect(
await stopStaleBreakService(client, hasActiveWorkout: () async => false),
isFalse,
);
expect(client.calls, isNot(contains('stop')));
});
test('does nothing on a platform with no foreground service', () async {
client
..isSupported = false
..running = true;
expect(
await stopStaleBreakService(client, hasActiveWorkout: () async => false),
isFalse,
);
expect(client.calls, isEmpty);
});
});
}

View File

@ -0,0 +1,247 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/break_intent.dart';
import 'package:workout_app/models/break_snapshot.dart';
import 'package:workout_app/services/break_intent_queue.dart';
import 'package:workout_app/services/break_intent_store.dart';
import 'package:workout_app/services/break_service_port.dart';
import 'package:workout_app/services/break_task_handler.dart';
import '../fake_break_service.dart';
class _MemStore implements BreakIntentStore {
final ints = <String, int>{};
final lists = <String, List<String>>{};
@override
Future<int> readInt(String key) async => ints[key] ?? 0;
@override
Future<void> writeInt(String key, int value) async => ints[key] = value;
@override
Future<List<String>> readStringList(String key) async =>
lists[key] ?? const [];
@override
Future<void> writeStringList(String key, List<String> value) async =>
lists[key] = List.of(value);
}
void main() {
final now = DateTime(2026, 9, 12, 14);
late FakeBreakServicePort port;
late _MemStore store;
late BreakIntentQueue queue;
late BreakTaskHandler handler;
setUp(() {
port = FakeBreakServicePort();
store = _MemStore();
queue = BreakIntentQueue(store);
handler = BreakTaskHandler(port, queue);
});
Map<String, Object?> snapMap({
int breakEndMs = 0,
int breakDurationSecs = 180,
int nextExIdx = 0,
int nextSetIdx = 1,
int lastExIdx = 0,
int lastSetIdx = 0,
int breakForExIdx = 0,
int breakForSetIdx = 0,
int setsRemaining = 4,
}) => BreakSnapshot(
workoutType: 'A',
breakEndMs: breakEndMs,
breakDurationSecs: breakDurationSecs,
breakLabel: 'Rest (3 min — well done!)',
breakForExIdx: breakForExIdx,
breakForSetIdx: breakForSetIdx,
nextExIdx: nextExIdx,
nextSetIdx: nextSetIdx,
nextExName: 'Squat',
nextSetNumber: nextSetIdx + 1,
nextTotalSets: 5,
nextReps: 5,
nextWeight: 40,
lastExIdx: lastExIdx,
lastSetIdx: lastSetIdx,
setsRemaining: setsRemaining,
).toMap();
Future<List<BreakIntent>> queued() async {
final raw = await store.readStringList(BreakIntentQueue.intentsKey);
return [for (final e in raw) BreakIntent.tryDecode(e)!];
}
test('start registers plugins before anything else touches them', () async {
await handler.start(snapMap(), now);
expect(port.ready, isTrue);
expect(port.drawn, hasLength(1));
});
test('redraws only when the words actually changed', () async {
final endMs = now.add(const Duration(seconds: 90)).millisecondsSinceEpoch;
await handler.start(snapMap(breakEndMs: endMs), now);
final afterStart = port.drawn.length;
// Same displayed second, twice: one redraw, not two.
await handler.tick(now);
await handler.tick(now.add(const Duration(milliseconds: 300)));
expect(port.drawn.length, afterStart);
await handler.tick(now.add(const Duration(seconds: 1)));
expect(port.drawn.length, afterStart + 1);
});
test('alerts once when the rest ends, not every tick after', () async {
final endMs = now.add(const Duration(seconds: 5)).millisecondsSinceEpoch;
await handler.start(snapMap(breakEndMs: endMs), now);
await handler.tick(now.add(const Duration(seconds: 4)));
expect(port.alerts, 0);
await handler.tick(now.add(const Duration(seconds: 5)));
await handler.tick(now.add(const Duration(seconds: 6)));
await handler.tick(now.add(const Duration(seconds: 30)));
expect(port.alerts, 1);
});
test('a new rest period alerts again', () async {
final first = now.add(const Duration(seconds: 5)).millisecondsSinceEpoch;
await handler.start(snapMap(breakEndMs: first), now);
await handler.tick(now.add(const Duration(seconds: 5)));
expect(port.alerts, 1);
final second = now.add(const Duration(seconds: 60)).millisecondsSinceEpoch;
await handler.receiveData(snapMap(breakEndMs: second), now);
await handler.tick(now.add(const Duration(seconds: 60)));
expect(port.alerts, 2);
});
test('tick before any snapshot does nothing', () async {
await handler.tick(now);
expect(port.drawn, isEmpty);
expect(port.alerts, 0);
});
group('button presses', () {
test('Done queues the next set and nudges the UI', () async {
await handler.start(snapMap(nextExIdx: 1, nextSetIdx: 2), now);
await handler.pressButton(BreakNotificationAction.done, now);
final intents = await queued();
expect(intents, hasLength(1));
expect(intents.single.kind, BreakIntentKind.done);
expect(intents.single.exIdx, 1);
expect(intents.single.setIdx, 2);
expect(port.nudges, 1);
});
test('− 1 rep targets the set recorded last, resolved at press time',
() async {
await handler.start(snapMap(lastExIdx: 2, lastSetIdx: 3), now);
await handler.pressButton(BreakNotificationAction.minusRep, now);
final intents = await queued();
expect(intents.single.kind, BreakIntentKind.minusRep);
expect(intents.single.exIdx, 2);
expect(intents.single.setIdx, 3);
});
test('− 1 rep stretches a running rest to the failure length', () async {
final endMs = now.add(const Duration(seconds: 120)).millisecondsSinceEpoch;
await handler.start(
snapMap(breakEndMs: endMs, breakDurationSecs: 180),
now,
);
await handler.pressButton(BreakNotificationAction.minusRep, now);
final s = handler.snapshot!;
expect(s.breakDurationSecs, 300);
expect(s.breakLabel, contains('5 min'));
// Re-cut from the original start: 60s in, so 240s left of 300.
expect(
DateTime.fromMillisecondsSinceEpoch(s.breakEndMs)
.difference(now)
.inSeconds,
240,
);
});
test('Skip break clears the rest immediately', () async {
final endMs = now.add(const Duration(seconds: 90)).millisecondsSinceEpoch;
await handler.start(snapMap(breakEndMs: endMs), now);
await handler.pressButton(BreakNotificationAction.skipBreak, now);
expect((await queued()).single.kind, BreakIntentKind.skipBreak);
expect(handler.snapshot!.hasBreak, isFalse);
});
test('Done on the last set stops the service instead of carrying on',
() async {
await handler.start(snapMap(setsRemaining: 1), now);
await handler.pressButton(BreakNotificationAction.done, now);
expect(port.stopped, isTrue);
});
test('ignores presses that no longer refer to anything', () async {
await handler.start(
snapMap(nextExIdx: -1, nextSetIdx: -1, lastExIdx: -1, lastSetIdx: -1),
now,
);
await handler.pressButton(BreakNotificationAction.done, now);
await handler.pressButton(BreakNotificationAction.minusRep, now);
await handler.pressButton(BreakNotificationAction.skipBreak, now);
await handler.pressButton('something_else', now);
expect(await queued(), isEmpty);
expect(port.nudges, 0);
});
test('ignores a press before any snapshot arrived', () async {
await handler.pressButton(BreakNotificationAction.done, now);
expect(await queued(), isEmpty);
});
test('− 1 rep outside a rest queues without touching the clock', () async {
await handler.start(snapMap(lastExIdx: 0, lastSetIdx: 0), now);
await handler.pressButton(BreakNotificationAction.minusRep, now);
expect((await queued()).single.kind, BreakIntentKind.minusRep);
expect(handler.snapshot!.hasBreak, isFalse);
});
test('− 1 rep during a WARMUP rest leaves the clock alone', () async {
final endMs = now.add(const Duration(seconds: 90)).millisecondsSinceEpoch;
await handler.start(
snapMap(breakEndMs: endMs, breakForSetIdx: -1, lastSetIdx: 0),
now,
);
await handler.pressButton(BreakNotificationAction.minusRep, now);
expect(handler.snapshot!.breakEndMs, endMs);
});
});
group('bad payloads', () {
test('a non-map payload leaves the previous state showing', () async {
await handler.start(snapMap(), now);
final before = handler.snapshot;
await handler.receiveData('not a map', now);
expect(handler.snapshot, same(before));
});
test('a malformed map leaves the previous state showing', () async {
await handler.start(snapMap(), now);
final before = handler.snapshot;
await handler.receiveData(<String, Object?>{'workoutType': 'A'}, now);
expect(handler.snapshot, same(before));
});
test('start with no payload draws nothing but still registers', () async {
await handler.start(null, now);
expect(port.ready, isTrue);
expect(port.drawn, isEmpty);
});
});
}