Compare commits

...

18 Commits

Author SHA1 Message Date
95adc8699c Document the selective push gate
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:52:00 +01:00
89f8efc92b Set push gate Dart budget to 25 tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:51:33 +01:00
01b7a4a83f Fix ruff findings in selector
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:50:54 +01:00
55d5d29fed Satisfy pylint in coverage helper
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:50:37 +01:00
c3207c43dc Docstring the selector tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:50:26 +01:00
4b6e4df1bf Log gate helper failures
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:50:09 +01:00
f79d425d3d Add full gate, nightly timer, 8 shards
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:47:43 +01:00
100b0c9663 Add selective push gate and wire it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:47:11 +01:00
1c696b72ce Test the push-gate selector
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:46:44 +01:00
eb9d8c5e32 Add change-based test selector for push gate
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:46:18 +01:00
4009e9475b Bump material_ui, sync_settings_ui, web pins
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:37:53 +01:00
9ba2f46c23 Fix run-mode gates: logs, file caps, coverage
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:35:32 +01:00
2137152729 Relay run notification taps to the host
flutter_foreground_task 11.0.3 calls onNotificationPressed only for a
MAIN+LAUNCHER intent; the sandbox has no LAUNCHER filter, so the press
never reached RunHost. MainActivity now relays it (cold and warm).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWW75Epgijvt2eJ1ErR
2026-11-17 21:55:52 +01:00
0175cbede4 Persist runs: tests, trims, adapter coverage
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWW75Epgijvt2eJ1ErR
2026-11-17 21:28:45 +01:00
cfc2cd553a Adapt run host to the real recorder API
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWW75Epgijvt2eJ1ErR
2026-11-17 21:08:45 +01:00
218632fd0e Merge branch 'run-persist-logic' into worktree-agent-ad5ad3468f792eb82 2026-11-17 20:59:06 +01:00
c1dbfa0352 Host the run in the foreground service
WIP: host, link, view, finish modal, launch routing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWW75Epgijvt2eJ1ErR
2026-11-17 20:59:06 +01:00
d45e67a02c Persist and bridge GPS runs across death
Checkpoint codec and file store, gap bridging at 2:30-12:00 min/km, watchdog (suggest finish, 5 h auto end), recorder restore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWW75Epgijvt2eJ1ErR
2026-11-17 20:54:40 +01:00
99 changed files with 6644 additions and 668 deletions

View File

@ -316,7 +316,7 @@ repos:
files: '^stronglift_replacement/workout_app/.*\.(dart|yaml)$'
pass_filenames: false
- id: flutter-test-coverage-shard-0
name: flutter test bucket 0/4 (workout app, local gate)
name: flutter test bucket 0/8 (workout app, local gate)
entry: bash scripts/check_flutter_coverage.sh --gate-shard 0
language: system
pass_filenames: false
@ -324,7 +324,7 @@ repos:
require_serial: true
stages: [manual]
- id: flutter-test-coverage-shard-1
name: flutter test bucket 1/4 (workout app, local gate)
name: flutter test bucket 1/8 (workout app, local gate)
entry: bash scripts/check_flutter_coverage.sh --gate-shard 1
language: system
pass_filenames: false
@ -332,7 +332,7 @@ repos:
require_serial: true
stages: [manual]
- id: flutter-test-coverage-shard-2
name: flutter test bucket 2/4 (workout app, local gate)
name: flutter test bucket 2/8 (workout app, local gate)
entry: bash scripts/check_flutter_coverage.sh --gate-shard 2
language: system
pass_filenames: false
@ -340,17 +340,49 @@ repos:
require_serial: true
stages: [manual]
- id: flutter-test-coverage-shard-3
name: flutter test bucket 3/4 (workout app, local gate)
name: flutter test bucket 3/8 (workout app, local gate)
entry: bash scripts/check_flutter_coverage.sh --gate-shard 3
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: flutter-test-coverage-shard-4
name: flutter test bucket 4/8 (workout app, local gate)
entry: bash scripts/check_flutter_coverage.sh --gate-shard 4
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: flutter-test-coverage-shard-5
name: flutter test bucket 5/8 (workout app, local gate)
entry: bash scripts/check_flutter_coverage.sh --gate-shard 5
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: flutter-test-coverage-shard-6
name: flutter test bucket 6/8 (workout app, local gate)
entry: bash scripts/check_flutter_coverage.sh --gate-shard 6
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: flutter-test-coverage-shard-7
name: flutter test bucket 7/8 (workout app, local gate)
entry: bash scripts/check_flutter_coverage.sh --gate-shard 7
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
# Fails unless every shard above passed on THIS tree, then applies the
# unchanged 100% bar and every-lib-file guard to their union.
- id: flutter-test-coverage-merge
name: flutter coverage 100% (union of the 4 buckets)
name: flutter coverage 100% (union of the 8 buckets)
entry: bash scripts/check_flutter_coverage.sh --gate-merge
language: system
pass_filenames: false

View File

@ -123,3 +123,17 @@ wait, and tests pin the retry to 0.
- coverage: `python -m pytest -n auto -p no:sugar -q`
- coverage-gaps: `coverage-gaps coverage.lcov`
- deploy: `git -C ~/src/screen-locker pull --ff-only && bash ~/src/screen-locker/scripts/deploy.sh` (reinstalls, restarts web/poke/runnerup units, health-checks them, then release-deploys the workout app; exit 46 from the phone guard means kuhy reruns it with `PHONE_PROTECT_ALLOW=com.kuhy.workout_app`)
## Pre-push gate (<=60 s)
A stamped tree (full suite green) pushes in ~1 s. An unstamped tree runs
`scripts/push_gate.sh`: pre-commit plus only the tests the change since the
last full-green commit can affect (`scripts/gate_select.py`), 100% line
coverage on the changed dart files, and it prints which tests ran and why.
Pubspec/analysis_options/conftest/pyproject changes, or more than 25 selected
Dart tests, need the full suite: `scripts/full_gate.sh step <id>` once per id
(`full_gate.sh list`; 8 shards, each <60 s) or `full_gate.sh all`. The nightly
`full-gate.timer` (22:00, loadavg guard) runs `full_gate.sh all`; a red result
(`$GIT_DIR/gate-full-status`) refuses every push until a full run is green.
Install the nightly: copy `full-gate.{service,timer}` to `~/.config/systemd/user/`
and `systemctl --user enable --now full-gate.timer` (not enabled yet).

14
full-gate.service Normal file
View File

@ -0,0 +1,14 @@
[Unit]
Description=screen-locker full test suite (writes the green/red full stamp that gates pushes)
[Service]
Type=oneshot
# %h = kuhy's home. nightly_full_gate.sh skips under load and on a dirty tree.
ExecStart=/bin/bash %h/src/screen-locker/scripts/nightly_full_gate.sh
# Each hook step is <60 s on its own; the whole run gets its own generous cap.
TimeoutStartSec=45min
Nice=19
IOSchedulingClass=idle
CPUQuota=20%
MemoryMax=4G
Environment=FLUTTER_TEST_CONCURRENCY=2

14
full-gate.timer Normal file
View File

@ -0,0 +1,14 @@
[Unit]
Description=Nightly screen-locker full suite at 22:00
# No After=graphical-session.target: it would close an ordering cycle with
# timers.target and systemd would delete this timer's job (see
# early-bird-workout-check.timer, 2026-08-04).
[Timer]
OnCalendar=*-*-* 22:00:00
# Persistent stamps on elapse, not on success; a night skipped by the load
# guard is simply skipped. The PC is off from 23:00, so no catch-up is wanted.
Persistent=false
[Install]
WantedBy=timers.target

View File

@ -0,0 +1,90 @@
"""Selection of push-gate tests from a change set (scripts/gate_select.py)."""
from __future__ import annotations
from typing import TYPE_CHECKING
from scripts import gate_select as gs
if TYPE_CHECKING:
from pathlib import Path
APP = gs.APP
def _write(root: Path, rel: str, text: str = "") -> None:
path = root / APP / rel
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
def _tree(root: Path) -> None:
_write(root, "lib/a.dart", "")
_write(root, "lib/b.dart", "import 'a.dart';")
_write(root, "lib/c.dart", "import 'package:workout_app/b.dart' if (x) 'a.dart';")
_write(root, "lib/lonely.dart", "")
_write(root, "test/rig.dart", "import 'package:workout_app/lonely.dart';")
_write(root, "test/c_test.dart", "import 'package:workout_app/c.dart';")
_write(root, "test/lonely_test.dart", "import 'rig.dart';")
_write(root, "test/sub/x_test.dart", "import '../rig.dart';")
_write(root, "test/other_test.dart", "import 'dart:io';")
def test_transitive_import_reaches_test(tmp_path: Path) -> None:
"""Selector: transitive import reaches test."""
_tree(tmp_path)
got = gs.dart_affected_tests(tmp_path, [f"{APP}/lib/a.dart"])
assert got == [f"{APP}/test/c_test.dart"]
def test_helper_followed_by_import(tmp_path: Path) -> None:
"""Selector: helper followed by import."""
_tree(tmp_path)
got = gs.dart_affected_tests(tmp_path, [f"{APP}/test/rig.dart"])
assert got == [f"{APP}/test/lonely_test.dart", f"{APP}/test/sub/x_test.dart"]
def test_untouched_change_selects_nothing(tmp_path: Path) -> None:
"""Selector: untouched change selects nothing."""
_tree(tmp_path)
assert gs.dart_affected_tests(tmp_path, [f"{APP}/lib/lonely.dart"]) == [
f"{APP}/test/lonely_test.dart",
f"{APP}/test/sub/x_test.dart",
]
assert gs.dart_affected_tests(tmp_path, ["README.md"]) == []
def test_pubspec_forces_full_and_says_why(tmp_path: Path) -> None:
"""Selector: pubspec forces full and says why."""
_tree(tmp_path)
sel = gs.select(tmp_path, [f"{APP}/pubspec.yaml", "web/x.ts"], [])
assert sel.full_dart
assert sel.web
assert any("full Dart suite" in why for why in sel.why)
def test_python_mapping_and_full(tmp_path: Path) -> None:
"""Selector: python mapping and full."""
tracked = [
"screen_locker/tests/test_foo_bar.py",
"screen_locker/tests/test__foo.py",
]
assert gs.python_tests_for(["screen_locker/_foo.py"], tracked) == (
["screen_locker/tests/test__foo.py", "screen_locker/tests/test_foo_bar.py"],
False,
)
assert gs.python_tests_for(["screen_locker/tests/test_x.py"], tracked) == (
["screen_locker/tests/test_x.py"],
False,
)
assert gs.python_tests_for(["pyproject.toml"], tracked) == ([], True)
assert gs.python_tests_for(["README.md"], tracked) == ([], False)
def test_no_web_without_web_files(tmp_path: Path) -> None:
"""Selector: no web without web files."""
_tree(tmp_path)
sel = gs.select(tmp_path, [f"{APP}/lib/a.dart"], [])
assert not sel.web
assert not sel.full_dart
assert sel.dart == [f"{APP}/test/c_test.dart"]

View File

@ -42,7 +42,7 @@ APP_DIR="stronglift_replacement/workout_app"
LCOV_INFO="$APP_DIR/coverage/lcov.info"
# Number of local-gate buckets; must equal the flutter-test-coverage-shard-*
# hooks in .pre-commit-config.yaml (the merge counts them, see below).
GATE_SHARDS=4
GATE_SHARDS=8
die() {
echo "ERROR: $*" >&2
@ -163,6 +163,10 @@ while IFS= read -r dart_file; do
# whitespace, so a wrapped `export 'x' if (...) 'y';` statement (the
# platform-gate barrel shape) becomes matchable on one logical line
# regardless of how it's line-wrapped in source.
# A file that opts out wholesale is dropped from lcov by flutter itself.
if grep -qE '^// coverage:ignore-file' "$dart_file"; then
continue
fi
code_only=$(grep -vE '^[[:space:]]*(///|//|$)' "$dart_file" | tr '\n' ' ' | tr -s ' ')
if [[ $code_only =~ $barrel_pattern ]]; then
continue

View File

@ -24,6 +24,18 @@ main() {
exit 1
fi
# A stamped tree (full gate green) passes in ~1 s. An unstamped tree gets
# the selective push gate: pre-commit + only the tests the change can
# affect, <=60 s, and it says which ran and why (scripts/push_gate.sh).
if [[ "${1:-}" == check ]]; then
local here
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if bash "$SHARED_GATE" check 2>/dev/null; then
exit 0
fi
echo "gate-stamp: tree not fully stamped; running the selective push gate" >&2
exec bash "$here/push_gate.sh"
fi
exec bash "$SHARED_GATE" "$@"
}

53
scripts/full_gate.sh Executable file
View File

@ -0,0 +1,53 @@
#!/bin/bash
# ============================================================================
# The FULL suite, outside the push path: every manual-stage hook of
# .pre-commit-config.yaml as its own <60 s step (gate_stamp.sh step <id>), then
# a green or red verdict in $GIT_DIR:
# gate-full-green commit the full suite passed on (push gate's base)
# gate-full-status "green <commit> <time>" or "red <hook-id> <commit> <time>"
# A red status makes scripts/push_gate.sh refuse every push until a full run
# is green again. The stamp itself is written by gate_stamp.sh once every
# step passed, as before.
#
# full_gate.sh list hook ids, one per line
# full_gate.sh step <id> one step (interactive use: one call each)
# full_gate.sh all every step in order, stops at the first red
# (the nightly timer's entry point)
# ============================================================================
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
gitdir="$(git rev-parse --git-dir)"
readonly GATE="bash scripts/check_gate_stamp.sh"
record() { # verdict words...
printf '%s %s\n' "$*" "$(date -Is)" > "$gitdir/gate-full-status"
}
run_step() {
local id="$1" head
head="$(git rev-parse HEAD)"
if $GATE step "$id"; then
# The last passing step stamps the tree: that is a full green.
if bash "${GATE_SHARED:-$HOME/src/utils/scripts/gate_stamp.sh}" check >/dev/null 2>&1; then
printf '%s\n' "$head" > "$gitdir/gate-full-green"
record green "$head"
echo "full-gate: GREEN on ${head:0:10}"
fi
else
record red "$id" "$head"
echo "full-gate: RED at '$id' on ${head:0:10}; pushes are refused until green" >&2
return 1
fi
}
case "${1:-}" in
list) $GATE full --list ;;
step) run_step "${2:?usage: full_gate.sh step <hook-id>}" ;;
all)
while IFS= read -r id; do run_step "$id"; done < <($GATE full --list)
;;
*) echo "usage: full_gate.sh list | step <id> | all" >&2; exit 2 ;;
esac

View File

@ -0,0 +1,56 @@
"""100% line bar for CHANGED dart files, from the lcov of the selected tests.
Usage: gate_changed_coverage.py LCOV CHANGED_FILE...
Paths in CHANGED_FILE are repo-relative; only lib/ files of the app count.
A changed lib file missing from the lcov fails (a file no selected test
loads would otherwise score 100% by absence).
"""
from __future__ import annotations
import logging
from pathlib import Path
import sys
_LOG = logging.getLogger(__name__)
APP_LIB = "stronglift_replacement/workout_app/lib/"
def uncovered(lcov: str, wanted: set[str]) -> dict[str, list[int] | None]:
"""Map wanted lib file -> uncovered line numbers (None = absent from lcov)."""
result: dict[str, list[int] | None] = dict.fromkeys(wanted)
current: str | None = None
for line in lcov.splitlines():
if line.startswith("SF:"):
current = f"{APP_LIB}{line[3:].removeprefix('lib/')}"
if current in wanted:
result[current] = result[current] or []
else:
current = None
elif line.startswith("DA:") and current is not None:
num, hits = line[3:].split(",")[:2]
if not int(hits):
(result[current] or []).append(int(num))
return result
def main(argv: list[str]) -> int:
"""Exit 1 listing every changed lib file that is not fully covered."""
wanted = {f for f in argv[2:] if f.startswith(APP_LIB) and f.endswith(".dart")}
bad = 0
for path, lines in sorted(
uncovered(Path(argv[1]).read_text(encoding="utf-8"), wanted).items()
):
if lines is None or lines:
_LOG.error(
"changed file below 100%%: %s (uncovered: %s)",
path,
"absent from lcov" if lines is None else lines,
)
bad += 1
return 1 if bad else 0
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, format="push-gate: %(message)s")
raise SystemExit(main(sys.argv))

181
scripts/gate_select.py Normal file
View File

@ -0,0 +1,181 @@
"""Pick the tests a push must run: only those affected since the last green full run.
Selection is sound, not clever: a Dart test is selected if its transitive
imports reach a changed dart file (lib or test helper); python tests are mapped
by module name as in scripts/test_changed.sh; web runs only when web/ changed.
Anything that can change every test (pubspec, analysis_options, conftest,
pyproject) selects the full suite, and the caller must say so -- selection
never narrows silently.
CLI: gate_select.py BASE [HEAD] prints JSON of the Selection
"""
from __future__ import annotations
from dataclasses import asdict, dataclass, field
import json
import logging
from pathlib import Path
import re
import shutil
import subprocess
import sys
_HEAD_ARG = 2
_GIT = shutil.which("git") or "git"
_LOG = logging.getLogger(__name__)
APP = "stronglift_replacement/workout_app"
_DIRECTIVE = re.compile(r"^\s*(?:import|export|part)\s[^;]*;", re.MULTILINE)
_QUOTED = re.compile(r"'([^']+)'|\"([^\"]+)\"")
_FULL_DART = (
f"{APP}/pubspec.yaml",
f"{APP}/pubspec.lock",
f"{APP}/analysis_options.yaml",
)
_FULL_PY = {"conftest.py", "pyproject.toml", "pytest.ini", "setup.cfg"}
@dataclass
class Selection:
"""What a push must run, and the reasons (printed by the gate)."""
dart: list[str] = field(default_factory=list)
python: list[str] = field(default_factory=list)
web: bool = False
full_dart: bool = False
full_python: bool = False
why: list[str] = field(default_factory=list)
def _norm(path: str) -> str:
parts: list[str] = []
for p in path.split("/"):
if p == "..":
parts.pop()
elif p not in (".", ""):
parts.append(p)
return "/".join(parts)
def _imports(root: Path, rel: str, pkg: str) -> set[str]:
"""Repo-relative dart files that `rel` imports, exports or parts."""
out: set[str] = set()
try:
text = (root / rel).read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as exc:
_LOG.warning("gate_select: cannot read %s: %s", rel, exc)
return out
for stmt in _DIRECTIVE.findall(text):
for a, b in _QUOTED.findall(stmt):
uri = a or b
if uri.startswith(f"package:{pkg}/"):
cand = f"{APP}/lib/{uri.split('/', 1)[1]}"
elif ":" in uri:
continue
else:
cand = _norm(f"{Path(rel).parent.as_posix()}/{uri}")
if (root / cand).is_file():
out.add(cand)
return out
def dart_affected_tests(
root: Path, changed: list[str], pkg: str = "workout_app"
) -> list[str]:
"""Test files whose transitive imports reach a changed dart file."""
files = sorted(
p.relative_to(root).as_posix()
for sub in ("lib", "test")
for p in (root / APP / sub).rglob("*.dart")
)
rev: dict[str, set[str]] = {}
for f in files:
for dep in _imports(root, f, pkg):
rev.setdefault(dep, set()).add(f)
seen = {c for c in changed if c.endswith(".dart")}
stack = list(seen)
while stack:
for user in rev.get(stack.pop(), ()):
if user not in seen:
seen.add(user)
stack.append(user)
return sorted(
f for f in seen if f.startswith(f"{APP}/test/") and f.endswith("_test.dart")
)
def python_tests_for(changed: list[str], tracked: list[str]) -> tuple[list[str], bool]:
"""(tests, full) for changed python files, mirroring scripts/test_changed.sh."""
tests: set[str] = set()
for f in changed:
if Path(f).name in _FULL_PY:
return [], True
if not f.endswith(".py"):
continue
base = Path(f).stem.removeprefix("_")
if base.startswith("test_") or base.endswith("_test"):
tests.add(f)
continue
pat = re.compile(
rf"(test_{re.escape(base)}|test__{re.escape(base)}|{re.escape(base)}_test)[^/]*\.py$"
)
tests.update(t for t in tracked if pat.search(t))
return sorted(tests), False
def select(root: Path, changed: list[str], tracked: list[str]) -> Selection:
"""Build the selection for a change set."""
sel = Selection()
app_changed = [c for c in changed if c.startswith(f"{APP}/")]
for f in _FULL_DART:
if f in changed:
sel.full_dart = True
sel.why.append(f"{f} changed: the full Dart suite is required")
helpers = [
c
for c in app_changed
if "/test/" in c and c.endswith(".dart") and not c.endswith("_test.dart")
]
if app_changed and not sel.full_dart:
sel.dart = dart_affected_tests(root, app_changed)
extra = (
f" (incl. {len(helpers)} test helpers, followed by import)"
if helpers
else ""
)
sel.why.append(
f"{len(sel.dart)} Dart tests reach {len(app_changed)} changed files{extra}"
)
sel.python, sel.full_python = python_tests_for(changed, tracked)
if sel.full_python:
sel.why.append("conftest/pyproject changed: the full Python suite is required")
elif sel.python:
sel.why.append(
f"{len(sel.python)} Python test files map to the changed modules"
)
sel.web = any(c.startswith("web/") for c in changed)
if sel.web:
sel.why.append("web/ changed: vitest coverage runs")
return sel
def _git(root: Path, *args: str) -> list[str]:
out = subprocess.run(
[_GIT, *args], cwd=root, check=True, capture_output=True, text=True
).stdout
return [line for line in out.splitlines() if line]
def main(argv: list[str]) -> int:
"""Print the selection for BASE..HEAD as JSON."""
root = Path(_git(Path.cwd(), "rev-parse", "--show-toplevel")[0])
logging.basicConfig(level=logging.INFO)
base, head = argv[1], (argv[_HEAD_ARG] if len(argv) > _HEAD_ARG else "HEAD")
changed = _git(root, "diff", "--name-only", f"{base}..{head}")
sel = select(root, changed, _git(root, "ls-files", "*.py"))
sys.stdout.write(json.dumps(asdict(sel), indent=1) + "\n")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv))

28
scripts/nightly_full_gate.sh Executable file
View File

@ -0,0 +1,28 @@
#!/bin/bash
# ============================================================================
# Nightly entry point (full-gate.timer, 22:00): run the full suite on a clean
# detached checkout of main in a throwaway worktree, unless the machine is
# busy. A red result lands in the repo's $GIT_DIR/gate-full-status, which
# refuses the next push (scripts/push_gate.sh).
# Loadavg guard: skip (exit 0, logged) when the 5-min load exceeds MAX_LOAD.
# ============================================================================
set -euo pipefail
readonly REPO="${SCREEN_LOCKER_REPO:-$HOME/src/screen-locker}"
readonly MAX_LOAD="${GATE_MAX_LOAD:-6}"
read -r _ load5 _ < /proc/loadavg
if awk -v l="$load5" -v m="$MAX_LOAD" 'BEGIN { exit !(l > m) }'; then
echo "nightly-full-gate: load5=$load5 > $MAX_LOAD, skipped tonight" >&2
exit 0
fi
cd "$REPO"
# The verdict files live in the main repo's git dir; the suite runs on HEAD.
if [[ -n "$(git status --porcelain --untracked-files=no)" ]]; then
echo "nightly-full-gate: working tree dirty, skipped (the gate stamps HEAD only)" >&2
exit 0
fi
exec bash scripts/full_gate.sh all

96
scripts/push_gate.sh Executable file
View File

@ -0,0 +1,96 @@
#!/bin/bash
# ============================================================================
# pre-push gate for an UN-stamped tree: pre-commit plus ONLY the tests the
# change since the last fully green run can affect (scripts/gate_select.py),
# with the 100% line bar on the changed dart files. Budget: 60 s wall-clock.
#
# Never narrows silently: it prints which tests ran and why, and refuses
# (exit 1) when the selection is the full suite or exceeds the budget -- those
# belong to scripts/full_gate.sh, which stamps the tree.
#
# push_gate.sh [BASE] BASE defaults to the last full-green commit
# ($GIT_DIR/gate-full-green), else origin/main
# ============================================================================
set -euo pipefail
readonly APP="stronglift_replacement/workout_app"
readonly MAX_DART_TESTS="${GATE_MAX_DART_TESTS:-25}"
readonly FLUTTER_CONCURRENCY="${FLUTTER_TEST_CONCURRENCY:-2}"
die() {
echo "push-gate: $*" >&2
exit 1
}
cd "$(git rev-parse --show-toplevel)"
gitdir="$(git rev-parse --git-dir)"
# A red nightly/full run refuses every push until a full run is green again.
if [[ "$(cat "$gitdir/gate-full-status" 2>/dev/null || true)" == red* ]]; then
die "RED FULL STAMP ($(cat "$gitdir/gate-full-status")). The last full suite failed; fix it and rerun scripts/full_gate.sh -- no push until it is green."
fi
base="${1:-}"
[[ -n "$base" ]] || base="$(cat "$gitdir/gate-full-green" 2>/dev/null || true)"
[[ -n "$base" ]] || base="$(git merge-base origin/main HEAD 2>/dev/null || true)"
[[ -n "$base" ]] || die "no base (no full-green commit, no origin/main): run scripts/full_gate.sh"
git rev-parse --verify --quiet "$base^{commit}" >/dev/null || die "base $base is unknown: run scripts/full_gate.sh"
sel="$(python3 scripts/gate_select.py "$base" HEAD)"
field() { jq -r "$1" <<<"$sel"; }
echo "push-gate: base ${base:0:10}..HEAD $(git rev-parse --short HEAD)"
field '.why[] | "push-gate: " + .'
if [[ "$(field .full_dart)" == true || "$(field .full_python)" == true ]]; then
die "the change needs the FULL suite (see above). Run scripts/full_gate.sh, then push."
fi
mapfile -t dart < <(field '.dart[]')
mapfile -t py < <(field '.python[]')
(( ${#dart[@]} <= MAX_DART_TESTS )) \
|| die "${#dart[@]} Dart tests selected, over the ${MAX_DART_TESTS}-test push budget. Run scripts/full_gate.sh."
changed=()
mapfile -t changed < <(git diff --name-only "$base"..HEAD)
pids=() names=()
run_bg() { # name, command...
local name="$1" log
shift
log="$(mktemp)"
( "$@" >"$log" 2>&1 ) &
pids+=("$!") names+=("$name:$log")
}
run_bg pre-commit pre-commit run --from-ref "$base" --to-ref HEAD
if (( ${#dart[@]} > 0 )); then
rel=("${dart[@]#"$APP"/}")
echo "push-gate: Dart ran: ${#dart[@]} tests"
run_bg dart bash -c "cd '$APP' && env -u GIT_DIR -u GIT_WORK_TREE -u GIT_INDEX_FILE \
flutter test --coverage --concurrency '$FLUTTER_CONCURRENCY' ${rel[*]} \
&& cd - >/dev/null && python3 scripts/gate_changed_coverage.py '$APP/coverage/lcov.info' ${changed[*]}"
fi
if (( ${#py[@]} > 0 )); then
echo "push-gate: Python ran: ${#py[@]} test files"
run_bg python python3 -m pytest -o addopts="--strict-markers --strict-config -p screen_locker.tests.test_sync_fixtures" \
-p no:sugar --no-cov -q --tb=short "${py[@]}"
fi
if [[ "$(field .web)" == true ]]; then
echo "push-gate: web ran: vitest coverage"
run_bg web pnpm --dir web run coverage
fi
fail=0
for i in "${!pids[@]}"; do
name="${names[$i]%%:*}" log="${names[$i]#*:}"
if wait "${pids[$i]}"; then
echo "push-gate: $name OK"
else
echo "push-gate: $name FAILED" >&2
tail -25 "$log" >&2
fail=1
fi
rm -f "$log"
done
(( fail == 0 )) || die "failed (selection above); fix it, or run scripts/full_gate.sh"
echo "push-gate: OK (selective; the full suite is the nightly's job)"

View File

@ -32,6 +32,12 @@
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission
android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
<!-- A location foreground service that is (re)started from the
background (sticky restart after a kill, boot) may only read the
location if this is held; without it the run would restart silently
and receive no fixes. -->
<uses-permission
android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<!-- 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" />

View File

@ -1,11 +1,43 @@
package com.kuhy.workout_app
import android.content.Intent
import android.os.Bundle
import android.util.Log
import com.pravera.flutter_foreground_task.service.ForegroundService
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
relayNotificationPress(intent)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
relayNotificationPress(intent)
}
// flutter_foreground_task only tells the service a notification was tapped
// when the opening intent is MAIN + LAUNCHER. The sandbox flavor has no
// LAUNCHER filter (it must stay out of the launcher), so its press would
// be dropped and the run notification could never open the finish modal.
// Hand such a press to the plugin as if it were a LAUNCHER intent. A real
// LAUNCHER intent was already handled by the plugin: not relayed twice.
private fun relayNotificationPress(opened: Intent?) {
if (opened == null ||
opened.getStringExtra(PRESS_EXTRA) != PRESS_ACTION ||
opened.hasCategory(Intent.CATEGORY_LAUNCHER)
) {
return
}
Log.i(LOG_TAG, "notification press relayed")
ForegroundService.handleNotificationContentIntent(
Intent(opened).addCategory(Intent.CATEGORY_LAUNCHER),
)
}
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
// The sandbox flavor is a build-time fact; Dart asks for it once at
@ -50,5 +82,9 @@ class MainActivity : FlutterActivity() {
const val PAIRING_CHANNEL = "com.kuhy.workout_app/pc_pairing"
const val CHANNEL = "com.kuhy.workout_app/sandbox"
const val LOG_TAG = "WorkoutSandbox"
// The extra the plugin puts on its notification's launch intent.
private const val PRESS_EXTRA = "intentData"
private const val PRESS_ACTION = "onNotificationPressed"
}
}

View File

@ -17,18 +17,23 @@ 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/foreground_run_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/pc_pairing.dart';
import 'package:workout_app/services/progression_sync_service.dart';
import 'package:workout_app/services/run_checkpoint_location.dart';
import 'package:workout_app/services/run_launch.dart';
import 'package:workout_app/services/run_upload_credentials.dart';
import 'package:workout_app/services/run_uploader.dart';
import 'package:workout_app/services/run_wiring.dart';
import 'package:workout_app/services/runnerup_importer.dart';
import 'package:workout_app/services/shared_storage.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/sync_device_id.dart';
import 'package:workout_app/services/sync_service.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/run_landing.dart';
// coverage:ignore-start
// App bootstrap: permission request, DB init, and a real listening socket —
@ -101,12 +106,14 @@ void main(List<String> args) async {
// still pending from an earlier launch.
if (!Sandbox.enabled) await RunCredentialStore().importProvisionFile();
unawaited(RunUploader.instance.uploadPending());
installRunWiring();
// 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,
runIsOwed: runIsOwed, // the service may be hosting a run
);
await StorageService.instance.restoreFromBackupIfNeeded();
// The permission-free restore path, and the reason storage is now optional.
@ -147,7 +154,13 @@ void main(List<String> args) async {
localDir: sharedPathFor(Sandbox.packageName, kRunnerUpLocalDir),
).runGuarded(),
);
runApp(const WorkoutApp());
final resumeRun =
Platform.isAndroid &&
await resumeRunOnLaunch(
owed: runIsOwed,
client: FlutterForegroundRunClient(),
);
runApp(WorkoutApp(resumeRun: resumeRun));
}
// coverage:ignore-end
@ -157,8 +170,11 @@ void main(List<String> args) async {
/// listening socket while the app is backgrounded, so the process (and its
/// open socket) doesn't sit alive indefinitely and block Doze/App-Standby.
class WorkoutApp extends StatefulWidget {
/// Creates the root app widget.
const WorkoutApp({super.key});
/// Creates the root app widget; [resumeRun] opens the live run screen.
const WorkoutApp({super.key, this.resumeRun = false});
/// A run is in progress: land on it, whatever launched the app.
final bool resumeRun;
@override
State<WorkoutApp> createState() => _WorkoutAppState();
@ -214,7 +230,10 @@ class _WorkoutAppState extends State<WorkoutApp> with WidgetsBindingObserver {
fw.DefaultMaterialLocalizations.delegate,
DefaultWidgetsLocalizations.delegate,
],
home: const HomeScreen(),
home: RunLanding(
owed: Platform.isAndroid ? runIsOwed : null,
child: HomeScreen(openRunOnLaunch: widget.resumeRun),
),
// The one thing that must never be mistaken for the daily build: a
// ribbon on every screen, in the error colour, on the sandbox only.
builder: (context, child) => Sandbox.enabled

View File

@ -54,6 +54,20 @@ enum RunSource {
values.firstWhere((s) => s.storageKey == key);
}
/// How a [RunPoint] joins the one before it.
enum RunLink {
/// Reached in the normal flow of fixes.
continuous,
/// A new segment: after a pause (or a GPS jump re-anchor). The line from
/// the previous point is not drawn and credits nothing.
segmentStart,
/// Reached across a gap (phone dead, GPS lost): a straight line from the
/// previous point, drawn always, credited only at a running pace.
bridge,
}
/// One accepted GPS fix.
@immutable
class RunPoint {
@ -64,6 +78,7 @@ class RunPoint {
required this.longitude,
required this.distanceM,
this.altitudeM,
this.link = RunLink.continuous,
}) : time = time.toUtc();
/// When the fix was taken (UTC).
@ -84,9 +99,13 @@ class RunPoint {
/// values, so this is the field the recorder must keep honest.
final double distanceM;
/// How this point joins the previous one.
final RunLink link;
@override
bool operator ==(Object other) =>
other is RunPoint &&
other.link == link &&
other.time == time &&
other.latitude == latitude &&
other.longitude == longitude &&
@ -95,7 +114,7 @@ class RunPoint {
@override
int get hashCode =>
Object.hash(time, latitude, longitude, altitudeM, distanceM);
Object.hash(time, latitude, longitude, altitudeM, distanceM, link);
}
/// A finished (or in-progress) track.

View File

@ -37,8 +37,12 @@ class HomeScreen extends StatefulWidget {
this.clock,
this.configuredProbe,
this.openWorkoutOnLaunch = true,
this.openRunOnLaunch = false,
});
/// A run is in progress: the first load opens the run, not the workout.
final bool openRunOnLaunch;
/// Sync service to use; defaults to a real [WorkoutSyncService].
final WorkoutSyncService? syncService;
@ -97,6 +101,7 @@ class _HomeScreenState extends State<HomeScreen> {
lastDate.day == today.day;
final firstLoad = !_hasAutoOpened;
_hasAutoOpened = true;
final resumeRun = firstLoad && widget.openRunOnLaunch;
final launch = await _decideLaunch(
firstLoad: firstLoad,
hasSaved: saved != null,
@ -122,7 +127,11 @@ class _HomeScreenState extends State<HomeScreen> {
// changes what the card says when it lands.
unawaited(_refreshSyncStatus());
if (launch.open) {
if (resumeRun) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) unawaited(_openRun(resuming: true));
});
} else if (launch.open) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
unawaited(

View File

@ -40,7 +40,9 @@ extension _HomeScreenLaunch on _HomeScreenState {
required DateTime today,
}) async {
const stay = (open: false, syncedToday: false, syncNotSetUp: false);
// A run in progress opens its own screen (see `_load`).
if (!firstLoad || !widget.openWorkoutOnLaunch) return stay;
if (widget.openRunOnLaunch) return stay;
final wantsFresh = !hasSaved && !doneLocally && !lockModeEnabled;
if (!hasSaved && !wantsFresh) return stay;

View File

@ -16,11 +16,11 @@ extension _HomeScreenNavigation on _HomeScreenState {
/// Pushes the GPS run screen, then reloads (a finished run can change
/// today's credit once the PC has it).
Future<void> _openRun() async {
SandboxLog.event('open run screen');
await Navigator.of(
context,
).push(MaterialPageRoute<void>(builder: (_) => const RunScreen()));
Future<void> _openRun({bool resuming = false}) async {
SandboxLog.event('open run screen', {'resuming': resuming});
await Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => RunScreen(resuming: resuming)),
);
unawaited(_load());
}

View File

@ -8,46 +8,30 @@ library;
import 'dart:async';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart';
import 'package:latlong2/latlong.dart';
import 'package:material_ui/material_ui.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox_log.dart';
import 'package:workout_app/sandbox/sandbox_run_replay.dart';
import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/foreground_run_client.dart';
import 'package:workout_app/services/foreground_run_client_flutter.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/pace_target_store.dart';
import 'package:workout_app/services/run_controller.dart';
import 'package:workout_app/services/run_format.dart';
import 'package:workout_app/services/run_recorder.dart';
import 'package:workout_app/services/run_saver.dart';
import 'package:workout_app/services/run_phase.dart';
import 'package:workout_app/services/run_uploader.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/run_view.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/run_finish_dialog.dart';
import 'package:workout_app/widgets/run_map_slot.dart';
import 'package:workout_app/widgets/run_pace_picker.dart';
import 'package:workout_app/widgets/run_upload_badge.dart';
part 'run_screen_numbers.dart';
part 'run_screen_parts.dart';
/// The controller the app uses: real GPS (or the sandbox replay), the real
/// foreground service, the real database and the app-wide upload queue.
RunController buildRunController() => RunController(
sourceFor: positionSourceFor,
idleSourceFor: idlePositionSourceFor,
service: FlutterForegroundRunClient(),
cues: FeedbackCues(AudioPlayer()),
save: (track) => saveRecordedRun(
track,
storage: StorageService.instance,
enqueue: RunUploader.instance.uploadPending,
),
);
part 'run_screen_pulse.dart';
part 'run_screen_state.dart';
/// Builds the live map from the run's accepted points and the user's current
/// position (shown until the run has points).
@ -59,19 +43,29 @@ typedef RunMapBuilder =
);
/// Records one GPS activity (always a run).
///
/// The run itself lives in a host that outlasts this screen: leaving, closing
/// the app or replacing this screen never ends it. Only the finish button
/// followed by its confirm modal does.
class RunScreen extends StatefulWidget {
/// Creates the screen; every argument is a test or map seam.
const RunScreen({
super.key,
this.controllerFactory = buildRunController,
this.controllerFactory,
this.uploader,
this.paceStore,
this.mapBuilder,
this.openSettings = openAppSettings,
this.resuming = false,
});
/// The factory `main` installs: real GPS, the real service and database.
/// Set once at startup; tests pass [controllerFactory] instead.
static RunController Function()? defaultControllerFactory;
/// Builds the controller for a recording (called again for "new run").
final RunController Function() controllerFactory;
/// Defaults to [defaultControllerFactory].
final RunController Function()? controllerFactory;
/// The upload queue shown in the badge; defaults to the app-wide one.
final RunUploader? uploader;
@ -85,147 +79,14 @@ class RunScreen extends StatefulWidget {
/// Opens the system settings page for this app.
final Future<bool> Function() openSettings;
/// The app opened because a run is in progress: back does nothing until
/// the host has answered and the run is on screen.
final bool resuming;
@override
State<RunScreen> createState() => _RunScreenState();
}
class _RunScreenState extends State<RunScreen> with WidgetsBindingObserver {
late RunController _controller = widget.controllerFactory();
late final RunUploader _uploader = widget.uploader ?? RunUploader.instance;
late final PaceTargetStore _paceStore =
widget.paceStore ?? PrefsPaceTargetStore();
bool _starting = false;
bool _paceOn = false;
int _paceTarget = kDefaultPaceTarget;
@override
void initState() {
super.initState();
SandboxLog.event('open run');
WidgetsBinding.instance.addObserver(this);
unawaited(_controller.watchIdle());
unawaited(_loadPaceTarget());
// So the badge shows the real queue, not the pre-first-pass default.
unawaited(_uploader.uploadPending());
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_controller.dispose();
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// A silent re-check: the permission prompt itself backgrounds the app, so
// asking again here would loop.
if (state == AppLifecycleState.resumed) {
unawaited(_controller.recheckAccess());
}
}
Future<void> _loadPaceTarget() async {
final stored = await _paceStore.load();
if (mounted) setState(() => _paceTarget = stored);
}
void _setPaceTarget(int seconds) {
setState(() => _paceTarget = seconds);
unawaited(_paceStore.save(seconds));
}
Future<void> _start() async {
setState(() => _starting = true);
_controller.recorder.setPaceTarget(_paceOn ? _paceTarget : null);
try {
await _controller.start();
} finally {
if (mounted) setState(() => _starting = false);
}
}
void _again() {
final old = _controller;
setState(() => _controller = widget.controllerFactory());
unawaited(_controller.watchIdle());
old.dispose();
}
/// Fixable refusals open the system settings; a plain denial asks again.
VoidCallback? _issueTap(RunIssue issue) => switch (issue) {
RunIssue.deniedForever ||
RunIssue.serviceOff => () => unawaited(widget.openSettings()),
RunIssue.denied => () => unawaited(_controller.watchIdle()),
_ => null,
};
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: _controller,
builder: (context, _) {
final c = _controller;
final r = c.recorder;
final blocked = c.blocked;
final issue = _IssueButton(
issue: r.issue,
onTap: _issueTap(r.issue),
size: blocked ? 96 : 24,
);
return PopScope(
// A recording lives in this screen's controller: leaving would lose it.
canPop: !c.active,
child: Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(AppSpacing.md),
child: Column(
children: [
_StatusRow(
controller: c,
uploader: _uploader,
issue: blocked ? null : issue,
),
const SizedBox(height: AppSpacing.sm),
if (blocked)
Expanded(child: Center(child: issue))
else ...[
Expanded(
flex: 4,
child: KeyedSubtree(
key: ObjectKey(c),
child: (widget.mapBuilder ?? _defaultMap)(
context,
r.livePoints,
c.position,
),
),
),
const SizedBox(height: AppSpacing.md),
Expanded(flex: 3, child: _Numbers(recorder: r)),
const SizedBox(height: AppSpacing.md),
_Controls(
controller: c,
starting: _starting,
paceOn: _paceOn,
paceTarget: _paceTarget,
onPaceToggle: () => setState(() => _paceOn = !_paceOn),
onPaceChanged: _setPaceTarget,
onStart: () => unawaited(_start()),
onAgain: _again,
onClose: () => Navigator.of(context).maybePop(),
),
],
],
),
),
),
),
);
},
);
}
Widget _defaultMap(
BuildContext context,
ValueListenable<List<RunPoint>> points,

View File

@ -3,15 +3,15 @@
part of 'run_screen.dart';
class _Numbers extends StatelessWidget {
const _Numbers({required this.recorder});
const _Numbers({required this.view});
final RunRecorder recorder;
final RunView view;
/// Green on pace, red off it, plain while there is no verdict yet.
Color _paceColour(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final colors = Theme.of(context).extension<AppStatusColors>()!;
final band = recorder.coach.band;
final band = view.band;
if (band == null) return scheme.onSurface;
return band == PaceBand.onPace ? colors.success : scheme.error;
}
@ -44,14 +44,14 @@ class _Numbers extends StatelessWidget {
],
),
);
final current = recorder.coach.pace;
final current = view.pace;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Flexible(
child: big(
const Key('run_time'),
formatDuration(recorder.seconds),
formatDuration(view.seconds),
96,
scheme.onSurface,
),
@ -62,17 +62,14 @@ class _Numbers extends StatelessWidget {
small(
Icons.straighten,
const Key('run_distance'),
formatDistanceKm(recorder.distanceM),
formatDistanceKm(view.distanceM),
),
small(
Icons.speed,
const Key('run_pace'),
formatPace(
seconds: recorder.seconds,
distanceM: recorder.distanceM,
),
formatPace(seconds: view.seconds, distanceM: view.distanceM),
),
if (recorder.coach.target != null)
if (view.paceTarget != null)
small(
Icons.bolt,
const Key('run_pace_now'),

View File

@ -115,6 +115,7 @@ class _Controls extends StatelessWidget {
required this.onPaceToggle,
required this.onPaceChanged,
required this.onStart,
required this.onFinish,
required this.onAgain,
required this.onClose,
});
@ -126,12 +127,13 @@ class _Controls extends StatelessWidget {
final VoidCallback onPaceToggle;
final ValueChanged<int> onPaceChanged;
final VoidCallback onStart;
final VoidCallback onFinish;
final VoidCallback onAgain;
final VoidCallback onClose;
@override
Widget build(BuildContext context) {
final recorder = controller.recorder;
final view = controller.view;
final scheme = Theme.of(context).colorScheme;
Widget button(
String id,
@ -152,7 +154,13 @@ class _Controls extends StatelessWidget {
);
}
final buttons = switch (recorder.phase) {
// Advice to finish (stationary, vehicle speed, GPS lost, restored) only
// makes this button pulse: the run ends on the modal's check, nowhere else.
final finish = _PulsingFinish(
pulsing: view.suggestion != null,
child: button('finish', Icons.stop, onFinish, tint: scheme.error),
);
final buttons = switch (view.phase) {
RunPhase.idle => [
Flexible(
child: RunPacePicker(
@ -170,21 +178,11 @@ class _Controls extends StatelessWidget {
],
RunPhase.recording => [
button('pause', Icons.pause, controller.pause),
button(
'finish',
Icons.stop,
() => unawaited(controller.finish()),
tint: scheme.error,
),
finish,
],
RunPhase.paused => [
button('resume', Icons.play_arrow, controller.resume),
button(
'finish',
Icons.stop,
() => unawaited(controller.finish()),
tint: scheme.error,
),
finish,
],
RunPhase.finished => [
button('again', Icons.refresh, controller.saving ? null : onAgain),

View File

@ -0,0 +1,54 @@
// The finish button's pulse: the one cue that finishing is suggested.
part of 'run_screen.dart';
/// Pulses [child] while [pulsing]: the one cue the screen gives that finishing
/// is suggested. A symbol of motion, no words.
class _PulsingFinish extends StatefulWidget {
const _PulsingFinish({required this.pulsing, required this.child});
final bool pulsing;
final Widget child;
@override
State<_PulsingFinish> createState() => _PulsingFinishState();
}
class _PulsingFinishState extends State<_PulsingFinish>
with SingleTickerProviderStateMixin {
late final AnimationController _pulse = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 700),
lowerBound: 0.88,
);
@override
void initState() {
super.initState();
_sync();
}
@override
void didUpdateWidget(_PulsingFinish old) {
super.didUpdateWidget(old);
_sync();
}
void _sync() {
if (widget.pulsing && !_pulse.isAnimating) {
_pulse.repeat(reverse: true);
}
}
@override
void dispose() {
_pulse.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => ScaleTransition(
key: Key(widget.pulsing ? 'run_finish_pulse' : 'run_finish_still'),
scale: widget.pulsing ? _pulse : const AlwaysStoppedAnimation(1),
child: widget.child,
);
}

View File

@ -0,0 +1,177 @@
// The run screen's state: the controller's life, the finish modal, "new run".
part of 'run_screen.dart';
class _RunScreenState extends State<RunScreen> with WidgetsBindingObserver {
late RunController _controller = _build();
late final RunUploader _uploader = widget.uploader ?? RunUploader.instance;
late final PaceTargetStore _paceStore =
widget.paceStore ?? PrefsPaceTargetStore();
bool _starting = false;
bool _paceOn = false;
bool _asking = false;
int _paceTarget = kDefaultPaceTarget;
RunController _build() =>
(widget.controllerFactory ?? RunScreen.defaultControllerFactory!)();
@override
void initState() {
super.initState();
SandboxLog.event('open run');
WidgetsBinding.instance.addObserver(this);
_wire(_controller);
unawaited(_controller.watchIdle());
unawaited(_loadPaceTarget());
// So the badge shows the real queue, not the pre-first-pass default.
unawaited(_uploader.uploadPending());
}
/// Hears the host, so a notification tap or a started run reaches the
/// screen; asks it where the run stands.
void _wire(RunController c) {
c.addListener(_onControllerChanged);
unawaited(c.attach());
}
/// The notification asked for the finish modal: show it once.
void _onControllerChanged() {
if (_controller.view.promptFinish && !_asking && mounted) {
unawaited(_askFinish());
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_controller
..removeListener(_onControllerChanged)
// Hangs up only: the run is in the host and goes on.
..dispose();
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// A silent re-check: the permission prompt itself backgrounds the app, so
// asking again here would loop.
if (state == AppLifecycleState.resumed) {
unawaited(_controller.recheckAccess());
}
}
Future<void> _loadPaceTarget() async {
final stored = await _paceStore.load();
if (mounted) setState(() => _paceTarget = stored);
}
void _setPaceTarget(int seconds) {
setState(() => _paceTarget = seconds);
unawaited(_paceStore.save(seconds));
}
Future<void> _start() async {
setState(() => _starting = true);
try {
await _controller.start(paceTarget: _paceOn ? _paceTarget : null);
} finally {
if (mounted) setState(() => _starting = false);
}
}
/// The one way a run ends: the confirm modal's red check.
Future<void> _askFinish() async {
if (_asking) return;
_asking = true;
try {
if (_controller.view.promptFinish) _controller.ackPrompt();
final end = await showRunFinishDialog(context);
if (end && mounted) await _controller.finish();
} finally {
_asking = false;
}
}
void _again() {
final old = _controller..removeListener(_onControllerChanged);
setState(() => _controller = _build());
_wire(_controller);
unawaited(_controller.watchIdle());
// Hangs up the old link; a run still going in the host is untouched.
old.dispose();
}
/// Fixable refusals open the system settings; a plain denial asks again.
VoidCallback? _issueTap(RunIssue issue) => switch (issue) {
RunIssue.deniedForever ||
RunIssue.serviceOff => () => unawaited(widget.openSettings()),
RunIssue.denied => () => unawaited(_controller.watchIdle()),
_ => null,
};
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: _controller,
builder: (context, _) {
final c = _controller;
final v = c.view;
final blocked = c.blocked;
final issue = _IssueButton(
issue: v.issue,
onTap: _issueTap(v.issue),
size: blocked ? 96 : 24,
);
return PopScope(
// The run lives in the host, but the screen still refuses to be left
// while one is going (or while a resumed one has not shown up yet).
canPop: !c.active && !(widget.resuming && !c.attachGaveUp && !v.synced),
child: Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(AppSpacing.md),
child: Column(
children: [
_StatusRow(
controller: c,
uploader: _uploader,
issue: blocked ? null : issue,
),
const SizedBox(height: AppSpacing.sm),
if (blocked)
Expanded(child: Center(child: issue))
else ...[
Expanded(
flex: 4,
child: KeyedSubtree(
key: ObjectKey(c),
child: (widget.mapBuilder ?? _defaultMap)(
context,
v.livePoints,
c.position,
),
),
),
const SizedBox(height: AppSpacing.md),
Expanded(flex: 3, child: _Numbers(view: v)),
const SizedBox(height: AppSpacing.md),
_Controls(
controller: c,
starting: _starting,
paceOn: _paceOn,
paceTarget: _paceTarget,
onPaceToggle: () => setState(() => _paceOn = !_paceOn),
onPaceChanged: _setPaceTarget,
onStart: () => unawaited(_start()),
onFinish: () => unawaited(_askFinish()),
onAgain: _again,
onClose: () => Navigator.of(context).maybePop(),
),
],
],
),
),
),
),
);
},
);
}

View File

@ -20,8 +20,12 @@ import 'package:workout_app/services/foreground_break_client.dart';
Future<bool> stopStaleBreakService(
ForegroundBreakClient client, {
required Future<bool> Function() hasActiveWorkout,
required Future<bool> Function() runIsOwed,
}) async {
if (!client.isSupported) return false;
// The one foreground service may be hosting a run (it comes back after a
// kill, with no workout session): stopping it would end the run.
if (await runIsOwed()) return false;
if (!await client.isRunning()) return false;
if (await hasActiveWorkout()) return false;
log(

View File

@ -109,4 +109,29 @@ class FeedbackCues {
debugPrint('WorkoutApp: pace tone failed to play ($error).');
});
}
/// The recorder suggests finishing the run (stationary, vehicle speed, GPS
/// lost, restored): three buzzes and, if allowed, the chime. Advice only,
/// the run keeps going.
Future<void> finishSuggested() => _longCue('cue finish suggested');
/// The 5 h limit ended the run: the same buzz and chime as a suggestion, so
/// a phone in a pocket says something happened.
Future<void> autoEnded() => _longCue('cue run auto-ended');
Future<void> _longCue(String event) async {
SandboxLog.event(event, {'sound': soundOn});
if (await Vibration.hasVibrator()) {
// Android/iOS-only: hasVibrator() is false on the Linux test host.
// coverage:ignore-start
unawaited(Vibration.vibrate(pattern: [0, 300, 150, 300, 150, 300]));
// coverage:ignore-end
}
if (!soundOn) return;
await _player.play(AssetSource('sounds/workout_done.wav')).catchError((
Object error,
) {
debugPrint('WorkoutApp: $event chime failed to play ($error).');
});
}
}

View File

@ -1,6 +1,7 @@
/// The real foreground-service client, and the service's entry point.
library;
import 'dart:developer';
import 'dart:io' show Platform;
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
@ -12,6 +13,8 @@ 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';
import 'package:workout_app/services/run_checkpoint_location.dart';
import 'package:workout_app/services/run_wire.dart';
/// Channel the ongoing workout notification lives on.
///
@ -113,8 +116,12 @@ class FlutterForegroundBreakClient implements ForegroundBreakClient {
);
}
/// The shared service hosts a RUN while its checkpoint exists; this client
/// must neither see, replace nor stop it (stopping clears the options the
/// plugin keeps for a boot restart, and ends the run).
@override
Future<bool> isRunning() => FlutterForegroundTask.isRunningService;
Future<bool> isRunning() async =>
!await runIsOwed() && await FlutterForegroundTask.isRunningService;
@override
Future<bool> hasNotificationPermission() async =>
@ -128,6 +135,14 @@ class FlutterForegroundBreakClient implements ForegroundBreakClient {
@override
Future<bool> start(BreakSnapshot snapshot) async {
if (await runIsOwed()) {
log(
'WorkoutApp: a GPS run owns the foreground service, so the break '
'timer service was not started. The in-app countdown still works.',
level: 1000,
);
return false;
}
if (await FlutterForegroundTask.isRunningService) {
await FlutterForegroundTask.stopService();
}
@ -154,6 +169,7 @@ class FlutterForegroundBreakClient implements ForegroundBreakClient {
@override
Future<void> stop() async {
if (await runIsOwed()) return;
if (await FlutterForegroundTask.isRunningService) {
await FlutterForegroundTask.stopService();
}
@ -174,7 +190,10 @@ class FlutterForegroundBreakClient implements ForegroundBreakClient {
/// 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();
void _handleTaskData(Object data) {
// The run host shares this channel; its snapshots are not nudges.
if (!isRunMessage(data)) _onNudge?.call();
}
// coverage:ignore-end
}

View File

@ -1,11 +1,17 @@
/// The real run foreground-service client, and the service's entry point.
/// The real run foreground-service client and the UI's real link to its host.
library;
import 'dart:async';
import 'dart:io' show Platform;
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/services/break_notification_text.dart';
import 'package:workout_app/services/foreground_run_client.dart';
import 'package:workout_app/services/run_link.dart';
import 'package:workout_app/services/run_service_isolate.dart';
import 'package:workout_app/services/run_wire.dart';
import 'package:workout_app/services/storage_service.dart';
/// Channel the ongoing run notification lives on.
///
@ -15,32 +21,6 @@ import 'package:workout_app/services/foreground_run_client.dart';
/// shows it in system settings.
const kRunOngoingChannelId = 'run_ongoing_v1';
// coverage:ignore-start
/// Entry point the plugin calls in the background isolate.
///
/// The handler does nothing: the recorder lives in the UI isolate. The
/// service exists to keep that isolate's process alive, to hold the wake lock
/// and to own the notification.
@pragma('vm:entry-point')
void runServiceStartCallback() {
FlutterForegroundTask.setTaskHandler(_RunServiceTaskHandler());
}
class _RunServiceTaskHandler extends TaskHandler {
@override
Future<void> onStart(DateTime timestamp, TaskStarter starter) async {}
@override
void onRepeatEvent(DateTime timestamp) {}
@override
void onNotificationPressed() => FlutterForegroundTask.launchApp();
@override
Future<void> onDestroy(DateTime timestamp, bool isTimeout) async {}
}
// coverage:ignore-end
/// The real [ForegroundRunClient], driving `flutter_foreground_task`.
class FlutterForegroundRunClient implements ForegroundRunClient {
/// Creates a client. Cheap: nothing happens until [start].
@ -51,7 +31,8 @@ class FlutterForegroundRunClient implements ForegroundRunClient {
// 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 run_controller.dart, covered against a fake.
// lead here live in run_controller.dart and run_host.dart, covered against
// fakes.
// coverage:ignore-start
@override
@ -64,12 +45,16 @@ class FlutterForegroundRunClient implements ForegroundRunClient {
await FlutterForegroundTask.requestNotificationPermission() ==
NotificationPermission.granted;
/// Starts the service, or leaves a running one alone: a live service may be
/// hosting a run, and replacing it would end that run.
@override
Future<bool> start({
required bool withLocation,
required String title,
required String text,
}) async {
if (await FlutterForegroundTask.isRunningService) return true;
await _saveFlags();
FlutterForegroundTask.init(
androidNotificationOptions: AndroidNotificationOptions(
channelId: kRunOngoingChannelId,
@ -80,18 +65,17 @@ class FlutterForegroundRunClient implements ForegroundRunClient {
iosNotificationOptions: const IOSNotificationOptions(),
foregroundTaskOptions: ForegroundTaskOptions(
eventAction: ForegroundTaskEventAction.nothing(),
// The run must come back by itself after a reboot, and the plugin
// restarts a killed service (allowAutoRestart defaults to true).
// allowWakeLock stays at its default (true): it is why GPS fixes keep
// arriving with the screen off.
autoRunOnBoot: true,
),
);
if (await FlutterForegroundTask.isRunningService) {
await FlutterForegroundTask.stopService();
}
final result = await FlutterForegroundTask.startService(
serviceTypes: [
ForegroundServiceTypes.dataSync,
if (withLocation) ForegroundServiceTypes.location,
],
// `location` alone: Android 15 refuses a dataSync service from the boot
// broadcast, and dataSync has a 6 h budget a long run can exhaust.
serviceTypes: [ForegroundServiceTypes.location],
notificationTitle: title,
notificationText: text,
callback: runServiceStartCallback,
@ -99,6 +83,21 @@ class FlutterForegroundRunClient implements ForegroundRunClient {
return result is ServiceRequestSuccess;
}
Future<void> _saveFlags() async {
await FlutterForegroundTask.saveData(
key: kRunFlagSandbox,
value: Sandbox.enabled,
);
await FlutterForegroundTask.saveData(
key: kRunFlagReplayFactor,
value: Sandbox.runReplayFactor,
);
await FlutterForegroundTask.saveData(
key: kRunFlagSound,
value: await StorageService.instance.getSoundEnabled(),
);
}
@override
Future<void> update({required String title, required String text}) async {
await FlutterForegroundTask.updateService(
@ -116,3 +115,34 @@ class FlutterForegroundRunClient implements ForegroundRunClient {
// coverage:ignore-end
}
/// The UI's link to the host in the service isolate.
// coverage:ignore-start
class ServiceRunLink implements RunHostLink {
/// Listens for the host's messages until [close].
ServiceRunLink() {
FlutterForegroundTask.addTaskDataCallback(_onData);
}
final _out = StreamController<Map<Object?, Object?>>.broadcast();
void _onData(Object data) {
// The break service shares this channel; only run messages pass.
if (isRunMessage(data)) _out.add(data as Map<Object?, Object?>);
}
@override
Stream<Map<Object?, Object?>> get messages => _out.stream;
@override
void send(Map<String, Object?> command) =>
FlutterForegroundTask.sendDataToTask(command);
@override
Future<void> close() async {
FlutterForegroundTask.removeTaskDataCallback(_onData);
await _out.close();
}
}
// coverage:ignore-end

View File

@ -3,6 +3,7 @@ library;
import 'package:flutter/foundation.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/run_gap_bridge.dart';
import 'package:workout_app/services/run_math.dart';
/// Worst horizontal accuracy (metres, 68 % radius) a fix may report.
@ -65,14 +66,24 @@ enum FixVerdict {
/// Accumulates accepted points and their cumulative credited distance.
///
/// A step between two accepted points adds distance only when it is a moving
/// step (see [isMovingStep]): a dropout longer than [kMaxCreditGapSeconds]
/// and standing-still jitter credit nothing. The PC judges windows of 10 s or
/// more and keeps a dropout moving at 1 m/s or faster, so it can credit more
/// than this does (see `run_math.dart`).
/// step (see [isMovingStep]): standing-still jitter credits nothing. A gap
/// over [kMaxCreditGapSeconds] (phone dead, GPS dropout) is bridged by a
/// straight line, always kept, credited only at a plausible pace
/// ([bridgeCredits]); the jump cap does not apply across it.
class GpsFilter {
/// Creates a filter; every recording uses the running jump cap.
GpsFilter();
/// Rebuilds a filter from a checkpoint: the [points] so far, whether a
/// pause is still waiting for its next fix, and the jump count.
GpsFilter.restore({
required List<RunPoint> points,
this._segmentBreak = false,
this._jumps = 0,
}) {
_points.addAll(points);
}
final List<RunPoint> _points = [];
int _jumps = 0;
bool _segmentBreak = false;
@ -80,6 +91,12 @@ class GpsFilter {
/// Accepted points so far, in time order.
List<RunPoint> get points => List.unmodifiable(_points);
/// Whether the next accepted fix starts a new segment (a pause is open).
bool get segmentBreak => _segmentBreak;
/// Consecutive too-fast fixes seen since the last accepted one.
int get jumps => _jumps;
/// Cumulative credited distance in metres.
double get distanceM => _points.isEmpty ? 0 : _points.last.distanceM;
@ -103,7 +120,7 @@ class GpsFilter {
isUtc: true,
);
if (_points.isEmpty) {
_accept(fix, time, 0);
_accept(fix, time, 0, RunLink.continuous);
return FixVerdict.accepted;
}
final last = _points.last;
@ -111,7 +128,7 @@ class GpsFilter {
if (gap <= 0) return FixVerdict.outOfOrder;
if (_segmentBreak) {
_segmentBreak = false;
_accept(fix, time, 0);
_accept(fix, time, 0, RunLink.segmentStart);
return FixVerdict.accepted;
}
final step = haversineM(
@ -120,20 +137,24 @@ class GpsFilter {
fix.latitude,
fix.longitude,
);
if (gap > kMaxCreditGapSeconds) {
final credited = bridgeCredits(stepM: step, gapSeconds: gap);
_accept(fix, time, credited ? step : 0, RunLink.bridge);
return FixVerdict.accepted;
}
if (step / gap > kRunningMaxSpeedMps) {
_jumps++;
if (_jumps < kMaxConsecutiveJumps) return FixVerdict.tooFast;
// The anchor, not the fixes, was wrong: continue from here, no credit.
_accept(fix, time, 0);
_accept(fix, time, 0, RunLink.segmentStart);
return FixVerdict.accepted;
}
final moving =
gap <= kMaxCreditGapSeconds && step / gap >= kMinMovingSpeedMps;
_accept(fix, time, moving ? step : 0);
final moving = step / gap >= kMinMovingSpeedMps;
_accept(fix, time, moving ? step : 0, RunLink.continuous);
return FixVerdict.accepted;
}
void _accept(GpsFix fix, DateTime time, double credited) {
void _accept(GpsFix fix, DateTime time, double credited, RunLink link) {
_jumps = 0;
_points.add(
RunPoint(
@ -142,6 +163,7 @@ class GpsFilter {
longitude: fix.longitude,
altitudeM: fix.altitudeM,
distanceM: distanceM + credited,
link: link,
),
);
}

View File

@ -0,0 +1,168 @@
/// Everything needed to rebuild a [RunRecorder] after the process died.
///
/// The recorder offers one after every accepted fix and on pause or resume;
/// the host stores it (see `run_checkpoint_store.dart`). The JSON is versioned
/// and strict: [RunCheckpoint.fromJson] throws a [FormatException] on anything
/// it does not understand, so a damaged file is reported, never half-read.
library;
import 'package:flutter/foundation.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/run_phase.dart';
/// The JSON layout version written by [RunCheckpoint.toJson].
const int kCheckpointVersion = 1;
/// A snapshot of an active run: recording or paused.
@immutable
class RunCheckpoint {
/// Creates a checkpoint; times are normalised to UTC.
RunCheckpoint({
required DateTime startedAt,
required DateTime savedAt,
required this.phase,
required this.points,
required this.movingSeconds,
required this.distanceM,
required this.km,
required this.segmentBreak,
required this.jumps,
this.paceTargetSeconds,
}) : startedAt = startedAt.toUtc(),
savedAt = savedAt.toUtc();
/// Reads a checkpoint written by [toJson]; throws [FormatException] when
/// [json] is of another version, is missing a field or has a wrong type.
factory RunCheckpoint.fromJson(Map<String, Object?> json) {
if (json['v'] != kCheckpointVersion) {
throw FormatException('unsupported checkpoint version ${json['v']}');
}
final phase = RunPhase.values.asNameMap()[_field<String>(json, 'phase')];
if (phase != RunPhase.recording && phase != RunPhase.paused) {
throw FormatException('checkpoint phase ${json['phase']} is not active');
}
return RunCheckpoint(
startedAt: _time(json, 'startedAt'),
savedAt: _time(json, 'savedAt'),
phase: phase!,
points: [
for (final p in _field<List<Object?>>(json, 'points')) _point(p),
],
movingSeconds: _field<int>(json, 'moving'),
distanceM: _field<num>(json, 'distance').toDouble(),
km: _field<int>(json, 'km'),
segmentBreak: _field<bool>(json, 'segBreak'),
jumps: _field<int>(json, 'jumps'),
paceTargetSeconds: _optional<int>(json, 'target'),
);
}
/// When the run began (wall clock, UTC); the auto-end is measured from it.
final DateTime startedAt;
/// When this snapshot was taken (UTC).
final DateTime savedAt;
/// Recording or paused.
final RunPhase phase;
/// Accepted points so far, with their segment and bridge markers.
final List<RunPoint> points;
/// Credited moving time in seconds.
final int movingSeconds;
/// Credited distance in metres.
final double distanceM;
/// Whole kilometres already announced.
final int km;
/// Whether a pause is still waiting for its next fix (starts a segment).
final bool segmentBreak;
/// Consecutive too-fast fixes the filter had seen.
final int jumps;
/// The pace target in seconds per kilometre, or null when off.
final int? paceTargetSeconds;
/// The track id the run will save under (its first point, else its start).
String get id =>
RunTrack.idFor(points.isEmpty ? startedAt : points.first.time);
/// A JSON-encodable form, read back by [RunCheckpoint.fromJson].
Map<String, Object?> toJson() => {
'v': kCheckpointVersion,
'id': id,
'startedAt': startedAt.toIso8601String(),
'savedAt': savedAt.toIso8601String(),
'phase': phase.name,
'moving': movingSeconds,
'distance': distanceM,
'km': km,
'segBreak': segmentBreak,
'jumps': jumps,
'target': paceTargetSeconds,
// [epoch ms, lat, lon, altitude|null, credited distance, link index]
'points': [
for (final p in points)
[
p.time.millisecondsSinceEpoch,
p.latitude,
p.longitude,
p.altitudeM,
p.distanceM,
p.link.index,
],
],
};
}
T _field<T>(Map<String, Object?> json, String key) {
final value = json[key];
if (value is T) return value;
throw FormatException('checkpoint field "$key" is missing or not a $T');
}
T? _optional<T>(Map<String, Object?> json, String key) {
final value = json[key];
if (value == null || value is T) return value as T?;
throw FormatException('checkpoint field "$key" is not a $T');
}
DateTime _time(Map<String, Object?> json, String key) {
final parsed = DateTime.tryParse(_field<String>(json, key));
if (parsed == null) throw FormatException('checkpoint "$key" is no time');
return parsed;
}
RunPoint _point(Object? raw) {
if (raw is! List<Object?> || raw.length != 6) {
throw FormatException('checkpoint point $raw is not 6 values');
}
final ms = raw[0];
final lat = raw[1];
final lon = raw[2];
final alt = raw[3];
final dist = raw[4];
final link = raw[5];
if (ms is! int ||
lat is! num ||
lon is! num ||
(alt != null && alt is! num) ||
dist is! num ||
link is! int ||
link < 0 ||
link >= RunLink.values.length) {
throw FormatException('checkpoint point $raw has a bad value');
}
return RunPoint(
time: DateTime.fromMillisecondsSinceEpoch(ms, isUtc: true),
latitude: lat.toDouble(),
longitude: lon.toDouble(),
altitudeM: (alt as num?)?.toDouble(),
distanceM: dist.toDouble(),
link: RunLink.values[link],
);
}

View File

@ -0,0 +1,24 @@
// coverage:ignore-file
// A path_provider lookup only the phone can answer; the logic around it is
// tested against in-memory stores.
/// Where the active run's checkpoint lives on disk, for every isolate.
library;
import 'dart:io';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:workout_app/services/run_checkpoint_store.dart';
/// Opens the one checkpoint file of the app (shared by the UI isolate, the
/// service isolate and the boot path).
Future<RunCheckpointStore> openRunCheckpointStore() async {
final dir = await getApplicationSupportDirectory();
return FileRunCheckpointStore(File(p.join(dir.path, 'run_checkpoint.json')));
}
/// Whether a run is owed: its checkpoint is on disk. While true the shared
/// foreground service belongs to the run, and nothing else may stop or
/// replace it.
Future<bool> runIsOwed() async =>
await (await openRunCheckpointStore()).load() != null;

View File

@ -0,0 +1,121 @@
/// Where the run's checkpoint lives between process deaths.
library;
import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'package:workout_app/services/run_checkpoint.dart';
/// Keeps the newest [RunCheckpoint] of the run in progress.
abstract interface class RunCheckpointStore {
/// Replaces the stored checkpoint with [c].
Future<void> save(RunCheckpoint c);
/// The stored checkpoint, or null when there is none (or it was corrupt).
Future<RunCheckpoint?> load();
/// Forgets the checkpoint: the run ended and was saved.
Future<void> clear();
}
/// A store in memory, for tests and hosts that keep nothing on disk.
class MemoryRunCheckpointStore implements RunCheckpointStore {
RunCheckpoint? _held;
@override
Future<void> save(RunCheckpoint c) async => _held = c;
@override
Future<RunCheckpoint?> load() async => _held;
@override
Future<void> clear() async => _held = null;
}
void _logLoud(String message) => log(message, level: 1000);
/// One JSON file, written atomically (temp file, then rename) so a kill
/// mid-write leaves the previous checkpoint whole.
///
/// Saves are coalesced: while one write is in flight, later saves replace
/// each other and only the newest is written next, so the 2 s fix stream
/// can never queue up writes behind a slow disk.
class FileRunCheckpointStore implements RunCheckpointStore {
/// A store at [file]. [clock] stamps the name of a corrupt file moved
/// aside; [onLoud] hears every problem (default: a level-1000 log).
FileRunCheckpointStore(
this.file, {
this._clock = DateTime.now,
void Function(String message) onLoud = _logLoud,
}) : _loud = onLoud;
/// The checkpoint file.
final File file;
final DateTime Function() _clock;
final void Function(String message) _loud;
RunCheckpoint? _newest;
Future<void>? _draining;
File get _tmp => File('${file.path}.tmp');
@override
Future<void> save(RunCheckpoint c) {
_newest = c;
return _draining ??= _drain();
}
Future<void> _drain() async {
try {
while (_newest != null) {
final c = _newest!;
_newest = null;
await _write(c);
}
} finally {
_draining = null;
}
}
Future<void> _write(RunCheckpoint c) async {
await file.parent.create(recursive: true);
await _tmp.writeAsString(jsonEncode(c.toJson()), flush: true);
await _tmp.rename(file.path);
}
@override
Future<RunCheckpoint?> load() async {
if (!file.existsSync()) return null;
try {
final json = jsonDecode(utf8.decode(await file.readAsBytes()));
if (json is! Map<String, Object?>) {
throw FormatException(
'top level is ${json.runtimeType}, not an object',
);
}
return RunCheckpoint.fromJson(json);
} on FormatException catch (e) {
log('RunCheckpointStore: corrupt checkpoint (${e.message})', level: 1000);
await _moveAside(e);
return null;
}
}
Future<void> _moveAside(FormatException why) async {
final aside = '${file.path}.corrupt-${_clock().millisecondsSinceEpoch}';
await file.rename(aside);
_loud(
'RunCheckpointStore: the run checkpoint is corrupt (${why.message}); '
'moved to $aside and starting without it. The run it held is lost.',
);
}
@override
Future<void> clear() async {
for (final f in [file, _tmp]) {
if (f.existsSync()) await f.delete();
}
}
}

View File

@ -1,5 +1,9 @@
/// Wires one recording to the phone: permission, foreground service, cues,
/// notification and the save at the end.
/// The run screen's side of a recording: location access, the foreground
/// service, the link to the host that holds the run, and the view of it.
///
/// The recording itself (GPS stream, numbers, checkpoint, cues, the save)
/// lives in the host. This controller can be disposed, replaced or killed at
/// any moment without touching the run: [dispose] only hangs up.
library;
import 'dart:async';
@ -7,74 +11,84 @@ import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:latlong2/latlong.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/foreground_run_client.dart';
import 'package:workout_app/services/idle_location.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_link.dart';
import 'package:workout_app/services/run_notification.dart';
import 'package:workout_app/services/run_recorder.dart';
import 'package:workout_app/services/run_phase.dart';
import 'package:workout_app/services/run_saver.dart';
import 'package:workout_app/services/run_view.dart';
import 'package:workout_app/services/run_wire.dart';
/// Owns a [RunRecorder] and everything that must happen around it.
/// How long a command waits for the host before the screen stops waiting.
const kRunHostTimeout = Duration(seconds: 20);
/// Owns the [RunView] and everything the UI must do around a recording.
///
/// Order matters at the start: location access first (the recorder asks), then
/// the foreground service (Android 14 refuses a `location` service without
/// the permission), then the first fix.
/// Order matters at the start: location access first, then the foreground
/// service (Android 14 refuses a `location` service without the permission),
/// then the host's first fix.
class RunController extends ChangeNotifier {
/// Creates a controller; it builds its own [recorder] over [sourceFor].
///
/// [idleSourceFor] feeds the idle map before the run (display only); it
/// defaults to [sourceFor].
/// Creates a controller over [link]; [idleSourceFor] feeds the idle map.
RunController({
required PositionSource Function() sourceFor,
required PositionSource Function() idleSourceFor,
required this._service,
required this._cues,
required this._save,
PositionSource Function()? idleSourceFor,
required this._link,
required this._soundOn,
this.hostTimeout = kRunHostTimeout,
this.retryEvery = const Duration(milliseconds: 750),
}) {
recorder = RunRecorder(
sourceFor: sourceFor,
onKilometre: _onKilometre,
onPaceCue: _onPaceCue,
)..addListener(_onRecorderChanged);
_idle = IdleLocation((idleSourceFor ?? sourceFor)(), onAccess: _onAccess);
_idle = IdleLocation(idleSourceFor(), onAccess: _onAccess);
view.addListener(notifyListeners);
view.onNeedSync = _hello;
_sub = _link.messages.listen(_onMessage);
}
/// The state machine; the live map reads its points.
late final RunRecorder recorder;
/// What the screen shows.
final view = RunView();
/// How long to wait for the host, and how often [attach] asks again.
final Duration hostTimeout;
/// See [hostTimeout].
final Duration retryEvery;
late final IdleLocation _idle;
final ForegroundRunClient _service;
final FeedbackCues _cues;
final Future<RunSaveResult> Function(RunTrack track) _save;
final RunHostLink _link;
final Future<bool> Function() _soundOn;
late final StreamSubscription<Map<Object?, Object?>> _sub;
RunServiceState _serviceState = RunServiceState.none;
RunSaveResult? _saved;
bool _saving = false;
String _lastCopy = '';
bool _disposed = false;
Timer? _pauseTimer;
Completer<void>? _pauseDone;
/// The host never answered the screen's questions: nothing is there.
bool attachGaveUp = false;
/// Whether the foreground service is up (and with a notification).
RunServiceState get serviceState => _serviceState;
/// What saving the finished run did, once it ran.
RunSaveResult? get saved => _saved;
RunSaveResult? get saved => view.saved == null
? null
: RunSaveResult(stored: view.saved!.stored, reason: view.saved!.reason);
/// True while the finished run is being written.
bool get saving => _saving;
bool get saving =>
view.saving || (view.phase == RunPhase.finished && !view.done);
/// True from start to finish: the screen must not be left meanwhile.
bool get active => recorder.phase.isActive;
bool get active => view.phase.isActive;
/// Where the user is before the run starts (display only, never recorded).
ValueListenable<LatLng?> get position => _idle.position;
/// True while location is refused and the run has not started: the screen
/// shows only the problem icon, no map and no start.
bool get blocked =>
recorder.phase == RunPhase.idle && recorder.issue.isAccess;
bool get blocked => view.phase == RunPhase.idle && view.issue.isAccess;
/// Whether access has been found granted, so a start cannot race a prompt.
bool get canStart => _idle.access?.isGranted ?? false;
@ -85,45 +99,90 @@ class RunController extends ChangeNotifier {
/// Re-reads the access silently (the app came back to the foreground).
Future<void> recheckAccess() =>
recorder.phase == RunPhase.idle ? _idle.recheck() : Future.value();
view.phase == RunPhase.idle ? _idle.recheck() : Future.value();
/// Asks for access, starts the service, begins recording.
Future<void> start() async {
/// Asks the host where the run stands (and keeps asking until it answers:
/// a restarted service needs a moment to come up).
Future<void> attach() async {
for (var i = 0; i < 8 && !view.synced && !_disposed; i++) {
_hello();
await _pause(i == 0 ? Duration.zero : retryEvery);
}
if (!view.synced && !_disposed) {
attachGaveUp = true;
_serviceState = RunServiceState.none;
}
if (!_disposed) notifyListeners();
}
/// Asks for access, starts the service, begins recording. A run that is
/// already going is never restarted.
Future<void> start({int? paceTarget}) async {
if (view.phase.isActive) return;
await _idle.stop();
await _cues.load();
final started = await recorder.start(afterAccess: _startService);
await _startService();
await attach();
_link.send({
'cmd': RunCmd.start,
'paceTarget': paceTarget,
'sound': await _soundOn(),
});
await _until(() => view.phase.isActive || view.issue != RunIssue.none);
// A refused start leaves the screen blocked; let a resume recheck it.
if (!started && recorder.issue.isAccess) _idle.reopen();
if (!view.phase.isActive && view.issue.isAccess) _idle.reopen();
}
/// Pauses crediting.
void pause() => recorder.pause();
void pause() => _link.send({'cmd': RunCmd.pause});
/// Resumes crediting.
void resume() => recorder.resume();
void resume() => _link.send({'cmd': RunCmd.resume});
/// Ends the run, stops the service and saves the track.
/// Changes the pace target of a running recording.
void setPaceTarget(int? seconds) =>
_link.send({'cmd': RunCmd.paceTarget, 'paceTarget': seconds});
/// Tells the host the finish modal the notification asked for is showing.
void ackPrompt() => _link.send({'cmd': RunCmd.ackPrompt});
/// Ends the run and waits until the host has saved it. Only the screen's
/// confirm modal calls this.
Future<void> finish() async {
final track = await recorder.finish();
await _stopService();
if (track == null) return;
unawaited(_cues.workoutFinished());
_saving = true;
notifyListeners();
try {
_saved = await _save(track);
} on Exception catch (error, stack) {
log(
'RunController: saving ${track.id} failed ($error) -- the run is '
'lost unless it is recorded again.',
level: 1000,
error: error,
stackTrace: stack,
);
_saved = RunSaveResult(stored: false, reason: 'save failed: $error');
_link.send({'cmd': RunCmd.finish});
await _until(() => view.phase == RunPhase.finished && view.done);
if (view.phase == RunPhase.finished && !_disposed) {
if (_serviceState.isUp) _serviceState = RunServiceState.none;
notifyListeners();
}
_saving = false;
notifyListeners();
}
/// Waits [length], or until [dispose] (so no timer outlives the screen).
Future<void> _pause(Duration length) {
final done = Completer<void>();
_pauseTimer = Timer(length, done.complete);
_pauseDone = done;
return done.future;
}
void _hello() => _link.send({'cmd': RunCmd.hello});
void _onMessage(Map<Object?, Object?> message) {
if (!isRunMessage(message)) return;
view.apply(message);
if (view.phase.isActive && _serviceState == RunServiceState.none) {
_serviceState = RunServiceState.running;
}
}
Future<void> _until(bool Function() done) async {
if (await view.waitUntil(done, hostTimeout)) return;
log(
'RunController: the run host did not answer within '
'${hostTimeout.inSeconds}s (phase ${view.phase.name}, issue '
'${view.issue.name}). The run itself is not touched; reopen the '
'screen to ask again.',
level: 1000,
);
}
Future<void> _startService() async {
@ -141,9 +200,8 @@ class RunController extends ChangeNotifier {
);
}
final copy = runNotificationCopy(metres: 0, movingSeconds: 0);
_lastCopy = '${copy.title}|${copy.body}';
final started = await _service.start(
withLocation: !Sandbox.enabled,
withLocation: true,
title: copy.title,
text: copy.body,
);
@ -161,47 +219,24 @@ class RunController extends ChangeNotifier {
: RunServiceState.runningHidden;
}
Future<void> _stopService() async {
if (!_serviceState.isUp) return;
await _service.stop();
_serviceState = RunServiceState.none;
notifyListeners();
}
void _onKilometre(int km) => unawaited(_cues.kilometreReached(km));
void _onPaceCue(PaceCue cue) => unawaited(_cues.paceOff(cue));
void _onAccess(LocationAccess access) {
recorder.noteAccess(access);
// canStart follows the access, which the recorder does not report.
notifyListeners();
}
void _onRecorderChanged() {
if (_serviceState == RunServiceState.running) {
final copy = runNotificationCopy(
metres: recorder.distanceM,
movingSeconds: recorder.seconds,
currentPace: recorder.coach.target == null ? null : recorder.coach.pace,
);
// Only when the words changed: an update per fix would redraw twice a
// second for nothing.
if ('${copy.title}|${copy.body}' != _lastCopy) {
_lastCopy = '${copy.title}|${copy.body}';
unawaited(_service.update(title: copy.title, text: copy.body));
}
}
view.noteAccess(access);
// canStart follows the access, which the view does not report.
notifyListeners();
}
/// Hangs up. The run, if any, goes on in the host.
@override
void dispose() {
_disposed = true;
_pauseTimer?.cancel();
if (_pauseDone case final done? when !done.isCompleted) done.complete();
unawaited(_sub.cancel());
unawaited(_idle.dispose());
recorder
..removeListener(_onRecorderChanged)
unawaited(_link.close());
view
..removeListener(notifyListeners)
..dispose();
if (active) unawaited(_service.stop());
super.dispose();
}
}

View File

@ -0,0 +1,92 @@
/// The recording the run host drives, as an interface.
///
/// The host (service isolate in production) never touches `RunRecorder`
/// directly: every call into it goes through `run_engine_recorder.dart`, so
/// the host is tested against a fake and a change to the recorder lands in one
/// adapter.
library;
import 'package:flutter/foundation.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/run_checkpoint.dart';
import 'package:workout_app/services/run_phase.dart';
/// What a recording tells its host while it runs.
class RunEngineHooks {
/// Creates the hooks.
const RunEngineHooks({
required this.onKilometre,
required this.onPaceCue,
required this.onSuggest,
required this.onAutoEnd,
});
/// A whole kilometre was credited (1, 2, 3 ...).
final void Function(int km) onKilometre;
/// The runner left the pace band.
final void Function(PaceCue cue) onPaceCue;
/// Advice to finish, named after the recorder's suggestion
/// (`stationary`, `vehicleSpeed`, `gpsLost`, `restored`). Never ends a run.
final void Function(String why) onSuggest;
/// The 5 h limit passed; the host finishes the run like a manual finish.
final void Function() onAutoEnd;
}
/// One recording: a state machine over a position source.
abstract interface class RunEngine implements Listenable {
/// Where the recording stands.
RunPhase get phase;
/// The current problem, or [RunIssue.none].
RunIssue get issue;
/// Accepted points so far, oldest first.
List<RunPoint> get points;
/// Credited moving time in seconds.
int get seconds;
/// Credited distance in metres.
double get distanceM;
/// The pace target in seconds per kilometre, or null.
int? get paceTarget;
/// The current pace in seconds per kilometre, once warmed up.
double? get pace;
/// Where [pace] stands against [paceTarget].
PaceBand? get band;
/// A snapshot to rebuild the run from, or null when idle or finished.
RunCheckpoint? checkpoint();
/// Asks for access and begins recording; false when refused or busy.
Future<bool> start();
/// Resumes the run from [checkpoint] without prompting; false when it
/// cannot (the reason is logged by the engine).
Future<bool> restore(RunCheckpoint checkpoint);
/// Stops crediting until [resume].
void pause();
/// Continues after [pause].
void resume();
/// Sets the pace target (null turns it off).
void setPaceTarget(int? seconds);
/// Ends the recording; the track, or null when there were too few fixes.
Future<RunTrack?> finish();
/// Releases the position stream.
void dispose();
}
/// Builds a fresh engine wired to [hooks].
typedef RunEngineFactory = RunEngine Function(RunEngineHooks hooks);

View File

@ -0,0 +1,94 @@
/// The one place the run host meets `RunRecorder`: an adapter from the
/// recorder's API to [RunEngine].
library;
import 'package:flutter/foundation.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_checkpoint.dart';
import 'package:workout_app/services/run_engine.dart';
import 'package:workout_app/services/run_recorder.dart';
/// A [RunEngine] over a [RunRecorder].
class RunRecorderEngine implements RunEngine {
/// Wraps [recorder].
RunRecorderEngine(this._recorder);
final RunRecorder _recorder;
@override
RunPhase get phase => _recorder.phase;
@override
RunIssue get issue => _recorder.issue;
@override
List<RunPoint> get points => _recorder.livePoints.value;
@override
int get seconds => _recorder.seconds;
@override
double get distanceM => _recorder.distanceM;
@override
int? get paceTarget => _recorder.coach.target;
@override
double? get pace => _recorder.coach.pace;
@override
PaceBand? get band => _recorder.coach.band;
@override
RunCheckpoint? checkpoint() => _recorder.checkpoint();
@override
Future<bool> start() => _recorder.start();
@override
Future<bool> restore(RunCheckpoint checkpoint) =>
_recorder.restore(checkpoint);
@override
void pause() => _recorder.pause();
@override
void resume() => _recorder.resume();
@override
void setPaceTarget(int? seconds) => _recorder.setPaceTarget(seconds);
@override
Future<RunTrack?> finish() => _recorder.finish();
@override
void dispose() => _recorder.dispose();
@override
void addListener(VoidCallback listener) => _recorder.addListener(listener);
@override
void removeListener(VoidCallback listener) =>
_recorder.removeListener(listener);
}
/// Builds recorders over [sourceFor]; [clock] and [autoEndAfter] are the
/// recorder's own seams (shrunk by tests and the sandbox).
RunEngineFactory recorderEngineFactory(
PositionSource Function() sourceFor, {
DateTime Function() clock = DateTime.now,
Duration autoEndAfter = const Duration(hours: 5),
}) =>
(hooks) => RunRecorderEngine(
RunRecorder(
sourceFor: sourceFor,
onKilometre: hooks.onKilometre,
onPaceCue: hooks.onPaceCue,
onSuggestFinish: (why) => hooks.onSuggest(why.name),
onAutoEnd: hooks.onAutoEnd,
clock: clock,
autoEndAfter: autoEndAfter,
),
);

View File

@ -0,0 +1,28 @@
/// When a straight line across a gap in the fixes may credit distance.
///
/// A gap is any stretch over `kMaxCreditGapSeconds` between two accepted fixes
/// that the runner did not pause: the phone died and was restored, or GPS
/// dropped out. The recorder always draws the line from the last fix before
/// the gap to the first one after it; it credits the distance (and the gap's
/// time as moving time) only when the implied pace is a plausible run.
library;
/// Fastest pace a bridge may credit, in seconds per kilometre (2:30 min/km).
/// Faster is a vehicle: the line is drawn, nothing is credited.
const int kBridgeFastestSecPerKm = 150;
/// Slowest pace a bridge may credit, in seconds per kilometre (12:00 min/km).
/// Slower is standing about, not a run.
const int kBridgeSlowestSecPerKm = 720;
/// The slowest speed a credited bridge can have, in metres per second.
const double kBridgeMinSpeedMps = 1000 / kBridgeSlowestSecPerKm;
/// Whether a bridge of [stepM] straight-line metres over [gapSeconds] is
/// credited: its pace lies within 2:30 and 12:00 min/km, bounds included.
bool bridgeCredits({required double stepM, required int gapSeconds}) {
if (stepM <= 0 || gapSeconds <= 0) return false;
final secPerKm = gapSeconds * 1000 / stepM;
return secPerKm >= kBridgeFastestSecPerKm &&
secPerKm <= kBridgeSlowestSecPerKm;
}

View File

@ -0,0 +1,250 @@
/// The one place a recording lives: owns the engine, keeps its checkpoint,
/// gives the cues and writes the finished run.
///
/// In production this runs in the foreground-service isolate, so a swiped-away
/// app or a dead process cannot end a run: only [RunCmd.finish] (after the
/// confirm modal) or the 5 h limit does. On Linux and in tests it runs in the
/// UI isolate behind a loopback link.
library;
import 'dart:async';
import 'dart:developer';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/run_checkpoint_store.dart';
import 'package:workout_app/services/run_engine.dart';
import 'package:workout_app/services/run_host_port.dart';
import 'package:workout_app/services/run_notification.dart';
import 'package:workout_app/services/run_phase.dart';
import 'package:workout_app/services/run_wire.dart';
export 'package:workout_app/services/run_host_port.dart';
/// Hosts one recording at a time.
class RunHost {
/// Creates a host; nothing happens until a command or [restoreFromStore].
RunHost({
required this.engineFactory,
required this.port,
required this.store,
required this.cues,
required this.save,
});
/// Builds the recording.
final RunEngineFactory engineFactory;
/// Where messages and the notification go.
final RunHostPort port;
/// Where the active run's checkpoint lives.
final RunCheckpointStore store;
/// The sounds and buzzes.
final FeedbackCues cues;
/// Writes a finished track to the database.
final RunSaveFn save;
RunEngine? _engine;
int _sent = 0;
String? _suggestion;
bool _prompt = false;
bool _saving = false;
bool _finishing = false;
bool _done = false;
({bool stored, String reason})? _saved;
String _lastCopy = '';
/// Resumes the run the checkpoint describes. False when there is none (the
/// caller then has nothing to host).
Future<bool> restoreFromStore() async {
final checkpoint = await store.load();
if (checkpoint == null) return false;
final engine = _fresh();
if (!await engine.restore(checkpoint)) {
log(
'RunHost: the checkpoint could not be resumed (${engine.issue.name}); '
'it is kept, and the run screen shows the problem.',
level: 1000,
);
}
_emit(full: true);
return true;
}
/// Applies one UI command.
Future<void> handle(Map<Object?, Object?> message) async {
switch (message['cmd']) {
case RunCmd.hello:
_engine ?? _fresh();
_emit(full: true);
case RunCmd.start:
await _start(message);
case RunCmd.pause:
_engine?.pause();
case RunCmd.resume:
_engine?.resume();
case RunCmd.paceTarget:
_engine?.setPaceTarget(message['paceTarget'] as int?);
case RunCmd.ackPrompt:
_prompt = false;
_emit();
case RunCmd.finish:
await _finish(auto: false);
default:
log('RunHost: unknown command ${message['cmd']} ignored.', level: 900);
}
}
/// The ongoing notification was tapped: with advice standing, the UI opens
/// on the finish modal (it still needs the check tap).
void notificationPressed() {
if (_suggestion != null) {
_prompt = true;
_emit();
}
port.launchApp();
}
RunEngine _fresh() {
_engine
?..removeListener(_onChanged)
..dispose();
_sent = 0;
_suggestion = null;
_prompt = false;
_saved = null;
_saving = false;
_done = false;
return _engine = engineFactory(
RunEngineHooks(
onKilometre: (km) => unawaited(cues.kilometreReached(km)),
onPaceCue: (cue) => unawaited(cues.paceOff(cue)),
onSuggest: _suggest,
onAutoEnd: () => unawaited(_finish(auto: true)),
),
)..addListener(_onChanged);
}
Future<void> _start(Map<Object?, Object?> message) async {
final current = _engine;
if (current != null && current.phase.isActive) {
// A second "start" can never restart a live run: it only re-syncs.
return _emit(full: true);
}
// Reuse the idle engine a "hello" made; anything else starts clean.
final engine = current != null && current.phase == RunPhase.idle
? current
: _fresh();
final zero = runNotificationCopy(metres: 0, movingSeconds: 0);
_lastCopy = '${zero.title}|${zero.body}';
cues.soundOn = message['sound'] as bool? ?? true;
engine.setPaceTarget(message['paceTarget'] as int?);
await engine.start();
_emit(full: true);
}
void _suggest(String why) {
if (_finishing) return;
_suggestion = why;
unawaited(cues.finishSuggested());
_onChanged();
}
void _onChanged() {
final engine = _engine;
if (engine == null) return;
if (engine.phase.isActive) {
saveCheckpointLoudly(store, engine.checkpoint());
_redrawNotification(engine);
}
_emit();
}
void _redrawNotification(RunEngine engine) {
final copy = runNotificationCopy(
metres: engine.distanceM,
movingSeconds: engine.seconds,
currentPace: engine.paceTarget == null ? null : engine.pace,
);
final why = _suggestion;
final title = why == null
? copy.title
: '${suggestionGlyph(why)} ${copy.title}';
// Only when the words changed, not on every fix.
if ('$title|${copy.body}' == _lastCopy) return;
_lastCopy = '$title|${copy.body}';
unawaited(port.notify(title: title, text: copy.body));
}
void _emit({bool full = false}) {
final engine = _engine;
if (engine == null) return;
final from = full ? 0 : _sent.clamp(0, engine.points.length);
port.send(
encodeSnapshot(
engine,
from: from,
suggestion: _suggestion,
prompt: _prompt,
saving: _saving,
done: _done,
saved: _saved,
),
);
_sent = engine.points.length;
}
Future<void> _finish({required bool auto}) async {
final engine = _engine;
if (engine == null || !engine.phase.isActive || _finishing) return;
_finishing = true;
try {
final track = await engine.finish();
_suggestion = null;
_prompt = false;
unawaited(auto ? cues.autoEnded() : cues.workoutFinished());
final kept = track != null && !await _saveTrack(track);
// A save that said "no" (say, a duplicate) still ends the run; only one
// that threw keeps the checkpoint, so the run is not lost.
if (!kept) await store.clear();
_done = true;
_emit();
await port.stopService();
} finally {
_finishing = false;
}
}
/// Whether the save ran without throwing.
Future<bool> _saveTrack(RunTrack track) async {
_saving = true;
_emit();
try {
_saved = await save(track);
return true;
} on Exception catch (error, stack) {
log(
'RunHost: saving ${track.id} failed ($error) -- the checkpoint is '
'kept, so the run comes back on the next launch.',
level: 1000,
error: error,
stackTrace: stack,
);
_saved = (stored: false, reason: 'save failed: $error');
return false;
} finally {
_saving = false;
}
}
/// Releases the engine (never ends a run).
void dispose() {
_engine
?..removeListener(_onChanged)
..dispose();
_engine = null;
}
}

View File

@ -0,0 +1,54 @@
/// The host's way out to the rest of the phone, and its two small types.
library;
import 'dart:async';
import 'dart:developer';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/run_checkpoint.dart';
import 'package:workout_app/services/run_checkpoint_store.dart';
/// The host's way out to the rest of the phone.
abstract interface class RunHostPort {
/// Sends [message] to the UI (dropped when no UI is listening).
void send(Map<String, Object?> message);
/// Redraws the ongoing notification.
Future<void> notify({required String title, required String text});
/// Stops the foreground service (the run is over and saved).
Future<void> stopService();
/// Brings the app to the front.
void launchApp();
}
/// Saves a finished track; the reason reads like a sentence.
typedef RunSaveFn =
Future<({bool stored, String reason})> Function(RunTrack track);
/// Marks a notification title as carrying advice to finish: symbols only
/// (textgate), one per reason.
String suggestionGlyph(String why) => switch (why) {
'stationary' => '⏸',
'vehicleSpeed' => '⚡',
'gpsLost' => '⌖',
_ => '↻',
};
/// Stores [checkpoint] (when there is one) without waiting; a failed write is
/// logged, never swallowed.
void saveCheckpointLoudly(RunCheckpointStore store, RunCheckpoint? checkpoint) {
if (checkpoint == null) return;
unawaited(
store.save(checkpoint).catchError((Object error, StackTrace stack) {
log(
'RunHost: could not save the run checkpoint ($error) -- a dead '
'process would lose the run since the last good save.',
level: 1000,
error: error,
stackTrace: stack,
);
}),
);
}

View File

@ -0,0 +1,37 @@
/// What the app does at launch about a run that may be in progress.
library;
import 'dart:developer';
import 'package:workout_app/services/foreground_run_client.dart';
import 'package:workout_app/services/run_notification.dart';
/// Whether the app must open on the live run, bringing its service back if it
/// is gone.
///
/// A run is owed while its checkpoint is on disk ([owed]). The service
/// normally survives (swipe-away, kill, reboot all restart it by themselves);
/// after a force-stop it does not, and this restarts it: the service restores
/// the run from the same checkpoint. [client.start] leaves a running service
/// alone, so asking while one is up is harmless.
Future<bool> resumeRunOnLaunch({
required Future<bool> Function() owed,
required ForegroundRunClient client,
}) async {
if (!await owed()) return false;
if (!client.isSupported) return true;
final copy = runNotificationCopy(metres: 0, movingSeconds: 0);
final up = await client.start(
withLocation: true,
title: copy.title,
text: copy.body,
);
if (!up) {
log(
'RunLaunch: a run is owed but its service would not start; the run '
'screen opens anyway and shows the problem. Its checkpoint is kept.',
level: 1000,
);
}
return true;
}

View File

@ -0,0 +1,91 @@
/// The UI's line to the run host, and the in-process version of it.
library;
import 'dart:async';
import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/foreground_run_client.dart';
import 'package:workout_app/services/run_checkpoint_store.dart';
import 'package:workout_app/services/run_engine.dart';
import 'package:workout_app/services/run_host.dart';
/// A conversation with the host. Closing it only hangs up: it never touches
/// the run.
abstract interface class RunHostLink {
/// The host's snapshots (see `run_wire.dart`).
Stream<Map<Object?, Object?>> get messages;
/// Sends a command (`cmd` key); a host that is not up never answers.
void send(Map<String, Object?> command);
/// Hangs up.
Future<void> close();
}
/// The host's side of a [LoopbackRunLink]: messages go to the link's stream,
/// the notification and the service go through the [ForegroundRunClient].
class LoopbackRunPort implements RunHostPort {
/// Creates a port over [_client].
LoopbackRunPort(this._client);
final ForegroundRunClient _client;
final _out = StreamController<Map<Object?, Object?>>.broadcast();
/// What the host sends.
Stream<Map<Object?, Object?>> get messages => _out.stream;
@override
void send(Map<String, Object?> message) => _out.add(message);
@override
Future<void> notify({required String title, required String text}) async {
if (_client.isSupported) await _client.update(title: title, text: text);
}
@override
Future<void> stopService() async {
if (_client.isSupported) await _client.stop();
}
@override
void launchApp() {}
}
/// A [RunHostLink] to a host in this very isolate: Linux, the tests, and any
/// platform with no foreground service.
class LoopbackRunLink implements RunHostLink {
/// Creates a link to [host]; [port] is the one the host was built with.
LoopbackRunLink(this.host, this._port);
/// Builds the host and its link in one go.
factory LoopbackRunLink.build({
required ForegroundRunClient client,
required RunEngineFactory engineFactory,
required FeedbackCues cues,
required RunSaveFn save,
RunCheckpointStore? store,
}) {
final port = LoopbackRunPort(client);
final host = RunHost(
engineFactory: engineFactory,
port: port,
store: store ?? MemoryRunCheckpointStore(),
cues: cues,
save: save,
);
return LoopbackRunLink(host, port);
}
/// The in-process host.
final RunHost host;
final LoopbackRunPort _port;
@override
Stream<Map<Object?, Object?>> get messages => _port.messages;
@override
void send(Map<String, Object?> command) => unawaited(host.handle(command));
@override
Future<void> close() async {}
}

View File

@ -10,22 +10,23 @@
/// 30 s or less earns moving time at 0.5 m/s or faster; a longer one (a GPS
/// dropout) at 1 m/s or faster; paused time earns nothing.
///
/// The app mirrors only the bounds, per pair of its 2 s fixes, and is stricter:
/// a pair over 30 s credits nothing, where the PC keeps a dropout at 1 m/s or
/// faster. The app writes zero distance across such a gap, so the PC does not
/// credit a dropout in an app-recorded run. Its on-screen moving time is
/// therefore an estimate, not the number the PC will credit.
/// The app mirrors the bounds per pair of its 2 s fixes. Across a gap over 30 s
/// it bridges with a straight line (see `run_gap_bridge.dart`): the distance is
/// credited only at 2:30 to 12:00 min/km, and the gap counts as moving time
/// exactly when its distance was credited. Its on-screen moving time is an
/// estimate, not the number the PC will credit.
library;
import 'dart:math' as math;
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/run_gap_bridge.dart';
/// Mean Earth radius in metres (IUGG), the haversine constant.
const double kEarthRadiusM = 6371008.8;
/// A pair of fixes further apart in time than this earns neither distance
/// nor moving time: a GPS dropout whose motion is unknown.
/// A pair of fixes further apart in time than this is a gap: bridged by a
/// straight line (see `run_gap_bridge.dart`), not a normal step.
///
/// Mirrors `WALK_MAX_GAP_SECONDS` in the PC's `screen_locker/_constants.py`.
const int kMaxCreditGapSeconds = 30;
@ -56,18 +57,22 @@ double haversineM(double lat1, double lon1, double lat2, double lon2) {
return 2 * kEarthRadiusM * math.asin(math.min(1, math.sqrt(a)));
}
/// Whether the step from [a] to [b] counts as moving: seen within
/// [kMaxCreditGapSeconds] and travelled at a speed in
/// `[kMinMovingSpeedMps, maxSpeed]`.
/// Whether the step from [a] to [b] counts as moving: travelled at a speed in
/// `[kMinMovingSpeedMps, maxSpeed]`, or across a gap over
/// [kMaxCreditGapSeconds] at one in `[kBridgeMinSpeedMps, maxSpeed]` (only a
/// credited bridge has any distance at all).
///
/// Speed comes from the cumulative `distanceM` difference, as the PC reads a
/// TCX, but over one pair of fixes rather than a window of 10 s or more, so the
/// two can disagree on a jittery or stop-and-go stretch.
bool isMovingStep(RunPoint a, RunPoint b, double maxSpeed) {
final gap = b.time.difference(a.time).inMilliseconds / 1000;
if (gap <= 0 || gap > kMaxCreditGapSeconds) return false;
if (gap <= 0) return false;
final speed = (b.distanceM - a.distanceM) / gap;
return speed >= kMinMovingSpeedMps && speed <= maxSpeed;
final floor = gap > kMaxCreditGapSeconds
? kBridgeMinSpeedMps
: kMinMovingSpeedMps;
return speed >= floor && speed <= maxSpeed;
}
/// Moving seconds over [points]: the summed gaps of every moving step.

View File

@ -55,3 +55,19 @@ enum RunIssue {
bool get isAccess =>
this == denied || this == deniedForever || this == serviceOff;
}
/// Why the recorder suggests the runner finish. It never ends a run itself
/// (the 5 h auto end is a separate callback).
enum RunSuggestion {
/// Under 50 m of progress in 10 minutes; repeats every 10 minutes.
stationary,
/// Faster than 25 km/h for a minute: probably in a vehicle.
vehicleSpeed,
/// No GPS fix for 5 minutes.
gpsLost,
/// The run was just restored from a checkpoint after the app died.
restored,
}

View File

@ -2,7 +2,6 @@
library;
import 'dart:async';
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:workout_app/models/run_track.dart';
@ -11,10 +10,17 @@ import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/pace_coach.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_checkpoint.dart';
import 'package:workout_app/services/run_math.dart';
import 'package:workout_app/services/run_phase.dart';
import 'package:workout_app/services/run_recorder_log.dart';
import 'package:workout_app/services/run_watchdog.dart';
export 'package:workout_app/services/run_phase.dart';
export 'package:workout_app/services/run_watchdog.dart' show RunLimits;
part 'run_recorder_fixes.dart';
part 'run_recorder_persist.dart';
/// Records one GPS activity from a [PositionSource].
///
@ -25,13 +31,38 @@ export 'package:workout_app/services/run_phase.dart';
/// walked while paused and the first fix after it credit nothing. Moving time
/// is [movingSeconds] applied as fixes arrive: an estimate that mirrors the
/// PC's bounds per pair of fixes, not its 10 s windows (see `run_math.dart`).
///
/// The run survives a dead process: [onCheckpoint] hands the host a
/// [RunCheckpoint] after every accepted fix and on pause or resume, and
/// `restore` (see `run_recorder_persist.dart`) rebuilds the recording from
/// one. A gap (dead phone, GPS dropout) is bridged by a straight line (see
/// `run_gap_bridge.dart`). A [RunWatchdog] suggests finishing and ends the
/// run after 5 h of wall clock.
class RunRecorder extends ChangeNotifier {
/// Creates a recorder; [sourceFor] builds the fix stream on [start].
///
/// [clock] is the wall-clock seam; [autoEndAfter] and [limits] default to
/// the agreed rules and are shrunk by the sandbox and the tests.
RunRecorder({
required this.sourceFor,
this.onKilometre,
void Function(PaceCue cue)? onPaceCue,
}) : coach = PaceCoach(onCue: onPaceCue);
this.onSuggestFinish,
this.onAutoEnd,
this.onCheckpoint,
DateTime Function() clock = DateTime.now,
Duration autoEndAfter = const Duration(hours: 5),
RunLimits limits = const RunLimits(),
}) : _clock = clock,
coach = PaceCoach(onCue: onPaceCue) {
_watch = RunWatchdog(
clock: clock,
onSuggest: (why) => onSuggestFinish?.call(why),
onAutoEnd: () => onAutoEnd?.call(),
autoEndAfter: autoEndAfter,
limits: limits,
);
}
/// Builds the source for one recording.
final PositionSource Function() sourceFor;
@ -39,13 +70,26 @@ class RunRecorder extends ChangeNotifier {
/// Called with 1, 2, 3 ... as each whole kilometre is credited.
final void Function(int km)? onKilometre;
/// Advice to finish the run (never ends it).
final void Function(RunSuggestion why)? onSuggestFinish;
/// Called once after 5 h of wall clock; the host then calls [finish].
final void Function()? onAutoEnd;
/// Hears a fresh checkpoint after every accepted fix, on start, pause and
/// resume: the host stores it.
final void Function(RunCheckpoint checkpoint)? onCheckpoint;
/// The pace target's state: current pace, band and cues.
final PaceCoach coach;
final DateTime Function() _clock;
late final RunWatchdog _watch;
RunPhase _phase = RunPhase.idle;
RunIssue _issue = RunIssue.none;
GpsFilter? _filter;
StreamSubscription<GpsFix>? _sub;
late DateTime _startedAt;
bool _starting = false;
int _moving = 0;
int _km = 0;
@ -93,19 +137,14 @@ class RunRecorder extends ChangeNotifier {
try {
final source = sourceFor();
final access = await source.requestAccess();
if (!access.isGranted) {
_refuse(access);
if (!await _open(source, access, afterAccess, GpsFilter())) {
return false;
}
await afterAccess?.call();
_filter = GpsFilter();
_sub = source
.fixes() // the source's default 2 s, far under kMaxCreditGapSeconds
.listen(_onFix, onError: _onError, onDone: _onDone);
_issue = RunIssue.none;
_startedAt = _clock().toUtc();
_phase = RunPhase.recording;
_watch.begin(_startedAt);
SandboxLog.event('run started');
notifyListeners();
_announce();
return true;
} finally {
_starting = false;
@ -117,8 +156,9 @@ class RunRecorder extends ChangeNotifier {
if (_phase != RunPhase.recording) return;
_filter!.breakSegment();
_phase = RunPhase.paused;
_watch.pause();
SandboxLog.event('run paused', {'m': distanceM});
notifyListeners();
_announce();
}
/// Continues after [pause].
@ -126,14 +166,16 @@ class RunRecorder extends ChangeNotifier {
if (_phase != RunPhase.paused) return;
_phase = RunPhase.recording;
coach.restartAt(_filter!.points.length);
_watch.resume();
SandboxLog.event('run resumed', {'m': distanceM});
notifyListeners();
_announce();
}
/// Ends the recording and returns the track, or null when there were too
/// few usable fixes (then [issue] is [RunIssue.tooShort]).
Future<RunTrack?> finish() async {
if (!_phase.isActive) return null;
_watch.stop();
await _sub?.cancel();
_sub = null;
_phase = RunPhase.finished;
@ -142,11 +184,7 @@ class RunRecorder extends ChangeNotifier {
RunTrack? track;
if (points.length < 2) {
_issue = RunIssue.tooShort;
log(
'RunRecorder: finished with ${points.length} usable GPS fix(es) '
'-- not enough for a track, so nothing is saved.',
level: 1000,
);
logTooShort(points.length);
} else {
track = RunTrack.started(
sport: RunSport.running,
@ -166,81 +204,26 @@ class RunRecorder extends ChangeNotifier {
return track;
}
/// [notifyListeners] for the `part` files' extensions, which may not call
/// a protected member themselves.
void _changed() => notifyListeners();
/// Tells listeners and hands the host a fresh checkpoint.
void _announce() {
notifyListeners();
final c = onCheckpoint == null ? null : checkpoint();
if (c != null) onCheckpoint!(c);
}
void _refuse(LocationAccess access) {
_issue = RunIssue.forAccess(access);
final fix = access == LocationAccess.serviceOff
? 'Switch location on'
: 'Grant location to the app in system settings';
log(
'RunRecorder: not recording -- location access is ${access.name}. '
'$fix and start again.',
level: 1000,
);
logRefused(access);
notifyListeners();
}
void _onFix(GpsFix fix) {
if (_phase != RunPhase.recording) return;
final verdict = _filter!.add(fix);
if (verdict != FixVerdict.accepted) {
_noteDropped(verdict);
return;
}
_issue = RunIssue.none;
final points = _filter!.points;
final n = points.length;
if (n >= 2 &&
isMovingStep(points[n - 2], points[n - 1], kRunningMaxSpeedMps)) {
_moving += points[n - 1].time.difference(points[n - 2].time).inSeconds;
}
_live.value = points;
coach.update(points);
while (distanceM ~/ 1000 > _km) {
_km++;
SandboxLog.event('run km', {'km': _km, 'secs': _moving});
onKilometre?.call(_km);
}
notifyListeners();
}
void _noteDropped(FixVerdict verdict) {
if (verdict == FixVerdict.mocked) {
_issue = RunIssue.mockedLocation;
notifyListeners();
}
// Said once per kind and run: a bad tunnel would otherwise flood the log.
if (!_seenVerdicts.add(verdict)) return;
log(
'RunRecorder: dropped a GPS fix (${verdict.name}); further drops of '
'this kind are not logged. Mock fixes never count towards a run.',
level: 900,
);
}
void _onError(Object error, StackTrace stack) {
_issue = RunIssue.streamError;
log(
'RunRecorder: the location stream failed ($error) -- fixes may have '
'stopped; time and distance are not crediting until they resume.',
level: 1000,
error: error,
stackTrace: stack,
);
notifyListeners();
}
void _onDone() {
if (!_phase.isActive) return;
log(
'RunRecorder: the location stream ended while still recording; '
'finish the run to save what was captured.',
level: 900,
);
SandboxLog.event('run stream ended', {'m': distanceM});
}
@override
void dispose() {
_watch.stop();
unawaited(_sub?.cancel());
_live.dispose();
super.dispose();

View File

@ -0,0 +1,51 @@
// What the recorder does with each fix, error and end of the stream: a `part`
// file so the state machine itself stays short.
part of 'run_recorder.dart';
extension _FixHandling on RunRecorder {
void _onFix(GpsFix fix) {
if (_phase != RunPhase.recording) return;
final verdict = _filter!.add(fix);
_watch.onFix(fix, verdict, distanceM);
if (verdict != FixVerdict.accepted) {
_noteDropped(verdict);
return;
}
_issue = RunIssue.none;
final points = _filter!.points;
final n = points.length;
if (n >= 2 &&
isMovingStep(points[n - 2], points[n - 1], kRunningMaxSpeedMps)) {
_moving += points[n - 1].time.difference(points[n - 2].time).inSeconds;
}
_live.value = points;
coach.update(points);
while (distanceM ~/ 1000 > _km) {
_km++;
SandboxLog.event('run km', {'km': _km, 'secs': _moving});
onKilometre?.call(_km);
}
_announce();
}
void _noteDropped(FixVerdict verdict) {
if (verdict == FixVerdict.mocked) {
_issue = RunIssue.mockedLocation;
_changed();
}
// Said once per kind and run: a bad tunnel would otherwise flood the log.
if (_seenVerdicts.add(verdict)) logDropped(verdict);
}
void _onError(Object error, StackTrace stack) {
_issue = RunIssue.streamError;
logStreamError(error, stack);
_changed();
}
void _onDone() {
if (!_phase.isActive) return;
logStreamEnded();
SandboxLog.event('run stream ended', {'m': distanceM});
}
}

View File

@ -0,0 +1,62 @@
/// The recorder's log lines, kept apart so the state machine stays short.
///
/// Level 1000 is "something is wrong and the user must act or lose data";
/// 900 is a warning. Nothing here is silent: see the repo's
/// "NEVER fail silently" rule.
library;
import 'dart:developer';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/position_source.dart';
/// Recording was refused because location access is [access].
void logRefused(LocationAccess access) {
final fix = access == LocationAccess.serviceOff
? 'Switch location on'
: 'Grant location to the app in system settings';
log(
'RunRecorder: not recording -- location access is ${access.name}. '
'$fix and start again.',
level: 1000,
);
}
/// A fix was dropped for [verdict]; the caller says it once per kind.
void logDropped(FixVerdict verdict) => log(
'RunRecorder: dropped a GPS fix (${verdict.name}); further drops of '
'this kind are not logged. Mock fixes never count towards a run.',
level: 900,
);
/// The location stream reported [error].
void logStreamError(Object error, StackTrace stack) => log(
'RunRecorder: the location stream failed ($error) -- fixes may have '
'stopped; time and distance are not crediting until they resume.',
level: 1000,
error: error,
stackTrace: stack,
);
/// The location stream ended while a run was still active.
void logStreamEnded() => log(
'RunRecorder: the location stream ended while still recording; '
'finish the run to save what was captured.',
level: 900,
);
/// A run finished with [count] usable fixes, too few to save.
void logTooShort(int count) => log(
'RunRecorder: finished with $count usable GPS fix(es) '
'-- not enough for a track, so nothing is saved.',
level: 1000,
);
/// Restoring the checkpointed run failed with [error].
void logRestoreFailed(Object error, StackTrace stack) => log(
'RunRecorder: could not reopen the position source to restore the run '
'($error) -- the run stays unrecovered; its checkpoint is kept.',
level: 1000,
error: error,
stackTrace: stack,
);

View File

@ -0,0 +1,96 @@
// Checkpointing and restore: a `part` file so they can use the recorder's
// private state while the recorder itself stays short.
part of 'run_recorder.dart';
/// Persistence of a run across a dead process.
extension RunRecorderPersistence on RunRecorder {
/// A snapshot to rebuild the run from, or null when idle or finished.
RunCheckpoint? checkpoint() {
final filter = _filter;
if (!_phase.isActive || filter == null) return null;
return RunCheckpoint(
startedAt: _startedAt,
savedAt: _clock(),
phase: _phase,
points: filter.points,
movingSeconds: _moving,
distanceM: filter.distanceM,
km: _km,
segmentBreak: filter.segmentBreak,
jumps: filter.jumps,
paceTargetSeconds: coach.target,
);
}
/// Rebuilds the run from [c] after the process died and reopens the
/// position source (without prompting). The next fix is bridged across the
/// dead time. Fires [RunRecorder.onSuggestFinish] with
/// [RunSuggestion.restored], or [RunRecorder.onAutoEnd] at once when 5 h
/// have passed. False (logged) when the source cannot open or a run is
/// already going.
Future<bool> restore(
RunCheckpoint c, {
Future<void> Function()? afterAccess,
}) async {
if (_phase != RunPhase.idle || _starting) return false;
_starting = true;
try {
final source = sourceFor();
final filter = GpsFilter.restore(
points: c.points,
segmentBreak: c.segmentBreak,
jumps: c.jumps,
);
final access = await source.checkAccess();
if (!await _open(source, access, afterAccess, filter)) return false;
_startedAt = c.startedAt;
_moving = c.movingSeconds;
_km = c.km;
coach
..setTarget(c.paceTargetSeconds)
..restartAt(c.points.length);
_live.value = c.points;
_phase = c.phase;
SandboxLog.event('run restored', {'m': c.distanceM});
_announce();
_watch.restored(
c.startedAt,
paused: c.phase == RunPhase.paused,
distanceM: c.distanceM,
);
return true;
} on Object catch (e, stack) {
debugPrint('RunRecorder: restore failed ($e)');
logRestoreFailed(e, stack);
await _sub?.cancel();
_sub = null;
_filter = null;
_phase = RunPhase.idle;
_issue = RunIssue.streamError;
_changed();
return false;
} finally {
_starting = false;
}
}
/// Opens [source] under [access] with [filter]; false when refused.
Future<bool> _open(
PositionSource source,
LocationAccess access,
Future<void> Function()? afterAccess,
GpsFilter filter,
) async {
if (!access.isGranted) {
_refuse(access);
return false;
}
await afterAccess?.call();
_filter = filter;
_sub = source
.fixes() // the source's default 2 s, far under kMaxCreditGapSeconds
.listen(_onFix, onError: _onError, onDone: _onDone);
_issue = RunIssue.none;
return true;
}
}

View File

@ -0,0 +1,145 @@
// coverage:ignore-file
// Everything here runs only in the foreground-service isolate, where there is
// no widget binding a test can reach. The decisions are in run_host.dart and
// run_task_handler.dart, covered against fakes; this file only wires the real
// plugin, location source and database to them.
/// The run foreground service's entry point (the isolate the run lives in).
library;
import 'dart:async';
import 'dart:developer';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/sandbox/sandbox_run_replay.dart';
import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/position_source_geolocator.dart';
import 'package:workout_app/services/run_checkpoint_location.dart';
import 'package:workout_app/services/run_engine_recorder.dart';
import 'package:workout_app/services/run_host.dart';
import 'package:workout_app/services/run_saver.dart';
import 'package:workout_app/services/run_task_handler.dart';
import 'package:workout_app/services/storage_service.dart';
/// `FlutterForegroundTask.saveData` keys the UI isolate writes before it
/// starts the service (the service isolate cannot ask MainActivity).
const kRunFlagSandbox = 'run_sandbox';
/// See [kRunFlagSandbox].
const kRunFlagReplayFactor = 'run_replay_factor';
/// See [kRunFlagSandbox].
const kRunFlagSound = 'run_sound';
/// Entry point the plugin calls in the background isolate.
@pragma('vm:entry-point')
void runServiceStartCallback() {
FlutterForegroundTask.setTaskHandler(_RunServiceTaskHandler());
}
/// A position source that never shows a prompt: the service has no Activity
/// to ask from, and the UI already settled the permission.
class NoPromptSource implements PositionSource {
/// Wraps [_inner].
NoPromptSource(this._inner);
final PositionSource _inner;
@override
Future<LocationAccess> requestAccess() => _inner.checkAccess();
@override
Future<LocationAccess> checkAccess() => _inner.checkAccess();
@override
Stream<GpsFix> fixes({Duration interval = const Duration(seconds: 2)}) =>
_inner.fixes(interval: interval);
}
class _ServicePort implements RunHostPort {
@override
void send(Map<String, Object?> message) =>
FlutterForegroundTask.sendDataToMain(message);
@override
Future<void> notify({required String title, required String text}) async {
await FlutterForegroundTask.updateService(
notificationTitle: title,
notificationText: text,
);
}
@override
Future<void> stopService() async {
final result = await FlutterForegroundTask.stopService();
if (result is! ServiceRequestSuccess) {
log('RunService: stopping the service failed ($result).', level: 1000);
}
}
@override
void launchApp() => FlutterForegroundTask.launchApp();
}
Future<({bool stored, String reason})> _saveInService(RunTrack track) async {
final result = await saveRecordedRun(
track,
storage: await StorageService.init(),
// The UI isolate uploads on its next start and resume; this isolate keeps
// the sandbox's offline guarantee (no HTTP overrides here).
enqueue: () async => null,
);
return (stored: result.stored, reason: result.reason);
}
class _RunServiceTaskHandler extends TaskHandler {
RunTaskHandler? _handler;
@override
Future<void> onStart(DateTime timestamp, TaskStarter starter) async {
Sandbox.enabled =
await FlutterForegroundTask.getData<bool>(key: kRunFlagSandbox) ??
false;
Sandbox.runReplayFactor =
await FlutterForegroundTask.getData<int>(key: kRunFlagReplayFactor) ??
Sandbox.defaultReplayFactor;
final cues = FeedbackCues(AudioPlayer())
..soundOn =
await FlutterForegroundTask.getData<bool>(key: kRunFlagSound) ?? true;
final port = _ServicePort();
final host = RunHost(
engineFactory: recorderEngineFactory(
() => Sandbox.enabled
? sandboxRunSource()
: NoPromptSource(GeolocatorPositionSource()),
),
port: port,
store: await openRunCheckpointStore(),
cues: cues,
save: _saveInService,
);
final handler = _handler = RunTaskHandler(host: host, port: port);
debugPrint('RunService: onStart ${starter.name}');
await handler.onStart(startedBySystem: starter == TaskStarter.system);
}
@override
void onRepeatEvent(DateTime timestamp) {}
@override
void onReceiveData(Object data) => _handler?.onReceiveData(data);
@override
void onNotificationPressed() => _handler?.onNotificationPressed();
@override
Future<void> onDestroy(DateTime timestamp, bool isTimeout) async {
debugPrint('RunService: onDestroy timeout=$isTimeout');
_handler?.onDestroy();
}
}

View File

@ -0,0 +1,59 @@
/// What the run foreground service does at each plugin callback, without the
/// plugin: [RunTaskHandler] is tested against a fake port, the thin adapter in
/// `run_service_isolate.dart` only forwards.
library;
import 'dart:async';
import 'dart:developer';
import 'package:workout_app/services/run_host.dart';
/// Drives a [RunHost] from the service's lifecycle.
class RunTaskHandler {
/// Creates a handler over [host]; [port] is the one the host was built with.
RunTaskHandler({required this.host, required this.port});
/// The recording's home.
final RunHost host;
/// Used to stop the service when it has nothing to host.
final RunHostPort port;
/// The service came up. A checkpoint on disk means a run is owed: resume it,
/// whoever started the service (the OS after a kill or a reboot, or the app
/// after a force-stop). With none, a system start has no run to serve (a
/// stale service or a leftover boot flag), so it stops itself; an app start
/// waits for the start command.
Future<void> onStart({required bool startedBySystem}) async {
final restored = await host.restoreFromStore();
if (restored) return;
if (startedBySystem) {
log(
'RunTaskHandler: the system started the run service but there is no '
'run checkpoint -- nothing to record, so it stops itself.',
level: 900,
);
await port.stopService();
}
}
/// A message from the UI.
void onReceiveData(Object data) {
if (data is Map && data['cmd'] is String) {
unawaited(host.handle(data));
return;
}
log(
'RunTaskHandler: ignored a message that is not a run command '
'(${data.runtimeType}); the break service shares this channel.',
level: 900,
);
}
/// The ongoing notification was tapped.
void onNotificationPressed() => host.notificationPressed();
/// The service is going away: the host lets go. This never ends the run;
/// its checkpoint stays for the next start.
void onDestroy() => host.dispose();
}

View File

@ -0,0 +1,149 @@
/// What the run screen shows: a mirror of the host's last snapshot.
library;
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_phase.dart';
import 'package:workout_app/services/run_wire.dart';
/// The recording as the UI sees it. The numbers belong to the host; this only
/// keeps the newest copy, so a dead screen loses nothing.
class RunView extends ChangeNotifier {
/// Asks the host for a full copy ([RunCmd.hello]) when points were missed.
void Function()? onNeedSync;
/// Where the recording stands.
RunPhase phase = RunPhase.idle;
/// The current problem, or [RunIssue.none].
RunIssue issue = RunIssue.none;
/// Credited moving time in seconds.
int seconds = 0;
/// Credited distance in metres.
double distanceM = 0;
/// The pace target in seconds per kilometre, or null.
int? paceTarget;
/// The current pace in seconds per kilometre, once warmed up.
double? pace;
/// Where [pace] stands against [paceTarget].
PaceBand? band;
/// The reason the host suggests finishing, or null.
String? suggestion;
/// The notification was tapped while a suggestion stood: show the modal.
bool promptFinish = false;
/// The host is writing the finished run.
bool saving = false;
/// The host is through with the finished run (saved, or nothing to save).
bool done = false;
/// What saving did, once the host finished.
({bool stored, String reason})? saved;
/// Whether any snapshot has arrived yet.
bool synced = false;
/// Accepted points so far, for the live map.
final livePoints = ValueNotifier<List<RunPoint>>(const []);
/// Folds an access check in while idle: a refusal becomes the issue, a
/// grant clears it. Local: with no run there is no host to ask.
void noteAccess(LocationAccess access) {
if (phase != RunPhase.idle) return;
if (!access.isGranted) {
issue = RunIssue.forAccess(access);
return notifyListeners();
}
if (!issue.isAccess) return;
issue = RunIssue.none;
notifyListeners();
}
/// Takes the host's newest message.
void apply(Map<Object?, Object?> m) {
final next = RunPhase.values.byName(m['phase']! as String);
final incoming = RunIssue.values.byName(m['issue']! as String);
// An idle host knows nothing of the permission the UI just checked: its
// "no issue" must not wipe a refusal the UI found itself.
if (next != RunPhase.idle || incoming != RunIssue.none) issue = incoming;
phase = next;
seconds = m['seconds']! as int;
distanceM = (m['distanceM']! as num).toDouble();
paceTarget = m['paceTarget'] as int?;
pace = (m['pace'] as num?)?.toDouble();
final bandName = m['band'] as String?;
band = bandName == null ? null : PaceBand.values.byName(bandName);
suggestion = m['suggestion'] as String?;
promptFinish = m['prompt']! as bool;
saving = m['saving']! as bool;
done = m['done']! as bool;
final savedRaw = m['saved'] as Map<Object?, Object?>?;
saved = savedRaw == null
? null
: (
stored: savedRaw['stored']! as bool,
reason: savedRaw['reason']! as String,
);
synced = true;
_applyPoints(m);
notifyListeners();
}
void _applyPoints(Map<Object?, Object?> m) {
final from = m['from']! as int;
final total = m['total']! as int;
final fresh = [
for (final raw in m['pts']! as List<Object?>)
decodePoint((raw! as List<Object?>).cast<Object?>()),
];
final held = livePoints.value;
if (from == 0) {
livePoints.value = fresh;
} else if (from == held.length) {
livePoints.value = [...held, ...fresh];
} else {
// A message was lost (the screen was away): ask for everything again.
onNeedSync?.call();
return;
}
if (livePoints.value.length != total) onNeedSync?.call();
}
/// Waits until [done] holds (checked on every snapshot); false on timeout.
Future<bool> waitUntil(bool Function() done, Duration timeout) async {
if (done()) return true;
final completer = Completer<void>();
void check() {
if (done() && !completer.isCompleted) completer.complete();
}
addListener(check);
try {
await completer.future.timeout(timeout);
return true;
} on TimeoutException {
debugPrint('RunView: condition not met within $timeout');
return false;
} finally {
removeListener(check);
}
}
@override
void dispose() {
livePoints.dispose();
super.dispose();
}
}

View File

@ -0,0 +1,209 @@
/// Watches a run for the signs that it should end: suggests finishing, and
/// ends it after 5 hours of wall clock.
///
/// It never finishes a run itself: [onSuggest] is advice, [onAutoEnd] tells
/// the host to call `finish()`. Checks run off a periodic [Timer] and the
/// injected [clock], not only when a fix arrives, so a silent GPS is noticed.
library;
import 'dart:async';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/run_math.dart';
import 'package:workout_app/services/run_phase.dart';
/// The suggest-finish thresholds; the defaults are the agreed rules, the
/// sandbox and the tests shrink them.
class RunLimits {
/// Creates limits.
const RunLimits({
this.stationaryWindow = const Duration(minutes: 10),
this.stationaryMinM = 50,
this.vehicleSpeedMps = 25 / 3.6,
this.vehicleWindow = const Duration(seconds: 60),
this.noFixAfter = const Duration(minutes: 5),
this.tick = const Duration(seconds: 5),
});
/// The progress window for [RunSuggestion.stationary].
final Duration stationaryWindow;
/// Credited metres a [stationaryWindow] needs to stay quiet.
final double stationaryMinM;
/// Speed above which a stretch looks like a vehicle, in metres per second.
final double vehicleSpeedMps;
/// How long that speed must hold.
final Duration vehicleWindow;
/// How long without a usable fix before [RunSuggestion.gpsLost].
final Duration noFixAfter;
/// How often the timer checks.
final Duration tick;
}
/// The suggest-finish and auto-end rules of one run.
class RunWatchdog {
/// Creates a watchdog with the agreed rules unless [limits] or
/// [autoEndAfter] say otherwise.
RunWatchdog({
required this.clock,
required this.onSuggest,
required this.onAutoEnd,
this.autoEndAfter = const Duration(hours: 5),
this.limits = const RunLimits(),
});
/// The wall clock.
final DateTime Function() clock;
/// Hears each suggestion to finish.
final void Function(RunSuggestion why) onSuggest;
/// Hears the auto end, once; the host then finishes the run.
final void Function() onAutoEnd;
/// Wall-clock run length (pauses and phone-off time included) that ends it.
final Duration autoEndAfter;
/// The suggest-finish thresholds.
final RunLimits limits;
Timer? _timer;
DateTime? _startedAt;
bool _paused = false;
bool _ended = false;
late DateTime _lastFixAt;
late DateTime _anchorAt;
double _anchorM = 0;
double _distanceM = 0;
bool _lostFired = false;
GpsFix? _prev;
DateTime? _fastSince;
bool _fastFired = false;
/// Starts watching a run that began at [startedAt].
void begin(DateTime startedAt) {
_startedAt = startedAt.toUtc();
_ended = false;
_paused = false;
_distanceM = 0;
_rebase();
_timer?.cancel();
_timer = Timer.periodic(limits.tick, (_) => check());
}
/// Starts watching a run restored from a checkpoint: advises finishing, or
/// ends it at once when 5 hours have already passed.
void restored(
DateTime startedAt, {
required bool paused,
required double distanceM,
}) {
begin(startedAt);
_paused = paused;
_distanceM = distanceM;
_anchorM = distanceM;
if (_expired()) {
check();
} else {
onSuggest(RunSuggestion.restored);
}
}
/// Stops all checks (finish or dispose). Safe to call twice.
void stop() {
_timer?.cancel();
_timer = null;
_startedAt = null;
}
/// A pause: nothing fires until [resume].
void pause() => _paused = true;
/// After a pause the windows start afresh, so paused time never reads as
/// standing still or a lost signal.
void resume() {
_paused = false;
_rebase();
}
/// Folds in one raw fix and the filter's [verdict] on it.
///
/// Too-fast fixes count: a vehicle never yields an accepted fix, the
/// filter drops it as a jump, so speed is read off raw consecutive fixes.
void onFix(GpsFix fix, FixVerdict verdict, double distanceM) {
if (verdict != FixVerdict.accepted && verdict != FixVerdict.tooFast) {
return;
}
_distanceM = distanceM;
_lastFixAt = clock();
_lostFired = false;
_readSpeed(fix);
check();
}
void _readSpeed(GpsFix fix) {
final prev = _prev;
if (prev == null) {
_prev = fix;
return;
}
final dt = fix.time.difference(prev.time).inSeconds;
if (dt <= 0) return; // a same-second fix says nothing about speed
_prev = fix;
final speed =
haversineM(prev.latitude, prev.longitude, fix.latitude, fix.longitude) /
dt;
if (speed <= limits.vehicleSpeedMps) {
_fastSince = null;
_fastFired = false;
return;
}
_fastSince ??= fix.time;
if (!_fastFired &&
fix.time.difference(_fastSince!) >= limits.vehicleWindow) {
_fastFired = true;
onSuggest(RunSuggestion.vehicleSpeed);
}
}
/// Runs every rule against the clock; the timer calls this every [tick].
void check() {
final started = _startedAt;
if (started == null || _ended) return;
if (_expired()) {
_ended = true;
_timer?.cancel();
onAutoEnd();
return;
}
if (_paused) return;
final now = clock();
if (!_lostFired && now.difference(_lastFixAt) >= limits.noFixAfter) {
_lostFired = true;
onSuggest(RunSuggestion.gpsLost);
}
if (now.difference(_anchorAt) >= limits.stationaryWindow) {
final progress = _distanceM - _anchorM;
_anchorAt = now;
_anchorM = _distanceM;
if (progress < limits.stationaryMinM) onSuggest(RunSuggestion.stationary);
}
}
bool _expired() => !_ended && clock().difference(_startedAt!) >= autoEndAfter;
void _rebase() {
final now = clock();
_lastFixAt = now;
_anchorAt = now;
_anchorM = _distanceM;
_lostFired = false;
_prev = null;
_fastSince = null;
_fastFired = false;
}
}

View File

@ -0,0 +1,92 @@
/// The messages the run UI and the run host (the foreground-service isolate)
/// exchange. JSON-safe maps only: they cross an isolate boundary.
library;
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/run_engine.dart';
/// Key every host message carries, so the break service's data channel (the
/// same plugin channel) can tell the two apart.
const kRunWireKey = 'run';
/// UI -> host commands, under the `cmd` key.
abstract final class RunCmd {
/// "Send me everything": answered with a full snapshot.
static const hello = 'hello';
/// Begin recording; carries `paceTarget` and `sound`.
static const start = 'start';
/// Pause crediting.
static const pause = 'pause';
/// Resume crediting.
static const resume = 'resume';
/// End the run (only after the confirm modal).
static const finish = 'finish';
/// Change the pace target; carries `paceTarget`.
static const paceTarget = 'paceTarget';
/// The UI showed the finish modal the notification asked for.
static const ackPrompt = 'ackPrompt';
}
/// One point as `[ms, lat, lon, distanceM, altitudeM?]`.
List<Object?> encodePoint(RunPoint p) => [
p.time.millisecondsSinceEpoch,
p.latitude,
p.longitude,
p.distanceM,
p.altitudeM,
];
/// Inverse of [encodePoint].
RunPoint decodePoint(List<Object?> raw) => RunPoint(
time: DateTime.fromMillisecondsSinceEpoch(raw[0]! as int, isUtc: true),
latitude: (raw[1]! as num).toDouble(),
longitude: (raw[2]! as num).toDouble(),
distanceM: (raw[3]! as num).toDouble(),
altitudeM: (raw[4] as num?)?.toDouble(),
);
/// The host's state as one message.
///
/// [from] says which point index `pts` starts at, so a UI that already holds
/// the first [from] points appends, and one that does not sends
/// [RunCmd.hello] for a full copy.
Map<String, Object?> encodeSnapshot(
RunEngine engine, {
required int from,
String? suggestion,
bool prompt = false,
bool saving = false,
bool done = false,
({bool stored, String reason})? saved,
}) {
final points = engine.points;
return {
kRunWireKey: 1,
'phase': engine.phase.name,
'issue': engine.issue.name,
'seconds': engine.seconds,
'distanceM': engine.distanceM,
'paceTarget': engine.paceTarget,
'pace': engine.pace,
'band': engine.band?.name,
'suggestion': suggestion,
'prompt': prompt,
'saving': saving,
'done': done,
'saved': saved == null
? null
: {'stored': saved.stored, 'reason': saved.reason},
'from': from,
'total': points.length,
'pts': [for (var i = from; i < points.length; i++) encodePoint(points[i])],
};
}
/// Whether [data] is a host message (not a break-service one).
bool isRunMessage(Object? data) => data is Map && data[kRunWireKey] == 1;

View File

@ -0,0 +1,50 @@
// coverage:ignore-file
// The composition root of a recording: it only names the real plugin,
// database and GPS. Every decision is in the classes it connects, covered
// against fakes.
/// The real parts a run is built from, installed by `main`.
library;
import 'package:audioplayers/audioplayers.dart';
import 'package:workout_app/sandbox/sandbox_run_replay.dart';
import 'package:workout_app/screens/run_screen.dart';
import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/foreground_run_client_flutter.dart';
import 'package:workout_app/services/run_controller.dart';
import 'package:workout_app/services/run_engine_recorder.dart';
import 'package:workout_app/services/run_link.dart';
import 'package:workout_app/services/run_saver.dart';
import 'package:workout_app/services/run_uploader.dart';
import 'package:workout_app/services/storage_service.dart';
/// Real GPS (or the sandbox replay), the real service and database. On
/// Android the run lives in the service isolate behind a [ServiceRunLink];
/// elsewhere it lives in this isolate behind a loopback.
RunController buildRunController() {
final client = FlutterForegroundRunClient();
return RunController(
idleSourceFor: idlePositionSourceFor,
service: client,
link: client.isSupported
? ServiceRunLink()
: LoopbackRunLink.build(
client: client,
engineFactory: recorderEngineFactory(positionSourceFor),
cues: FeedbackCues(AudioPlayer()),
save: (track) async {
final result = await saveRecordedRun(
track,
storage: StorageService.instance,
enqueue: RunUploader.instance.uploadPending,
);
return (stored: result.stored, reason: result.reason);
},
),
soundOn: () => StorageService.instance.getSoundEnabled(),
);
}
/// Installs [buildRunController] as the run screen's default.
void installRunWiring() {
RunScreen.defaultControllerFactory = buildRunController;
}

View File

@ -0,0 +1,50 @@
/// The confirm step before a run ends: a red check ends it, a cross goes back.
/// No words (textgate): colour and two icons carry the whole question.
library;
import 'package:material_ui/material_ui.dart';
import 'package:workout_app/ui/theme.dart';
/// Asks whether to end the run. True only for the red check; the cross, the
/// back button and a tap outside all answer false, so nothing but a deliberate
/// check ends a run.
Future<bool> showRunFinishDialog(BuildContext context) async {
final end = await showDialog<bool>(
context: context,
builder: (context) {
final scheme = Theme.of(context).colorScheme;
Widget choice(String id, IconData icon, Color fill, bool answer) =>
IconButton.filled(
key: Key('run_finish_$id'),
onPressed: () => Navigator.of(context).pop(answer),
iconSize: 48,
style: IconButton.styleFrom(
fixedSize: const Size.square(96),
backgroundColor: fill,
foregroundColor: scheme.onPrimary,
),
icon: Icon(icon, semanticLabel: id),
);
return Dialog(
key: const Key('run_finish_dialog'),
child: Padding(
padding: const EdgeInsets.all(AppSpacing.lg),
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
choice('confirm', Icons.check, scheme.error, true),
choice(
'cancel',
Icons.close,
scheme.surfaceContainerHighest,
false,
),
],
),
),
);
},
);
return end ?? false;
}

View File

@ -0,0 +1,55 @@
/// Keeps the app on the live run: when it comes back to the front with a run
/// owed and nothing above home, the run screen opens again.
library;
import 'dart:async';
import 'package:material_ui/material_ui.dart';
import 'package:workout_app/screens/run_screen.dart';
/// Wraps the home route of the app.
class RunLanding extends StatefulWidget {
/// Creates the wrapper; a null [owed] (no run can exist here) never lands.
const RunLanding({required this.child, this.owed, super.key});
/// Whether a run is owed right now.
final Future<bool> Function()? owed;
/// The home screen.
final Widget child;
@override
State<RunLanding> createState() => _RunLandingState();
}
class _RunLandingState extends State<RunLanding> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) unawaited(_land());
}
Future<void> _land() async {
final owed = widget.owed;
// Anything above home (the run itself, a workout) already has the screen.
if (owed == null || !(ModalRoute.of(context)?.isCurrent ?? false)) return;
if (!await owed() || !mounted) return;
await Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => const RunScreen(resuming: true)),
);
}
@override
Widget build(BuildContext context) => widget.child;
}

View File

@ -804,10 +804,10 @@ packages:
dependency: "direct main"
description:
name: material_ui
sha256: "474c135fd46b56ff1d35ca982155e8863d28fbc6464d1192acf4ee53a738680e"
sha256: a6b19012df437a356cbc01f8ea22a105e07194c47c9a6009da0032a0ce35c4ab
url: "https://pub.dev"
source: hosted
version: "1.11.0"
version: "1.11.1"
meta:
dependency: transitive
description:
@ -1209,11 +1209,11 @@ packages:
dependency: "direct main"
description:
path: sync_settings_ui
ref: "sync_settings_ui-v0.8.2"
resolved-ref: "3225af8365481677d61a8cabec0c0ad4d0407567"
ref: "sync_settings_ui-v0.8.3"
resolved-ref: dde5566b2c6eb38a8e1e58a4252925f3baca8ad1
url: "https://github.com/kuhyx/utils"
source: git
version: "0.8.2"
version: "0.8.3"
synchronized:
dependency: transitive
description:

View File

@ -52,7 +52,7 @@ dependencies:
http: 1.6.0
http_cache_file_store: 2.0.2
latlong2: 0.10.1
material_ui: 1.11.0
material_ui: 1.11.1
path: 1.9.1
path_provider: 2.1.6
permission_handler: 13.0.2
@ -64,7 +64,7 @@ dependencies:
sync_settings_ui:
git:
url: https://github.com/kuhyx/utils
ref: sync_settings_ui-v0.8.2
ref: sync_settings_ui-v0.8.3
path: sync_settings_ui
url_launcher: 6.3.3
uuid: 4.6.0

View File

@ -0,0 +1,157 @@
/// A hand-driven [RunEngine] for the host, controller and screen tests.
library;
import 'package:flutter/foundation.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/run_checkpoint.dart';
import 'package:workout_app/services/run_engine.dart';
import 'package:workout_app/services/run_phase.dart';
/// A checkpoint the tests only need to hand around.
class FakeCheckpoint implements RunCheckpoint {
/// Creates one marked with [tag].
FakeCheckpoint(this.tag);
/// Which snapshot this is.
final int tag;
@override
dynamic noSuchMethod(Invocation invocation) => null;
}
/// Records what the host asked of it; the test moves it along.
class FakeRunEngine extends ChangeNotifier implements RunEngine {
/// Creates an idle engine; [startResult] is what [start] answers.
FakeRunEngine({this.startResult = true, this.restoreResult = true});
/// Answer of [start].
bool startResult;
/// Answer of [restore].
bool restoreResult;
/// How many times [start] ran.
int starts = 0;
/// The checkpoints handed to [restore].
final restored = <RunCheckpoint>[];
/// Whether [dispose] ran.
bool disposed = false;
/// What [finish] returns.
RunTrack? track;
/// Calls in order, for ordering assertions.
final calls = <String>[];
RunPhase _phase = RunPhase.idle;
RunIssue _issue = RunIssue.none;
final _points = <RunPoint>[];
int _checkpoints = 0;
@override
RunPhase get phase => _phase;
@override
RunIssue get issue => _issue;
@override
List<RunPoint> get points => List.unmodifiable(_points);
@override
int get seconds => _points.length * 2;
@override
double get distanceM => _points.length * 6.0;
@override
int? paceTarget;
@override
double? get pace => null;
@override
PaceBand? get band => null;
/// Sets the phase and tells the listeners.
void setPhase(RunPhase phase, {RunIssue issue = RunIssue.none}) {
_phase = phase;
_issue = issue;
notifyListeners();
}
/// One accepted fix 6 m further on.
void addFix() {
final n = _points.length;
_points.add(
RunPoint(
time: DateTime.utc(2026, 11, 9, 12).add(Duration(seconds: n * 2)),
latitude: 48.8584 + n * 0.00005,
longitude: 2.2945,
distanceM: n * 6.0,
),
);
notifyListeners();
}
@override
RunCheckpoint? checkpoint() =>
_phase.isActive ? FakeCheckpoint(++_checkpoints) : null;
@override
Future<bool> start() async {
starts++;
calls.add('start');
if (!startResult) {
setPhase(RunPhase.idle, issue: RunIssue.denied);
return false;
}
setPhase(RunPhase.recording);
return true;
}
@override
Future<bool> restore(RunCheckpoint checkpoint) async {
restored.add(checkpoint);
calls.add('restore');
if (!restoreResult) {
setPhase(RunPhase.idle, issue: RunIssue.streamError);
return false;
}
setPhase(RunPhase.recording);
return true;
}
@override
void pause() {
calls.add('pause');
setPhase(RunPhase.paused);
}
@override
void resume() {
calls.add('resume');
setPhase(RunPhase.recording);
}
@override
void setPaceTarget(int? seconds) {
paceTarget = seconds;
calls.add('pace $seconds');
}
@override
Future<RunTrack?> finish() async {
calls.add('finish');
setPhase(RunPhase.finished);
return track;
}
@override
void dispose() {
disposed = true;
super.dispose();
}
}

View File

@ -100,4 +100,16 @@ class QuietCues extends FeedbackCues {
@override
Future<void> workoutFinished() async => finishes++;
/// How many times advice to finish was cued.
int suggestions = 0;
/// How many times the 5 h end was cued.
int autoEnds = 0;
@override
Future<void> finishSuggested() async => suggestions++;
@override
Future<void> autoEnded() async => autoEnds++;
}

View File

@ -0,0 +1,69 @@
/// A [RunController] over the real recorder behind the in-process host.
library;
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter_test/flutter_test.dart' show addTearDown;
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_controller.dart';
import 'package:workout_app/services/run_engine_recorder.dart';
import 'package:workout_app/services/run_host.dart';
import 'package:workout_app/services/run_link.dart';
import 'fake_run_service.dart';
import 'run_test_fixtures.dart';
/// Builds the controller; the host (which keeps a watchdog timer while a run
/// is active) is released at the end of the test.
RunController buildRunController({
required ManualPositionSource source,
PositionSource Function()? idleSourceFor,
FeedbackCues? cues,
FakeForegroundRunClient? service,
RunSaveFn? save,
List<RunTrack>? saved,
}) {
final client = service ?? FakeForegroundRunClient();
final link = LoopbackRunLink.build(
client: client,
engineFactory: recorderEngineFactory(() => source),
cues: cues ?? FeedbackCues(AudioPlayer()),
save:
save ??
(track) async {
saved?.add(track);
return (stored: true, reason: 'saved');
},
);
addTearDown(link.host.dispose);
return RunController(
idleSourceFor: idleSourceFor ?? () => source,
service: client,
link: link,
soundOn: () async => true,
retryEvery: const Duration(milliseconds: 1),
);
}
/// A link to nobody: commands vanish and nothing ever answers.
class SilentLink implements RunHostLink {
@override
Stream<Map<Object?, Object?>> get messages => const Stream.empty();
@override
void send(Map<String, Object?> command) {}
@override
Future<void> close() async {}
}
/// A controller whose host is down.
RunController buildSilentController() => RunController(
idleSourceFor: ManualPositionSource.new,
service: FakeForegroundRunClient(isSupported: false),
link: SilentLink(),
soundOn: () async => true,
hostTimeout: const Duration(milliseconds: 50),
retryEvery: const Duration(milliseconds: 1),
);

View File

@ -0,0 +1,144 @@
/// A [RunHost] over fakes, with every outward call recorded.
library;
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/run_checkpoint.dart';
import 'package:workout_app/services/run_checkpoint_store.dart';
import 'package:workout_app/services/run_engine.dart';
import 'package:workout_app/services/run_host.dart';
import 'fake_run_engine.dart';
import 'fake_run_service.dart';
import 'run_test_fixtures.dart';
/// A port that remembers everything.
class FakePort implements RunHostPort {
/// Messages sent to the UI.
final sent = <Map<String, Object?>>[];
/// Notification redraws as `title|text`.
final notes = <String>[];
/// How often the service was stopped.
int stops = 0;
/// How often the app was brought forward.
int launches = 0;
/// The newest message.
Map<String, Object?> get last => sent.last;
@override
void send(Map<String, Object?> message) => sent.add(message);
@override
Future<void> notify({required String title, required String text}) async =>
notes.add('$title|$text');
@override
Future<void> stopService() async => stops++;
@override
void launchApp() => launches++;
}
/// A store in memory that can be told to fail.
class FakeStore implements RunCheckpointStore {
/// The held checkpoint.
RunCheckpoint? held;
/// Saves that went through.
int saves = 0;
/// Clears.
int clears = 0;
/// Makes [save] throw.
bool saveFails = false;
@override
Future<void> save(RunCheckpoint c) async {
if (saveFails) throw Exception('disk full');
saves++;
held = c;
}
@override
Future<RunCheckpoint?> load() async => held;
@override
Future<void> clear() async {
clears++;
held = null;
}
}
/// Everything a host test touches.
class HostRig {
/// Builds the rig; [save] defaults to "stored".
HostRig({
this.saveThrows = false,
this.saveStores = true,
RunHostPort? hostPort,
}) {
host = RunHost(
engineFactory: (hooks) {
lastHooks = hooks;
final engine = FakeRunEngine(
startResult: startResult,
restoreResult: restoreResult,
)..track = sampleTrack();
engines.add(engine);
return engine;
},
port: hostPort ?? port,
store: store,
cues: cues,
save: (track) async {
if (saveThrows) throw Exception('db locked');
saved.add(track);
return (stored: saveStores, reason: 'saved');
},
);
}
/// Whether the save throws.
final bool saveThrows;
/// What the save answers.
final bool saveStores;
/// What new engines answer to start / restore.
bool startResult = true;
/// See [startResult].
bool restoreResult = true;
/// The host under test.
late final RunHost host;
/// Recorded port.
final port = FakePort();
/// Recorded store.
final store = FakeStore();
/// Recorded cues.
final cues = QuietCues();
/// Tracks the host saved.
final saved = <RunTrack>[];
/// Every engine the host built, oldest first.
final engines = <FakeRunEngine>[];
/// The hooks of the newest engine.
late RunEngineHooks lastHooks;
/// The newest engine.
FakeRunEngine get engine => engines.last;
/// Sends a UI command.
Future<void> cmd(String name, [Map<String, Object?> extra = const {}]) =>
host.handle({'cmd': name, ...extra});
}

View File

@ -0,0 +1,109 @@
/// A run screen/controller over the in-process host and a fake engine: the
/// run lives in the rig, so a test can throw the screen away and look at it.
library;
import 'dart:async';
import 'package:flutter_test/flutter_test.dart' show WidgetTester, addTearDown;
import 'package:material_ui/material_ui.dart';
import 'package:workout_app/screens/run_screen.dart';
import 'package:workout_app/services/run_controller.dart';
import 'package:workout_app/services/run_link.dart';
import 'package:workout_app/ui/theme.dart';
import 'fake_run_engine.dart';
import 'fake_run_service.dart';
import 'fake_run_uploader.dart';
import 'run_host_rig.dart';
import 'run_test_fixtures.dart';
import 'screens/_run_screen_helpers.dart';
/// The in-process host the controllers talk to, shared by every controller
/// the rig builds (as the real service is shared by every screen).
class PersistRig {
/// Creates the rig; [supported] says whether a service exists.
PersistRig({bool supported = true})
: service = FakeForegroundRunClient(isSupported: supported) {
port = LoopbackRunPort(service);
host = HostRig(hostPort: port);
addTearDown(host.host.dispose);
link = _RigLink(this);
}
/// The fake Android service.
final FakeForegroundRunClient service;
/// The host and its recorded collaborators.
late final HostRig host;
/// The port the host would use (loopback to [service]).
late final LoopbackRunPort port;
/// The link every controller gets.
late final RunHostLink link;
/// Controllers built, oldest first.
final controllers = <RunController>[];
final uploader = FakeRunUploader();
final paceStore = MemoryPaceStore();
final navigator = GlobalKey<NavigatorState>();
/// The newest engine.
FakeRunEngine get engine => host.engine;
/// A controller over the shared host and an idle source that grants.
RunController build() {
final c = RunController(
idleSourceFor: ManualPositionSource.new,
service: service,
link: link,
soundOn: () async => true,
hostTimeout: const Duration(milliseconds: 200),
retryEvery: const Duration(milliseconds: 1),
);
controllers.add(c);
return c;
}
/// A screen over [build].
RunScreen screen({bool resuming = false}) => RunScreen(
controllerFactory: build,
uploader: uploader,
paceStore: paceStore,
mapBuilder: fakeTileMap,
resuming: resuming,
);
/// Pumps an app with the run screen pushed on an empty route.
Future<void> pump(WidgetTester tester, {bool resuming = false}) async {
await tester.pumpWidget(
MaterialApp(
navigatorKey: navigator,
theme: buildAppTheme(),
home: const SizedBox(),
),
);
navigator.currentState!.push(
MaterialPageRoute<void>(builder: (_) => screen(resuming: resuming)),
);
await tester.pumpAndSettle();
}
}
/// Sends commands to the rig's host and relays its snapshots.
class _RigLink implements RunHostLink {
_RigLink(this._rig);
final PersistRig _rig;
@override
Stream<Map<Object?, Object?>> get messages => _rig.port.messages;
@override
void send(Map<String, Object?> command) =>
unawaited(_rig.host.host.handle(command));
@override
Future<void> close() async {}
}

View File

@ -0,0 +1,74 @@
/// Shared rig of the run recorder persistence tests.
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_checkpoint.dart';
import 'package:workout_app/services/run_recorder.dart';
import 'run_test_fixtures.dart';
final DateTime persistT0 = DateTime.utc(2026, 11, 9, 12);
/// A recorder plus everything it reports, on a clock the test moves.
class PersistHost {
PersistHost({
ManualPositionSource? source,
DateTime? at,
Duration autoEnd = const Duration(hours: 5),
}) : source = source ?? ManualPositionSource(),
now = at ?? persistT0 {
recorder = RunRecorder(
sourceFor: () => this.source,
onKilometre: km.add,
onSuggestFinish: suggestions.add,
onAutoEnd: () => autoEnds++,
onCheckpoint: checkpoints.add,
clock: () => now,
autoEndAfter: autoEnd,
);
}
final ManualPositionSource source;
late final RunRecorder recorder;
DateTime now;
final km = <int>[];
final suggestions = <RunSuggestion>[];
final checkpoints = <RunCheckpoint>[];
int autoEnds = 0;
/// Finishes inside `testWidgets`, where awaiting a stream cancel hangs the
/// fake-async zone: it runs in the real one instead.
Future<RunTrack?> finishAfter(WidgetTester tester) async =>
await tester.runAsync<RunTrack?>(recorder.finish);
/// Delivers [fixes]; inside `testWidgets` pass the tester, whose pump
/// drains the queue where a real-time `pumpEventQueue` would hang.
Future<void> feed(Iterable<GpsFix> fixes, {WidgetTester? tester}) async {
for (final fix in fixes) {
source.controller.add(fix);
}
await (tester?.pump() ?? pumpEventQueue());
}
}
RunCheckpoint viaJson(RunCheckpoint c) => RunCheckpoint.fromJson(
jsonDecode(jsonEncode(c.toJson())) as Map<String, Object?>,
);
Future<RunCheckpoint> checkpointAfter(int fixes, {bool pause = false}) async {
final h = PersistHost();
await h.recorder.start();
await h.feed(straightRun(fixes));
if (pause) h.recorder.pause();
final c = h.recorder.checkpoint()!;
await h.recorder.finish();
h.recorder.dispose();
return viaJson(c);
}
class ThrowingSource extends ManualPositionSource {
@override
Stream<GpsFix> fixes({Duration interval = const Duration(seconds: 2)}) =>
throw StateError('provider gone');
}

View File

@ -0,0 +1,46 @@
/// Shared rig of the run watchdog tests.
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/run_recorder.dart';
import 'package:workout_app/services/run_watchdog.dart';
import 'run_test_fixtures.dart';
final DateTime watchdogStart = DateTime.utc(2026, 11, 9, 12);
class WatchdogRig {
WatchdogRig({this.autoEnd = const Duration(hours: 5)}) {
dog = RunWatchdog(
clock: () => now,
onSuggest: suggestions.add,
onAutoEnd: () => autoEnds++,
autoEndAfter: autoEnd,
);
}
final Duration autoEnd;
late final RunWatchdog dog;
DateTime now = watchdogStart;
final suggestions = <RunSuggestion>[];
int autoEnds = 0;
double metres = 0;
void advance(Duration d) {
now = now.add(d);
dog.check();
}
/// [minutes] minutes with a fresh, motionless fix every minute.
void idle(int minutes) {
for (var i = 0; i < minutes; i++) {
now = now.add(const Duration(minutes: 1));
fix();
dog.check();
}
}
/// An accepted fix at the current clock, [stepM] further on.
void fix({double stepM = 0, int secondsIntoRun = 0}) {
metres += stepM;
dog.onFix(fixAt(secondsIntoRun, metres), FixVerdict.accepted, metres);
}
}

View File

@ -0,0 +1,41 @@
// Tapping the run notification must reach the run host, in every flavor.
//
// flutter_foreground_task 11.0.3 only calls the task handler's
// onNotificationPressed when the intent that opened the activity is MAIN +
// category LAUNCHER (ForegroundService.handleNotificationContentIntent). The
// sandbox flavor has no LAUNCHER filter (see sandbox_manifest_test.dart), so
// `getLaunchIntentForPackage` hands the notification a MAIN + INFO intent and
// the plugin silently drops the press: the app opened on the plain run screen,
// never on the finish modal. MainActivity therefore relays such presses
// itself, for the cold start (onCreate) and for a running app (onNewIntent).
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
/// Relative to the package root, which is `flutter test`'s cwd.
const _activityPath =
'android/app/src/main/kotlin/com/kuhy/workout_app/MainActivity.kt';
void main() {
late String activity;
setUpAll(() => activity = File(_activityPath).readAsStringSync());
test('the activity hands a press the plugin ignored to the plugin', () {
expect(
activity,
contains('ForegroundService.handleNotificationContentIntent'),
);
expect(activity, contains('Intent.CATEGORY_LAUNCHER'));
expect(activity, contains('"onNotificationPressed"'));
});
test('both a cold start and a running app are covered', () {
expect(activity, contains('override fun onCreate'));
expect(activity, contains('override fun onNewIntent'));
});
test('a press the plugin already handled is not relayed twice', () {
expect(activity, contains('hasCategory(Intent.CATEGORY_LAUNCHER)'));
});
}

View File

@ -11,43 +11,17 @@ import 'package:workout_app/screens/run_screen.dart';
import 'package:workout_app/services/pace_target_store.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_controller.dart';
import 'package:workout_app/services/run_saver.dart';
import 'package:workout_app/services/run_engine_recorder.dart';
import 'package:workout_app/services/run_link.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/run_map_slot.dart';
import '../fake_run_service.dart';
import '../fake_run_uploader.dart';
import '../run_test_fixtures.dart';
import '../widgets/_run_map_fixtures.dart';
import '_run_screen_helpers.dart';
/// An in-memory [PaceTargetStore].
class MemoryPaceStore implements PaceTargetStore {
/// The stored target.
int value = kDefaultPaceTarget;
/// How many times [save] ran.
int saves = 0;
@override
Future<int> load() async => value;
@override
Future<void> save(int seconds) async {
saves++;
value = seconds;
}
}
/// The real map slot over fake tiles, so nothing reaches the network.
Widget fakeTileMap(
BuildContext context,
ValueListenable<List<RunPoint>> points,
ValueListenable<LatLng?> position,
) => RunMapSlot(
points: points,
position: position,
tileProviderOpener: fakeTiles(),
);
export '_run_screen_helpers.dart';
/// Everything a test needs to drive and inspect one screen.
class RunHarness {
@ -71,17 +45,28 @@ class RunHarness {
final settingsOpened = <int>[];
final navigator = GlobalKey<NavigatorState>();
RunController build() => RunController(
sourceFor: () => source,
service: service,
cues: cues,
save: (track) async {
await saveGate?.future;
if (saveThrows) throw Exception('disk full');
saved.add(track);
return const RunSaveResult(stored: true, reason: 'saved');
},
);
RunController build() {
final link = LoopbackRunLink.build(
client: service,
engineFactory: recorderEngineFactory(() => source),
cues: cues,
save: (track) async {
await saveGate?.future;
if (saveThrows) throw Exception('disk full');
saved.add(track);
return (stored: true, reason: 'saved');
},
);
// The run outlives the screen, so the test ends it (the recorder keeps a
// watchdog timer).
addTearDown(link.host.dispose);
return RunController(
idleSourceFor: () => source,
service: service,
link: link,
soundOn: () async => true,
);
}
Widget app() => MaterialApp(
navigatorKey: navigator,
@ -124,15 +109,3 @@ class RunHarness {
await tester.pumpAndSettle();
}
}
Finder key(String id) => find.byKey(Key(id));
Future<void> tapKey(WidgetTester tester, String id) async {
await tester.tap(key(id));
// Stream cancel only completes on the real event loop, so give it a turn
// before settling the frames.
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 10)),
);
await tester.pumpAndSettle();
}

View File

@ -0,0 +1,68 @@
// Pieces of the run screen harness that do not need a recorder.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:latlong2/latlong.dart';
import 'package:material_ui/material_ui.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/pace_target_store.dart';
import 'package:workout_app/widgets/run_map_slot.dart';
import '../widgets/_run_map_fixtures.dart';
/// An in-memory [PaceTargetStore].
class MemoryPaceStore implements PaceTargetStore {
/// The stored target.
int value = kDefaultPaceTarget;
/// How many times [save] ran.
int saves = 0;
@override
Future<int> load() async => value;
@override
Future<void> save(int seconds) async {
saves++;
value = seconds;
}
}
/// The real map slot over fake tiles, so nothing reaches the network.
Widget fakeTileMap(
BuildContext context,
ValueListenable<List<RunPoint>> points,
ValueListenable<LatLng?> position,
) => RunMapSlot(
points: points,
position: position,
tileProviderOpener: fakeTiles(),
);
Finder key(String id) => find.byKey(Key(id));
Future<void> tapKey(WidgetTester tester, String id) async {
await tester.tap(key(id));
// Stream cancel only completes on the real event loop, so give it a turn
// before settling the frames.
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 10)),
);
await tester.pumpAndSettle();
}
/// Taps finish and the modal's red check, the only way a run ends.
Future<void> tapFinish(WidgetTester tester) async {
await tapKey(tester, 'run_finish');
await tester.tap(key('run_finish_confirm'));
// The host finishes on the real event loop (a stream cancel and messages
// between the screen and the host); give it turns, then settle the frames.
for (var i = 0; i < 3; i++) {
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 100)),
);
await tester.pump();
}
await tester.pumpAndSettle();
}

View File

@ -11,6 +11,7 @@ import 'package:workout_app/services/storage_service.dart';
import '../fake_audio_platform.dart';
import '../fake_geolocator.dart';
import '../fake_secure_storage.dart';
import '../run_persist_rig.dart';
import '_home_test_fixtures.dart';
void main() {
@ -31,6 +32,9 @@ void main() {
final original = GeolocatorPlatform.instance;
GeolocatorPlatform.instance = FakeGeolocator();
addTearDown(() => GeolocatorPlatform.instance = original);
// `main` installs the real wiring; here the run lives in a fake host.
RunScreen.defaultControllerFactory = PersistRig().build;
addTearDown(() => RunScreen.defaultControllerFactory = null);
});
testWidgets('the run icon opens the run screen and back returns home', (

View File

@ -0,0 +1,73 @@
// (c) A run in progress opens the app on the live run screen.
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.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/screens/home_screen.dart';
import 'package:workout_app/screens/run_screen.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/ui/theme.dart';
import '../fake_audio_platform.dart';
import '../fake_secure_storage.dart';
import '../run_persist_rig.dart';
import '_home_test_fixtures.dart';
void main() {
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
StorageService.resetForTesting();
await StorageService.init();
installFakeSecureStorage();
installFakeAudioPlatform();
});
Widget app({required bool openRun, bool openWorkout = false}) => MaterialApp(
theme: buildAppTheme(),
home: HomeScreen(
configuredProbe: () async => false,
clock: () => DateTime(2026, 8, 15, 18),
openWorkoutOnLaunch: openWorkout,
openRunOnLaunch: openRun,
),
);
testWidgets('a cold start with a run owed lands on the run screen', (
tester,
) async {
final rig = PersistRig();
RunScreen.defaultControllerFactory = rig.build;
addTearDown(() => RunScreen.defaultControllerFactory = null);
await rig.host.cmd('start'); // the host restored the run
rig.engine.addFix();
await pumpHome(tester, app(openRun: true, openWorkout: true));
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
await tester.pump(const Duration(milliseconds: 400));
expect(find.byType(RunScreen), findsOneWidget);
expect(find.byKey(const Key('run_pause')), findsOneWidget);
expect(find.byKey(const Key('run_start')), findsNothing);
// The workout did not open over it, and back does nothing.
await tester.binding.handlePopRoute();
await tester.pump(const Duration(milliseconds: 400));
expect(find.byType(RunScreen), findsOneWidget);
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 300)),
);
});
testWidgets('with no run owed home shows as before', (tester) async {
await pumpHome(tester, app(openRun: false));
expect(find.byType(RunScreen), findsNothing);
expect(find.byKey(const Key('home_run')), findsOneWidget);
});
}

View File

@ -0,0 +1,65 @@
// A notification tap on standing advice that lands while no screen is
// listening (a cold start: the UI process was dead) still opens the finish
// modal once the screen attaches and asks the host where the run stands.
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.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/services/run_phase.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/ui/theme.dart';
import '../fake_audio_platform.dart';
import '../run_persist_rig.dart';
import '_run_screen_helpers.dart';
void main() {
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
installFakeAudioPlatform();
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
StorageService.resetForTesting();
await StorageService.init();
});
testWidgets('a press before the screen exists shows the modal on attach', (
tester,
) async {
final rig = PersistRig();
await rig.host.cmd('start');
rig.host.lastHooks.onSuggest('gpsRestored');
// The plugin reaches the service while the UI process is still starting.
rig.host.host.notificationPressed();
// Not rig.pump: its pumpAndSettle never ends while the pulse repeats.
await tester.pumpWidget(
MaterialApp(
navigatorKey: rig.navigator,
theme: buildAppTheme(),
home: const SizedBox(),
),
);
rig.navigator.currentState!.push(
MaterialPageRoute<void>(builder: (_) => rig.screen(resuming: true)),
);
for (var i = 0; i < 6; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
expect(key('run_finish_dialog'), findsOneWidget);
expect(rig.engine.phase, RunPhase.recording);
expect(key('run_finish_pulse'), findsOneWidget);
await tester.tap(key('run_finish_cancel'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(rig.engine.phase, RunPhase.recording);
expect(key('run_finish_dialog'), findsNothing);
});
}

View File

@ -96,7 +96,7 @@ void main() {
await tapKey(tester, 'run_start');
expect(find.byType(PolylineLayer), findsNothing);
await h.run(tester, 5, from: 10);
await tapKey(tester, 'run_finish');
await tapFinish(tester);
expect(h.saved.single.points, hasLength(5));
});
}

View File

@ -61,7 +61,7 @@ void main() {
await tapKey(tester, 'run_pause');
_expectFits(tester);
await tapKey(tester, 'run_finish');
await tapFinish(tester);
_expectFits(tester);
});

View File

@ -31,7 +31,7 @@ void main() {
await tapKey(tester, 'run_start');
// 3 m/s is 10.8 km/h: over any walking cap, fine for the running filter.
await h.run(tester, 30);
await tapKey(tester, 'run_finish');
await tapFinish(tester);
final track = h.saved.single;
expect(track.sport, RunSport.running);

View File

@ -0,0 +1,90 @@
// The run outlives the screen: nothing but the finish button plus its confirm
// modal ends it. Checks (a) leaving or replacing the screen never stops an
// active run, (b) finishing needs the modal's red check, (c) the app opens on
// the live run.
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.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/screens/run_screen.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/run_phase.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/run_landing.dart';
import '../fake_audio_platform.dart';
import '../run_persist_rig.dart';
import '_run_screen_helpers.dart';
void main() {
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
installFakeAudioPlatform();
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
StorageService.resetForTesting();
await StorageService.init();
});
Future<void> startRun(WidgetTester tester, PersistRig rig) async {
await tapKey(tester, 'run_start');
rig.engine.addFix();
await tester.pumpAndSettle();
}
group('(c) the app opens on the run', () {
testWidgets('coming back to the front lands on the run again', (
tester,
) async {
final rig = PersistRig();
RunScreen.defaultControllerFactory = rig.build;
addTearDown(() => RunScreen.defaultControllerFactory = null);
await rig.host.cmd('start');
var owed = false;
await tester.pumpWidget(
MaterialApp(
theme: buildAppTheme(),
home: RunLanding(
owed: () async => owed,
child: const SizedBox(key: Key('home')),
),
),
);
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.pumpAndSettle();
expect(find.byType(RunScreen), findsNothing);
owed = true;
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.pumpAndSettle();
expect(find.byType(RunScreen), findsOneWidget);
// Already on the run: another resume does not stack a second one.
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.pumpAndSettle();
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(find.byType(RunScreen), findsOneWidget);
});
testWidgets('with no run owed home stays home', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: RunLanding(
owed: () async => false,
child: const SizedBox(key: Key('home')),
),
),
);
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.pumpAndSettle();
expect(key('home'), findsOneWidget);
});
});
}

View File

@ -0,0 +1,236 @@
// The run outlives the screen: nothing but the finish button plus its confirm
// modal ends it. Checks (a) leaving or replacing the screen never stops an
// active run, (b) finishing needs the modal's red check, (c) the app opens on
// the live run.
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.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/screens/run_screen.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/run_phase.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/run_landing.dart';
import '../fake_audio_platform.dart';
import '../run_persist_rig.dart';
import '_run_screen_helpers.dart';
void main() {
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
installFakeAudioPlatform();
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
StorageService.resetForTesting();
await StorageService.init();
});
Future<void> startRun(WidgetTester tester, PersistRig rig) async {
await tapKey(tester, 'run_start');
rig.engine.addFix();
await tester.pumpAndSettle();
}
group('(a) the run outlives the screen', () {
testWidgets('disposing the screen leaves the run recording', (
tester,
) async {
final rig = PersistRig();
await rig.pump(tester);
await startRun(tester, rig);
final engine = rig.engine;
await tester.pumpWidget(const SizedBox());
await tester.pumpAndSettle();
expect(find.byType(RunScreen), findsNothing);
expect(engine.phase, RunPhase.recording);
expect(engine.disposed, isFalse);
expect(rig.service.calls, isNot(contains('stop')));
expect(rig.host.saved, isEmpty);
});
testWidgets('back and pop do nothing while recording or paused', (
tester,
) async {
final rig = PersistRig();
await rig.pump(tester);
await startRun(tester, rig);
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(find.byType(RunScreen), findsOneWidget);
await tapKey(tester, 'run_pause');
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(find.byType(RunScreen), findsOneWidget);
expect(rig.engine.phase, RunPhase.paused);
expect(rig.service.calls, isNot(contains('stop')));
});
testWidgets('a second screen finds the run and cannot restart it', (
tester,
) async {
final rig = PersistRig();
await rig.pump(tester);
await startRun(tester, rig);
final engine = rig.engine;
// The system closed the screen; the app opens a new one.
await tester.pumpWidget(const SizedBox());
await rig.pump(tester, resuming: true);
expect(key('run_pause'), findsOneWidget, reason: 'live run, not idle');
expect(key('run_start'), findsNothing);
// A start command from the new controller is refused by the host.
await tester.runAsync(rig.controllers.last.start);
expect(rig.host.engines, hasLength(1));
expect(engine.starts, 1);
expect(engine.phase, RunPhase.recording);
expect(rig.service.calls, isNot(contains('stop')));
});
testWidgets('"new run" cannot replace a run that is still going', (
tester,
) async {
final rig = PersistRig();
await rig.pump(tester);
await startRun(tester, rig);
final engine = rig.engine;
// A rebuilt controller (what "new run" makes) asking to start.
final second = rig.build();
await tester.runAsync(() async {
await second.attach();
await second.start();
});
expect(rig.host.engines, hasLength(1));
expect(engine.phase, RunPhase.recording);
expect(engine.disposed, isFalse);
second.dispose();
});
});
group('(b) finishing needs the modal', () {
testWidgets('the finish button asks, the cross keeps recording', (
tester,
) async {
final rig = PersistRig();
await rig.pump(tester);
await startRun(tester, rig);
await tapKey(tester, 'run_finish');
expect(key('run_finish_dialog'), findsOneWidget);
expect(rig.engine.phase, RunPhase.recording);
await tapKey(tester, 'run_finish_cancel');
expect(key('run_finish_dialog'), findsNothing);
expect(rig.engine.phase, RunPhase.recording);
expect(rig.host.saved, isEmpty);
expect(key('run_pause'), findsOneWidget);
});
testWidgets('tapping outside or pressing back cancels', (tester) async {
final rig = PersistRig();
await rig.pump(tester);
await startRun(tester, rig);
await tapKey(tester, 'run_finish');
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(key('run_finish_dialog'), findsNothing);
expect(rig.engine.phase, RunPhase.recording);
await tapKey(tester, 'run_finish');
await tester.tapAt(const Offset(2, 2));
await tester.pumpAndSettle();
expect(key('run_finish_dialog'), findsNothing);
expect(rig.engine.phase, RunPhase.recording);
});
testWidgets('the red check ends and saves the run', (tester) async {
final rig = PersistRig();
await rig.pump(tester);
await startRun(tester, rig);
await tapKey(tester, 'run_finish');
await tapKey(tester, 'run_finish_confirm');
await tester.pumpAndSettle();
expect(rig.engine.phase, RunPhase.finished);
expect(rig.host.saved, hasLength(1));
expect(key('run_saved_ok'), findsOneWidget);
expect(rig.service.calls.last, 'stop');
expect(key('run_again'), findsOneWidget);
});
testWidgets('the modal shows icons only, no words', (tester) async {
final rig = PersistRig();
await rig.pump(tester);
await startRun(tester, rig);
await tapKey(tester, 'run_finish');
final dialog = find.byKey(const Key('run_finish_dialog'));
expect(
find.descendant(of: dialog, matching: find.byType(Text)),
findsNothing,
);
expect(
find.descendant(of: dialog, matching: find.byIcon(Icons.check)),
findsOneWidget,
);
expect(
find.descendant(of: dialog, matching: find.byIcon(Icons.close)),
findsOneWidget,
);
});
testWidgets('advice makes the finish button pulse, nothing more', (
tester,
) async {
final rig = PersistRig();
await rig.pump(tester);
await startRun(tester, rig);
expect(key('run_finish_still'), findsOneWidget);
rig.host.lastHooks.onSuggest('stationary');
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
expect(key('run_finish_pulse'), findsOneWidget);
expect(rig.engine.phase, RunPhase.recording);
expect(key('run_finish_dialog'), findsNothing);
expect(rig.host.saved, isEmpty);
});
testWidgets(
'a notification tap on advice opens the modal, still unconfirmed',
(tester) async {
final rig = PersistRig();
await rig.pump(tester);
await startRun(tester, rig);
rig.host.lastHooks.onSuggest('gpsLost');
await tester.pump();
rig.host.host.notificationPressed();
await tester.pump();
await tester.pump();
expect(key('run_finish_dialog'), findsOneWidget);
expect(rig.engine.phase, RunPhase.recording);
await tester.tap(key('run_finish_cancel'));
await tester.pump(const Duration(milliseconds: 400));
expect(rig.engine.phase, RunPhase.recording);
expect(key('run_finish_dialog'), findsNothing);
},
);
});
}

View File

@ -44,7 +44,7 @@ void main() {
final h = RunHarness();
await h.pump(tester);
await tapKey(tester, 'run_start');
await tapKey(tester, 'run_finish');
await tapFinish(tester);
expect(key('run_issue_tooShort'), findsOneWidget);
expect(h.saved, isEmpty);
expect(key('run_saved_ok'), findsNothing);
@ -77,7 +77,7 @@ void main() {
await h.pump(tester);
await tapKey(tester, 'run_start');
await h.run(tester, 4);
await tapKey(tester, 'run_finish');
await tapFinish(tester);
await tester.pumpAndSettle();
expect(key('run_saved_failed'), findsOneWidget);
expect(key('run_saved_ok'), findsNothing);

View File

@ -8,6 +8,7 @@ import 'package:shared_preferences_platform_interface/shared_preferences_async_p
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/sandbox/sandbox_run_replay.dart';
import 'package:workout_app/screens/run_screen.dart';
import 'package:workout_app/services/run_wiring.dart';
import 'package:workout_app/ui/theme.dart';
import '../fake_audio_platform.dart';
@ -21,6 +22,9 @@ void main() {
setUp(() {
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
// The real wiring: the recorder behind a loopback link (no service here).
installRunWiring();
addTearDown(() => RunScreen.defaultControllerFactory = null);
installFakeAudioPlatform();
Sandbox.enabled = true;
// Fast enough that a walking replay would show within the test.

View File

@ -11,6 +11,7 @@ import 'package:workout_app/models/run_record.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/screens/run_screen.dart';
import 'package:workout_app/services/run_wiring.dart';
import 'package:workout_app/services/backup_service.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/ui/theme.dart';
@ -30,6 +31,9 @@ void main() {
setUp(() async {
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
// The real wiring: the recorder behind a loopback link (no service here).
installRunWiring();
addTearDown(() => RunScreen.defaultControllerFactory = null);
StorageService.resetForTesting();
await StorageService.init();
installFakeAudioPlatform();
@ -82,6 +86,9 @@ void main() {
last = shown;
}
await tester.tap(key('run_finish'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
await tester.tap(key('run_finish_confirm'));
await Future<void>.delayed(const Duration(milliseconds: 500));
runs = await StorageService.instance.listRuns();
});

View File

@ -29,9 +29,7 @@ class _GatedSource extends ManualPositionSource {
void main() {
setUp(installFakeAudioPlatform);
testWidgets('idle: start, zeros and the map slot', (
tester,
) async {
testWidgets('idle: start, zeros and the map slot', (tester) async {
final h = RunHarness();
await h.pump(tester);
@ -70,7 +68,7 @@ void main() {
await tapKey(tester, 'run_resume');
expect(key('run_pause'), findsOneWidget);
await tapKey(tester, 'run_finish');
await tapFinish(tester);
await tester.pumpAndSettle();
expect(key('run_saved_ok'), findsOneWidget);
expect(h.saved.single.points, hasLength(8));
@ -87,7 +85,7 @@ void main() {
await tapKey(tester, 'run_start');
await h.run(tester, 4);
await tapKey(tester, 'run_pause');
await tapKey(tester, 'run_finish');
await tapFinish(tester);
expect(key('run_saved_ok'), findsOneWidget);
});
@ -98,7 +96,7 @@ void main() {
await h.pump(tester);
await tapKey(tester, 'run_start');
await h.run(tester, 4);
await tapKey(tester, 'run_finish');
await tapFinish(tester);
await tapKey(tester, 'run_again');
expect(key('run_start'), findsOneWidget);
@ -106,7 +104,7 @@ void main() {
expect(key('run_saved_ok'), findsNothing);
await tapKey(tester, 'run_start');
await tapKey(tester, 'run_finish');
await tapFinish(tester);
await tester.pumpAndSettle();
await tapKey(tester, 'run_close');
await tester.pumpAndSettle();
@ -130,7 +128,7 @@ void main() {
await tester.pumpAndSettle();
expect(find.byType(RunScreen), findsOneWidget);
await tapKey(tester, 'run_finish');
await tapFinish(tester);
await tester.pumpAndSettle();
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
@ -164,9 +162,10 @@ void main() {
await tapKey(tester, 'run_start');
await h.run(tester, 4);
await tester.tap(key('run_finish'));
await tapKey(tester, 'run_finish');
await tester.tap(key('run_finish_confirm'));
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 20)),
() => Future<void>.delayed(const Duration(milliseconds: 100)),
);
await tester.pump();
expect(key('run_saving'), findsOneWidget);
@ -175,7 +174,7 @@ void main() {
gate.complete();
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 20)),
() => Future<void>.delayed(const Duration(milliseconds: 100)),
);
await tester.pumpAndSettle();
expect(key('run_saving'), findsNothing);

View File

@ -180,11 +180,23 @@ void main() {
// 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('never stops the service while a run is owed', () async {
client.running = true;
final stopped = await stopStaleBreakService(
client,
hasActiveWorkout: () async => false,
runIsOwed: () async => true,
);
expect(stopped, isFalse);
expect(client.calls, isNot(contains('stop')));
});
test('stops a service whose workout no longer exists', () async {
client.running = true;
final stopped = await stopStaleBreakService(
client,
hasActiveWorkout: () async => false,
runIsOwed: () async => false,
);
expect(stopped, isTrue);
expect(client.calls, contains('stop'));
@ -197,6 +209,7 @@ void main() {
final stopped = await stopStaleBreakService(
client,
hasActiveWorkout: () async => true,
runIsOwed: () async => false,
);
expect(stopped, isFalse);
expect(client.calls, isNot(contains('stop')));
@ -209,6 +222,7 @@ void main() {
await stopStaleBreakService(
client,
hasActiveWorkout: () async => false,
runIsOwed: () async => false,
),
isFalse,
);
@ -223,6 +237,7 @@ void main() {
await stopStaleBreakService(
client,
hasActiveWorkout: () async => false,
runIsOwed: () async => false,
),
isFalse,
);

View File

@ -0,0 +1,36 @@
// The long cue of a run: advice to finish and the 5 h auto-end.
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/feedback_cues.dart';
import '../fake_audio_platform.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late FakeAudioRecorder audio;
setUp(() => audio = installFakeAudioPlatform());
for (final (name, cue) in <(String, Future<void> Function(FeedbackCues))>[
('advice to finish', (c) => c.finishSuggested()),
('the auto end', (c) => c.autoEnded()),
]) {
group(name, () {
test('chimes', () async {
await cue(FeedbackCues(AudioPlayer()));
expect(audio.resumedSources.single, contains('workout_done'));
});
test('stays silent when sound is off', () async {
await cue(FeedbackCues(AudioPlayer())..soundOn = false);
expect(audio.resumedSources, isEmpty);
});
test('a chime that cannot play is logged, not thrown', () async {
audio.failNextPlay = true;
await cue(FeedbackCues(AudioPlayer()));
expect(audio.resumedSources, isEmpty);
});
});
}
}

View File

@ -0,0 +1,108 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/run_math.dart';
const double _degM = 111194.9;
GpsFix _fix(int seconds, double northM, {double accuracy = 5}) => GpsFix(
time: DateTime.utc(2026, 11, 9, 12).add(Duration(seconds: seconds)),
latitude: 48.8584 + northM / _degM,
longitude: 2.2945,
altitudeM: 30,
accuracyM: accuracy,
);
GpsFilter _runningTo30m() => GpsFilter()
..add(_fix(0, 0))
..add(_fix(10, 30));
void main() {
group('a gap over 30 s is bridged by a straight line', () {
test('at 5:00/km the line is credited and flagged as a bridge', () {
final f = _runningTo30m();
expect(f.add(_fix(310, 30 + 1000)), FixVerdict.accepted);
expect(f.distanceM, closeTo(1030, 1));
expect(f.points.last.link, RunLink.bridge);
});
test('a bridge faster than 2:30/km is drawn but earns 0 m', () {
final f = _runningTo30m();
expect(f.add(_fix(70, 30 + 1000)), FixVerdict.accepted); // 60 s, 1 km
expect(f.distanceM, closeTo(30, 0.5));
expect(f.points.last.link, RunLink.bridge);
expect(f.points.last.latitude, closeTo(48.8584 + 1030 / _degM, 1e-6));
});
test('a bridge slower than 12:00/km earns 0 m', () {
final f = _runningTo30m()..add(_fix(1010, 30 + 100)); // 1000 s, 100 m
expect(f.distanceM, closeTo(30, 0.5));
expect(f.points.last.link, RunLink.bridge);
});
test('the jump cap does not reject the first fix after a gap', () {
final f = _runningTo30m();
expect(f.add(_fix(3610, 30 + 50000)), FixVerdict.accepted);
expect(f.distanceM, closeTo(30, 0.5));
});
test('exactly 30 s is not a gap', () {
final f = _runningTo30m()..add(_fix(40, 30 + 90)); // 30 s, 3 m/s
expect(f.points.last.link, RunLink.continuous);
expect(f.distanceM, closeTo(120, 0.5));
});
test('31 s is a gap and still credited at a running pace', () {
final f = _runningTo30m()..add(_fix(41, 30 + 93));
expect(f.points.last.link, RunLink.bridge);
expect(f.distanceM, closeTo(123, 0.5));
});
test('a pause still earns nothing and is a segment start', () {
final f = _runningTo30m()
..breakSegment()
..add(_fix(310, 30 + 1000));
expect(f.distanceM, closeTo(30, 0.5));
expect(f.points.last.link, RunLink.segmentStart);
});
test('moving time counts only a credited bridge', () {
final credited = _runningTo30m()..add(_fix(310, 1030));
expect(movingSeconds(credited.points), 10 + 300);
final vehicle = _runningTo30m()..add(_fix(70, 1030));
expect(movingSeconds(vehicle.points), 10);
});
});
group('GpsFilter.restore', () {
test('rebuilds points, segment break and jump count', () {
final f = _runningTo30m()..breakSegment();
final back = GpsFilter.restore(
points: f.points,
segmentBreak: f.segmentBreak,
jumps: f.jumps,
);
expect(back.points, f.points);
expect(back.segmentBreak, isTrue);
expect(back.distanceM, f.distanceM);
expect(back.add(_fix(310, 5000)), FixVerdict.accepted);
expect(back.points.last.link, RunLink.segmentStart);
});
test('an empty restore behaves like a fresh filter', () {
final back = GpsFilter.restore(points: const []);
expect(back.distanceM, 0);
expect(back.add(_fix(0, 0)), FixVerdict.accepted);
});
test('the jump count carries over', () {
final back = GpsFilter.restore(
points: _runningTo30m().points,
jumps: kMaxConsecutiveJumps - 1,
);
// 4 earlier jumps + this one = 5: re-anchors instead of rejecting.
expect(back.add(_fix(12, 30 + 1000)), FixVerdict.accepted);
expect(back.points.last.link, RunLink.segmentStart);
});
});
}

View File

@ -90,15 +90,15 @@ void main() {
expect(f.points.first.altitudeM, 30);
});
test('standing-still jitter and a long dropout earn no distance', () {
test('standing-still jitter earns nothing, a long dropout is bridged', () {
final f = GpsFilter()
..add(_fix(0, 0))
..add(_fix(10, 2)); // 0.2 m/s: standing
expect(f.distanceM, 0);
f.add(_fix(60, 100)); // 50 s later: unseen motion
expect(f.distanceM, 0);
f.add(_fix(60, 100)); // 50 s later, 98 m: 8:30/km, bridged and credited
expect(f.distanceM, closeTo(98, 0.2));
f.add(_fix(70, 127)); // seen again, moving
expect(f.distanceM, closeTo(27, 0.2));
expect(f.distanceM, closeTo(125, 0.2));
expect(f.points, hasLength(4));
});

View File

@ -0,0 +1,159 @@
@TestOn('vm')
library;
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/run_checkpoint.dart';
import 'package:workout_app/services/run_checkpoint_store.dart';
import 'package:workout_app/services/run_phase.dart';
RunCheckpoint _checkpoint({int moving = 6}) => RunCheckpoint(
startedAt: DateTime.utc(2026, 11, 9, 12),
savedAt: DateTime.utc(2026, 11, 9, 12, 5),
phase: RunPhase.recording,
points: [
RunPoint(
time: DateTime.utc(2026, 11, 9, 12),
latitude: 48.8584,
longitude: 2.2945,
distanceM: 0,
),
],
movingSeconds: moving,
distanceM: 0,
km: 0,
segmentBreak: false,
jumps: 0,
);
void main() {
late Directory dir;
late File file;
setUp(() {
dir = Directory.systemTemp.createTempSync('run_checkpoint_store_');
file = File('${dir.path}/sub/run_checkpoint.json');
});
tearDown(() => dir.deleteSync(recursive: true));
group('FileRunCheckpointStore', () {
test('load with no file is null', () async {
expect(await FileRunCheckpointStore(file).load(), isNull);
});
test('save then load returns the same checkpoint', () async {
final store = FileRunCheckpointStore(file);
await store.save(_checkpoint());
final back = (await store.load())!;
expect(back.movingSeconds, 6);
expect(back.startedAt, DateTime.utc(2026, 11, 9, 12));
expect(back.points, hasLength(1));
});
test('a save leaves no temp file behind', () async {
await FileRunCheckpointStore(file).save(_checkpoint());
final names = file.parent.listSync().map((e) => e.path).toList();
expect(names, [file.path]);
});
test('a second save replaces the first', () async {
final store = FileRunCheckpointStore(file);
await store.save(_checkpoint());
await store.save(_checkpoint(moving: 99));
expect((await store.load())!.movingSeconds, 99);
});
test('overlapping saves keep the newest and all complete', () async {
final store = FileRunCheckpointStore(file);
final saves = [
for (var i = 1; i <= 20; i++) store.save(_checkpoint(moving: i)),
];
await Future.wait(saves);
expect((await store.load())!.movingSeconds, 20);
expect(file.parent.listSync(), hasLength(1));
});
test('clear removes the file and is safe when there is none', () async {
final store = FileRunCheckpointStore(file);
await store.clear();
await store.save(_checkpoint());
await store.clear();
expect(file.existsSync(), isFalse);
expect(await store.load(), isNull);
});
test(
'a corrupt file is moved aside, logged loudly, load is null',
() async {
file.parent.createSync(recursive: true);
file.writeAsStringSync('{"v":1, truncated');
final logs = <String>[];
final store = FileRunCheckpointStore(
file,
clock: () => DateTime.utc(2026, 11, 9, 13),
onLoud: logs.add,
);
expect(await store.load(), isNull);
expect(file.existsSync(), isFalse);
final aside = file.parent
.listSync()
.map((e) => e.path)
.where((p) => p.contains('.corrupt-'))
.toList();
expect(aside, hasLength(1));
expect(File(aside.single).readAsStringSync(), contains('truncated'));
expect(logs.single, contains('corrupt'));
expect(aside.single, contains('.corrupt-'));
},
);
test('valid JSON of the wrong shape is corrupt too', () async {
file.parent.createSync(recursive: true);
file.writeAsStringSync('[1, 2, 3]');
expect(await FileRunCheckpointStore(file).load(), isNull);
expect(file.existsSync(), isFalse);
});
test('JSON that fails the codec is corrupt too', () async {
file.parent.createSync(recursive: true);
file.writeAsStringSync('{"v": 1}');
expect(await FileRunCheckpointStore(file).load(), isNull);
expect(file.existsSync(), isFalse);
});
test('bytes that are not UTF-8 are corrupt too', () async {
file.parent.createSync(recursive: true);
file.writeAsBytesSync([0xff, 0xfe, 0x00, 0x80]);
expect(await FileRunCheckpointStore(file).load(), isNull);
expect(file.existsSync(), isFalse);
});
test(
'an unreadable file surfaces the error instead of hiding it',
() async {
file.parent.createSync(recursive: true);
file.writeAsStringSync('{}');
Process.runSync('chmod', ['000', file.path]);
addTearDown(() => Process.runSync('chmod', ['644', file.path]));
await expectLater(
FileRunCheckpointStore(file).load(),
throwsA(isA<FileSystemException>()),
);
},
);
});
group('MemoryRunCheckpointStore', () {
test('keeps the last save until cleared', () async {
final store = MemoryRunCheckpointStore();
expect(await store.load(), isNull);
await store.save(_checkpoint());
expect((await store.load())!.movingSeconds, 6);
await store.clear();
expect(await store.load(), isNull);
});
});
}

View File

@ -0,0 +1,198 @@
import 'dart:convert';
import 'dart:math';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/run_checkpoint.dart';
import 'package:workout_app/services/run_phase.dart';
RunPoint _point(
int i, {
RunLink link = RunLink.continuous,
double? altitude = 30,
}) => RunPoint(
time: DateTime.utc(2026, 11, 9, 12).add(Duration(seconds: i * 2)),
latitude: 48.8584 + i * 0.00002,
longitude: 2.2945 - i * 0.000013,
altitudeM: altitude,
distanceM: i * 6.25,
link: link,
);
RunCheckpoint _checkpoint({
RunPhase phase = RunPhase.recording,
List<RunPoint>? points,
int? target = 330,
}) => RunCheckpoint(
startedAt: DateTime.utc(2026, 11, 9, 11, 59, 58),
savedAt: DateTime.utc(2026, 11, 9, 12, 5),
phase: phase,
points: points ?? [for (var i = 0; i < 4; i++) _point(i)],
movingSeconds: 6,
distanceM: 18.75,
km: 0,
segmentBreak: phase == RunPhase.paused,
jumps: 2,
paceTargetSeconds: target,
);
Map<String, Object?> _roundTripped(RunCheckpoint c) =>
jsonDecode(jsonEncode(c.toJson())) as Map<String, Object?>;
void _expectSame(RunCheckpoint a, RunCheckpoint b) {
expect(b.id, a.id);
expect(b.startedAt, a.startedAt);
expect(b.savedAt, a.savedAt);
expect(b.phase, a.phase);
expect(b.points, a.points);
expect(b.movingSeconds, a.movingSeconds);
expect(b.distanceM, a.distanceM);
expect(b.km, a.km);
expect(b.segmentBreak, a.segmentBreak);
expect(b.jumps, a.jumps);
expect(b.paceTargetSeconds, a.paceTargetSeconds);
}
void main() {
group('round trip through JSON text', () {
test('a recording checkpoint', () {
final c = _checkpoint();
_expectSame(c, RunCheckpoint.fromJson(_roundTripped(c)));
});
test('a paused one with no pace target', () {
final c = _checkpoint(phase: RunPhase.paused, target: null);
final back = RunCheckpoint.fromJson(_roundTripped(c));
_expectSame(c, back);
expect(back.paceTargetSeconds, isNull);
});
test('a run that has no fix yet', () {
final c = _checkpoint(points: const []);
final back = RunCheckpoint.fromJson(_roundTripped(c));
_expectSame(c, back);
expect(back.id, '2026-11-09T11:59:58Z');
});
test('segment and bridge markers and a missing altitude survive', () {
final c = _checkpoint(
points: [
_point(0),
_point(1, link: RunLink.bridge, altitude: null),
_point(2, link: RunLink.segmentStart),
],
);
final back = RunCheckpoint.fromJson(_roundTripped(c));
expect(back.points[1].link, RunLink.bridge);
expect(back.points[1].altitudeM, isNull);
expect(back.points[2].link, RunLink.segmentStart);
_expectSame(c, back);
});
test('the id is the first point time, like the saved track', () {
expect(_checkpoint().id, '2026-11-09T12:00:00Z');
});
test('many random shapes survive (seeded)', () {
final rng = Random(20261117);
for (var n = 0; n < 200; n++) {
final count = rng.nextInt(40);
final points = [
for (var i = 0; i < count; i++)
RunPoint(
time: DateTime.utc(
2026,
11,
9,
12,
).add(Duration(seconds: i * (1 + rng.nextInt(90)))),
latitude: rng.nextDouble() * 180 - 90,
longitude: rng.nextDouble() * 360 - 180,
altitudeM: rng.nextBool() ? rng.nextDouble() * 4000 - 400 : null,
distanceM: rng.nextDouble() * 50000,
link: RunLink.values[rng.nextInt(RunLink.values.length)],
),
];
final c = RunCheckpoint(
startedAt: DateTime.utc(2026, 11, 9, 11, rng.nextInt(60)),
savedAt: DateTime.utc(2026, 11, 9, 13, rng.nextInt(60)),
phase: rng.nextBool() ? RunPhase.recording : RunPhase.paused,
points: points,
movingSeconds: rng.nextInt(20000),
distanceM: rng.nextDouble() * 50000,
km: rng.nextInt(50),
segmentBreak: rng.nextBool(),
jumps: rng.nextInt(5),
paceTargetSeconds: rng.nextBool() ? 200 + rng.nextInt(400) : null,
);
_expectSame(c, RunCheckpoint.fromJson(_roundTripped(c)));
}
});
});
group('fromJson rejects bad data with a FormatException', () {
final good = _roundTripped(_checkpoint());
void rejects(String why, Map<String, Object?> Function() make) {
test(why, () {
expect(() => RunCheckpoint.fromJson(make()), throwsFormatException);
});
}
rejects('an unknown version', () => {...good, 'v': 99});
rejects('no version', () => {...good}..remove('v'));
rejects('a missing field', () => {...good}..remove('moving'));
rejects('a wrongly typed field', () => {...good, 'moving': 'six'});
rejects('a bad start time', () => {...good, 'startedAt': 'yesterday'});
rejects('a non-string start time', () => {...good, 'startedAt': 5});
rejects('idle as the phase', () => {...good, 'phase': 'idle'});
rejects('finished as the phase', () => {...good, 'phase': 'finished'});
rejects('an unknown phase', () => {...good, 'phase': 'dancing'});
rejects('points that are not a list', () => {...good, 'points': 'many'});
rejects(
'a point that is not a list',
() => {
...good,
'points': [5],
},
);
rejects(
'a short point',
() => {
...good,
'points': [
[1, 2.0],
],
},
);
rejects(
'a point with a text coordinate',
() => {
...good,
'points': [
[1, 'x', 2.0, null, 3.0, 0],
],
},
);
rejects(
'a point with a bad altitude',
() => {
...good,
'points': [
[1, 1.0, 2.0, 'high', 3.0, 0],
],
},
);
rejects(
'a point with an unknown link',
() => {
...good,
'points': [
[1, 1.0, 2.0, null, 3.0, 7],
],
},
);
rejects('a non-numeric pace target', () => {...good, 'target': 'fast'});
rejects('a non-bool segment break', () => {...good, 'segBreak': 1});
});
}

View File

@ -6,11 +6,11 @@ import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_controller.dart';
import 'package:workout_app/services/run_recorder.dart';
import 'package:workout_app/services/run_saver.dart';
import 'package:workout_app/services/run_phase.dart';
import '../fake_audio_platform.dart';
import '../fake_run_service.dart';
import '../run_controller_rig.dart';
import '../run_test_fixtures.dart';
class _CueSpy extends FeedbackCues {
@ -30,12 +30,11 @@ RunController _build(
PositionSource Function()? idleSourceFor,
FeedbackCues? cues,
FakeForegroundRunClient? service,
}) => RunController(
sourceFor: () => source,
}) => buildRunController(
source: source,
idleSourceFor: idleSourceFor,
service: service ?? FakeForegroundRunClient(),
cues: cues ?? _CueSpy(),
save: (_) async => const RunSaveResult(stored: true, reason: 'saved'),
service: service,
);
void main() {
@ -61,7 +60,7 @@ void main() {
await controller.watchIdle();
expect(controller.blocked, isTrue);
expect(controller.canStart, isFalse);
expect(controller.recorder.issue, RunIssue.deniedForever);
expect(controller.view.issue, RunIssue.deniedForever);
source.access = LocationAccess.granted;
await controller.recheckAccess();
@ -105,12 +104,12 @@ void main() {
final service = FakeForegroundRunClient();
final cues = _CueSpy();
final controller = _build(source, cues: cues, service: service);
controller.recorder.setPaceTarget(300);
await controller.start();
await controller.start(paceTarget: 300);
for (var i = 0; i < 12; i++) {
source.controller.add(fixAt(i * 2, i * 6.0));
}
await pumpEventQueue();
await pumpEventQueue();
expect(cues.paced, [PaceCue.tooSlow]);
expect(service.drawn.last, endsWith('5:35'));
controller.dispose();
@ -125,6 +124,7 @@ void main() {
source.controller.add(fixAt(i * 2, i * 6.0));
}
await pumpEventQueue();
await pumpEventQueue();
expect(service.drawn.last.split(' '), hasLength(2));
controller.dispose();
});

View File

@ -0,0 +1,101 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/foreground_run_client.dart';
import 'package:workout_app/services/foreground_run_client_flutter.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_controller.dart';
import 'package:workout_app/services/run_phase.dart';
import 'package:workout_app/services/storage_service.dart';
import '../fake_audio_platform.dart';
import '../fake_run_service.dart';
import '../run_controller_rig.dart';
import '../run_test_fixtures.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late FakeAudioRecorder audio;
late List<RunTrack> saved;
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
StorageService.resetForTesting();
await StorageService.init();
audio = installFakeAudioPlatform();
saved = [];
});
Future<void> feed(ManualPositionSource source, List<int> northM) async {
for (final (i, m) in northM.indexed) {
source.controller.add(fixAt(i * 2, m.toDouble()));
}
await pumpEventQueue();
await pumpEventQueue();
}
RunController build(
ManualPositionSource source,
FakeForegroundRunClient service,
) => buildRunController(source: source, service: service, saved: saved);
group('the run outlives the controller', () {
test('disposing mid-run never stops the service or the run', () async {
final source = ManualPositionSource();
final service = FakeForegroundRunClient();
final controller = build(source, service);
await controller.start();
await feed(source, [0, 6]);
controller.dispose();
expect(service.calls, isNot(contains('stop')));
expect(saved, isEmpty);
// The fix stream is still being listened to.
source.controller.add(fixAt(4, 12));
await pumpEventQueue();
});
test('a second start while a run is going changes nothing', () async {
final source = ManualPositionSource();
final service = FakeForegroundRunClient();
final controller = build(source, service);
await controller.start();
await controller.start();
expect(service.starts, hasLength(1));
expect(source.subscriptions, 1);
controller.dispose();
});
test('attach gives up when no host ever answers', () async {
final controller = buildSilentController();
await controller.attach();
expect(controller.attachGaveUp, isTrue);
expect(controller.view.synced, isFalse);
controller.dispose();
});
test('a start nobody answers times out loudly, run untouched', () async {
final controller = buildSilentController();
await controller.start();
expect(controller.active, isFalse);
controller.dispose();
});
test('a pace target change and an ack are commands', () async {
final source = ManualPositionSource();
final controller = build(source, FakeForegroundRunClient());
await controller.start(paceTarget: 330);
expect(controller.view.paceTarget, 330);
controller
..setPaceTarget(300)
..ackPrompt();
await pumpEventQueue();
expect(controller.view.paceTarget, 300);
controller.dispose();
});
});
}

View File

@ -1,19 +1,16 @@
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/foreground_run_client.dart';
import 'package:workout_app/services/foreground_run_client_flutter.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_controller.dart';
import 'package:workout_app/services/run_recorder.dart';
import 'package:workout_app/services/run_saver.dart';
import 'package:workout_app/services/run_phase.dart';
import 'package:workout_app/services/storage_service.dart';
import '../fake_audio_platform.dart';
import '../fake_run_service.dart';
import '../run_controller_rig.dart';
import '../run_test_fixtures.dart';
void main() {
@ -33,31 +30,19 @@ void main() {
saved = [];
});
tearDown(() => Sandbox.enabled = false);
RunController build(
ManualPositionSource source,
FakeForegroundRunClient service, {
Future<RunSaveResult> Function(RunTrack)? save,
}) => RunController(
sourceFor: () => source,
service: service,
cues: FeedbackCues(AudioPlayer()),
save:
save ??
(track) async {
saved.add(track);
return const RunSaveResult(stored: true, reason: 'saved');
},
);
Future<void> feed(ManualPositionSource source, List<int> northM) async {
for (final (i, m) in northM.indexed) {
source.controller.add(fixAt(i * 2, m.toDouble()));
}
await pumpEventQueue();
await pumpEventQueue();
}
RunController build(
ManualPositionSource source,
FakeForegroundRunClient service,
) => buildRunController(source: source, service: service, saved: saved);
test('starts the service after access and before the first fix', () async {
final source = ManualPositionSource();
var subscribedAtStart = -1;
@ -97,10 +82,9 @@ void main() {
ManualPositionSource(access: LocationAccess.deniedForever),
service,
);
await controller.watchIdle();
await controller.start();
expect(service.calls, isEmpty);
expect(controller.serviceState, RunServiceState.none);
expect(controller.recorder.issue, RunIssue.deniedForever);
expect(controller.view.issue, RunIssue.deniedForever);
expect(controller.active, isFalse);
controller.dispose();
});
@ -117,8 +101,8 @@ void main() {
expect(service.calls, ['has', 'request', 'start']);
expect(controller.serviceState, RunServiceState.runningHidden);
expect(service.drawn, hasLength(1));
expect(controller.recorder.livePoints.value, hasLength(3));
expect(service.drawn.first, '0.00|0:00 -:--');
expect(controller.view.livePoints.value, hasLength(3));
controller.dispose();
});
@ -131,8 +115,8 @@ void main() {
await controller.start();
await feed(source, [0, 6]);
expect(controller.serviceState, RunServiceState.failed);
expect(controller.recorder.phase, RunPhase.recording);
expect(controller.recorder.livePoints.value, hasLength(2));
expect(controller.view.phase, RunPhase.recording);
expect(controller.view.livePoints.value, hasLength(2));
await controller.finish();
expect(controller.serviceState, RunServiceState.failed);
controller.dispose();
@ -151,12 +135,11 @@ void main() {
controller.dispose();
});
test('the sandbox asks for the data-sync service type alone', () async {
Sandbox.enabled = true;
test('every start asks for the location service type', () async {
final service = FakeForegroundRunClient();
final controller = build(ManualPositionSource(), service);
await controller.start();
expect(service.starts, [false]);
expect(service.starts, [true]);
controller.dispose();
});
@ -168,7 +151,7 @@ void main() {
await feed(source, [for (var i = 0; i <= 170; i++) i * 6]);
await Future<void>.delayed(const Duration(milliseconds: 50));
expect(controller.recorder.distanceM, greaterThan(1000));
expect(controller.view.distanceM, greaterThan(1000));
expect(
audio.resumedSources.where((s) => s.contains('workout_done')),
hasLength(1),
@ -185,6 +168,7 @@ void main() {
controller
..pause()
..resume();
await pumpEventQueue();
final notified = <bool>[];
controller.addListener(() => notified.add(controller.saving));
@ -208,16 +192,15 @@ void main() {
await controller.finish();
expect(saved, isEmpty);
expect(controller.saved, isNull);
expect(controller.recorder.issue, RunIssue.tooShort);
expect(controller.view.issue, RunIssue.tooShort);
expect(service.calls.last, 'stop');
controller.dispose();
});
test('a failing save is reported, not thrown', () async {
final source = ManualPositionSource();
final controller = build(
source,
FakeForegroundRunClient(),
final controller = buildRunController(
source: source,
save: (_) async => throw Exception('disk full'),
);
await controller.start();
@ -228,15 +211,6 @@ void main() {
controller.dispose();
});
test('leaving mid-run stops the service', () async {
final source = ManualPositionSource();
final service = FakeForegroundRunClient();
final controller = build(source, service);
await controller.start();
controller.dispose();
expect(service.calls.last, 'stop');
});
test('the real client is unsupported off Android', () {
expect(FlutterForegroundRunClient().isSupported, isFalse);
expect(kRunOngoingChannelId, endsWith('_v1'));

View File

@ -0,0 +1,95 @@
// The adapter over the real recorder: what the host relies on.
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/run_engine.dart';
import 'package:workout_app/services/run_engine_recorder.dart';
import 'package:workout_app/services/run_phase.dart';
import '../run_test_fixtures.dart';
RunEngineHooks _hooks({
void Function()? onAutoEnd,
List<String>? advice,
List<int>? km,
}) => RunEngineHooks(
onKilometre: (k) => km?.add(k),
onPaceCue: (PaceCue _) {},
onSuggest: (why) => advice?.add(why),
onAutoEnd: onAutoEnd ?? () {},
);
void main() {
test('mirrors the recorder and ends cleanly', () async {
final source = ManualPositionSource();
final engine = recorderEngineFactory(() => source)(_hooks());
expect(engine.phase, RunPhase.idle);
expect(engine.checkpoint(), isNull);
var changes = 0;
void listener() => changes++;
engine
..addListener(listener)
..setPaceTarget(330);
expect(await engine.start(), isTrue);
straightRun(20).forEach(source.controller.add);
await pumpEventQueue();
expect(engine.phase, RunPhase.recording);
expect(engine.issue, RunIssue.none);
expect(engine.points, hasLength(20));
expect(engine.seconds, greaterThan(0));
expect(engine.distanceM, greaterThan(0));
expect(engine.paceTarget, 330);
expect(engine.pace, isNotNull);
expect(engine.band, isNotNull);
expect(engine.checkpoint(), isNotNull);
engine
..pause()
..resume();
expect(engine.phase, RunPhase.recording);
final track = await engine.finish();
expect(track!.points, hasLength(20));
expect(changes, greaterThan(0));
engine
..removeListener(listener)
..dispose();
});
test('a checkpoint resumes the run in a fresh engine', () async {
final source = ManualPositionSource();
final first = recorderEngineFactory(() => source)(_hooks());
await first.start();
straightRun(20).forEach(source.controller.add);
await pumpEventQueue();
final checkpoint = first.checkpoint()!;
first.dispose();
final second = recorderEngineFactory(() => ManualPositionSource())(
_hooks(),
);
expect(await second.restore(checkpoint), isTrue);
expect(second.phase, RunPhase.recording);
expect(second.points, hasLength(20));
await second.finish();
second.dispose();
});
test('the 5 h limit and advice reach the hooks', () async {
final source = ManualPositionSource();
var now = DateTime.utc(2026, 11, 9, 12);
final advice = <String>[];
var ended = 0;
final engine = recorderEngineFactory(
() => source,
clock: () => now,
autoEndAfter: const Duration(hours: 1),
)(_hooks(advice: advice, onAutoEnd: () => ended++));
await engine.start();
now = now.add(const Duration(hours: 2));
await Future<void>.delayed(const Duration(seconds: 6));
expect(ended, 1);
await engine.finish();
engine.dispose();
});
}

View File

@ -0,0 +1,33 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/run_gap_bridge.dart';
void main() {
group('bridgeCredits (2:30 to 12:00 min/km)', () {
test('a steady 5:00/km jog across a gap is credited', () {
expect(bridgeCredits(stepM: 1000, gapSeconds: 300), isTrue);
});
test('the pace bounds are inclusive', () {
expect(bridgeCredits(stepM: 1000, gapSeconds: 150), isTrue); // 2:30
expect(bridgeCredits(stepM: 1000, gapSeconds: 720), isTrue); // 12:00
});
test('faster than 2:30/km is a vehicle: drawn, not credited', () {
expect(bridgeCredits(stepM: 1000, gapSeconds: 149), isFalse);
});
test('slower than 12:00/km is standing about: not credited', () {
expect(bridgeCredits(stepM: 1000, gapSeconds: 721), isFalse);
});
test('no movement or no time credits nothing', () {
expect(bridgeCredits(stepM: 0, gapSeconds: 600), isFalse);
expect(bridgeCredits(stepM: 100, gapSeconds: 0), isFalse);
expect(bridgeCredits(stepM: -1, gapSeconds: 60), isFalse);
});
test('the minimum speed constant matches the slowest pace', () {
expect(kBridgeMinSpeedMps, closeTo(1000 / 720, 1e-9));
});
});
}

View File

@ -0,0 +1,146 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/run_phase.dart';
import 'package:workout_app/services/run_wire.dart';
import '../fake_audio_platform.dart';
import '../fake_run_engine.dart';
import '../run_host_rig.dart';
void main() {
setUp(installFakeAudioPlatform);
group('suggestions never end the run', () {
test('cue, glyph in the notification, run keeps recording', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.engine.addFix();
rig.lastHooks.onSuggest('stationary');
await pumpEventQueue();
expect(rig.cues.suggestions, 1);
expect(rig.engine.phase, RunPhase.recording);
expect(rig.port.last['suggestion'], 'stationary');
expect(rig.port.notes.last, startsWith('⏸ '));
expect(rig.saved, isEmpty);
expect(rig.port.stops, 0);
});
test('each reason has its own symbol', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
for (final (why, glyph) in [
('vehicleSpeed', '⚡'),
('gpsLost', '⌖'),
('restored', '↻'),
]) {
rig.lastHooks.onSuggest(why);
rig.engine.addFix();
expect(rig.port.notes.last, startsWith('$glyph '), reason: why);
}
});
test('a tap on the notification asks for the finish modal', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.lastHooks.onSuggest('gpsLost');
rig.host.notificationPressed();
expect(rig.port.launches, 1);
expect(rig.port.last['prompt'], isTrue);
expect(rig.engine.phase, RunPhase.recording, reason: 'still needs a tap');
await rig.cmd(RunCmd.ackPrompt);
expect(rig.port.last['prompt'], isFalse);
expect(rig.port.last['suggestion'], 'gpsLost');
});
test('a tap with no advice only opens the app', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.host.notificationPressed();
expect(rig.port.launches, 1);
expect(rig.port.last['prompt'], isFalse);
});
test('advice while finishing is dropped', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
final finishing = rig.cmd(RunCmd.finish);
rig.lastHooks.onSuggest('stationary');
await finishing;
expect(rig.cues.suggestions, 0);
});
});
group('5 h auto end', () {
test('saves like a finish and plays its own cue', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.engine.addFix();
rig.lastHooks.onAutoEnd();
await pumpEventQueue();
expect(rig.saved, hasLength(1));
expect(rig.cues.autoEnds, 1);
expect(rig.cues.finishes, 0);
expect(rig.store.held, isNull);
expect(rig.port.stops, 1);
});
});
group('hooks', () {
test('kilometres and pace cues reach the cues', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.lastHooks.onKilometre(1);
await pumpEventQueue();
expect(rig.cues.kilometres, [1]);
});
});
group('restoreFromStore', () {
test('false with no checkpoint, and no engine is built', () async {
final rig = HostRig();
expect(await rig.host.restoreFromStore(), isFalse);
expect(rig.engines, isEmpty);
});
test('resumes the run and tells the UI', () async {
final rig = HostRig();
rig.store.held = FakeCheckpoint(7);
expect(await rig.host.restoreFromStore(), isTrue);
expect(rig.engine.restored.single, isA<FakeCheckpoint>());
expect(rig.port.last['phase'], 'recording');
});
test(
'a checkpoint that cannot resume is kept and the issue shown',
() async {
final rig = HostRig()..restoreResult = false;
rig.store.held = FakeCheckpoint(7);
expect(await rig.host.restoreFromStore(), isTrue);
expect(rig.store.held, isNotNull);
expect(rig.port.last['issue'], 'streamError');
},
);
});
test('unknown commands are ignored', () async {
final rig = HostRig();
await rig.cmd('nonsense');
expect(rig.engines, isEmpty);
expect(rig.port.sent, isEmpty);
});
test('dispose lets go without ending anything', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.host.dispose();
expect(rig.engine.disposed, isTrue);
expect(rig.saved, isEmpty);
expect(rig.store.clears, 0);
rig.host.dispose();
});
}

View File

@ -0,0 +1,194 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/run_phase.dart';
import 'package:workout_app/services/run_wire.dart';
import '../fake_audio_platform.dart';
import '../fake_run_engine.dart';
import '../run_host_rig.dart';
void main() {
setUp(installFakeAudioPlatform);
group('start', () {
test('builds an engine, records, and tells the UI', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start, {'paceTarget': 330, 'sound': false});
expect(rig.engine.phase, RunPhase.recording);
expect(rig.engine.paceTarget, 330);
expect(rig.cues.soundOn, isFalse);
expect(rig.port.last['phase'], 'recording');
expect(rig.port.last['from'], 0);
});
test('a second start never restarts a live run', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.engine.addFix();
await rig.cmd(RunCmd.start);
expect(rig.engines, hasLength(1));
expect(rig.engine.starts, 1);
expect(rig.engine.disposed, isFalse);
expect(rig.port.last['total'], 1);
expect(rig.port.last['from'], 0, reason: 'a re-sync sends it all');
});
test('a refused start leaves the issue for the UI', () async {
final rig = HostRig()..startResult = false;
await rig.cmd(RunCmd.start);
expect(rig.port.last['phase'], 'idle');
expect(rig.port.last['issue'], 'denied');
});
test('a start after a finished run builds a fresh engine', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
await rig.cmd(RunCmd.finish);
await rig.cmd(RunCmd.start);
expect(rig.engines, hasLength(2));
expect(rig.engines.first.disposed, isTrue);
expect(rig.engine.phase, RunPhase.recording);
expect(rig.port.last['done'], isFalse);
});
});
group('snapshots', () {
test('send only the new points, hello sends all', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.engine
..addFix()
..addFix();
expect(rig.port.last['from'], 1);
expect(rig.port.last['pts'], hasLength(1));
await rig.cmd(RunCmd.hello);
expect(rig.port.last['from'], 0);
expect(rig.port.last['pts'], hasLength(2));
expect(isRunMessage(rig.port.last), isTrue);
});
test('hello with no run answers idle', () async {
final rig = HostRig();
await rig.cmd(RunCmd.hello);
expect(rig.port.last['phase'], 'idle');
});
});
group('checkpoint and notification', () {
test('every change of an active run is saved and redrawn', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.engine
..addFix()
..addFix();
await pumpEventQueue();
expect(rig.store.saves, greaterThanOrEqualTo(3));
expect(rig.port.notes, isNotEmpty);
final redraws = rig.port.notes.length;
rig.engine.notifyListeners();
expect(rig.port.notes, hasLength(redraws), reason: 'same words');
});
test('pause and resume are saved too', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
await pumpEventQueue();
final before = rig.store.saves;
await rig.cmd(RunCmd.pause);
await rig.cmd(RunCmd.resume);
await pumpEventQueue();
expect(rig.engine.calls, containsAllInOrder(['pause', 'resume']));
expect(rig.store.saves, before + 2);
});
test('a failed checkpoint write is logged, not fatal', () async {
final rig = HostRig();
rig.store.saveFails = true;
await rig.cmd(RunCmd.start);
rig.engine.addFix();
await pumpEventQueue();
expect(rig.engine.phase, RunPhase.recording);
});
test('a pace target change goes to the engine', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
await rig.cmd(RunCmd.paceTarget, {'paceTarget': 300});
expect(rig.engine.paceTarget, 300);
});
});
group('finish', () {
test('saves, clears the checkpoint, cues and stops the service', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.engine.addFix();
await rig.cmd(RunCmd.finish);
expect(rig.saved, hasLength(1));
expect(rig.store.held, isNull);
expect(rig.cues.finishes, 1);
expect(rig.port.stops, 1);
expect(rig.port.last['done'], isTrue);
expect(rig.port.last['saved'], {'stored': true, 'reason': 'saved'});
expect(rig.port.sent.any((m) => m['saving'] == true), isTrue);
});
test('a refused save (duplicate) still ends the run cleanly', () async {
final rig = HostRig(saveStores: false);
await rig.cmd(RunCmd.start);
await rig.cmd(RunCmd.finish);
expect(rig.store.held, isNull);
expect(rig.port.last['saved'], {'stored': false, 'reason': 'saved'});
expect(rig.port.stops, 1);
});
test('a save that throws keeps the checkpoint', () async {
final rig = HostRig(saveThrows: true);
await rig.cmd(RunCmd.start);
await pumpEventQueue();
await rig.cmd(RunCmd.finish);
expect(rig.store.held, isNotNull);
expect(rig.port.last['saved'], {
'stored': false,
'reason': 'save failed: Exception: db locked',
});
expect(rig.port.last['done'], isTrue);
});
test('too few fixes: nothing saved, checkpoint cleared', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.engine.track = null;
await rig.cmd(RunCmd.finish);
expect(rig.saved, isEmpty);
expect(rig.store.held, isNull);
expect(rig.port.last['saved'], isNull);
expect(rig.port.last['done'], isTrue);
});
test('finishing with no active run does nothing', () async {
final rig = HostRig();
await rig.cmd(RunCmd.finish);
expect(rig.saved, isEmpty);
expect(rig.port.stops, 0);
});
test('finishing twice at once saves once', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
await Future.wait([rig.cmd(RunCmd.finish), rig.cmd(RunCmd.finish)]);
expect(rig.saved, hasLength(1));
});
});
}

View File

@ -0,0 +1,42 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/run_launch.dart';
import '../fake_run_service.dart';
void main() {
test('no run owed: home as usual, the service is left alone', () async {
final client = FakeForegroundRunClient();
expect(
await resumeRunOnLaunch(owed: () async => false, client: client),
isFalse,
);
expect(client.calls, isEmpty);
});
test('a run owed opens the run and brings its service back', () async {
final client = FakeForegroundRunClient();
expect(
await resumeRunOnLaunch(owed: () async => true, client: client),
isTrue,
);
expect(client.calls, ['start']);
expect(client.starts, [true]);
});
test('a service that will not start still opens the run screen', () async {
final client = FakeForegroundRunClient(startSucceeds: false);
expect(
await resumeRunOnLaunch(owed: () async => true, client: client),
isTrue,
);
});
test('a platform without services just opens the run', () async {
final client = FakeForegroundRunClient(isSupported: false);
expect(
await resumeRunOnLaunch(owed: () async => true, client: client),
isTrue,
);
expect(client.calls, isEmpty);
});
}

View File

@ -0,0 +1,240 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_checkpoint.dart';
import 'package:workout_app/services/run_recorder.dart';
import '../run_recorder_persist_rig.dart';
import '../run_test_fixtures.dart';
void main() {
group('checkpoint()', () {
test('is null when idle and after finish', () async {
final h = PersistHost();
expect(h.recorder.checkpoint(), isNull);
await h.recorder.start();
expect(h.recorder.checkpoint(), isNotNull);
await h.recorder.finish();
expect(h.recorder.checkpoint(), isNull);
h.recorder.dispose();
});
test('holds the whole recording state', () async {
final h = PersistHost(at: persistT0.add(const Duration(minutes: 3)));
await h.recorder.start();
h.recorder.setPaceTarget(330);
await h.feed(straightRun(10));
final c = h.recorder.checkpoint()!;
expect(c.startedAt, persistT0.add(const Duration(minutes: 3)));
expect(c.savedAt, h.now);
expect(c.phase, RunPhase.recording);
expect(c.points, hasLength(10));
expect(c.distanceM, closeTo(54, 0.5));
expect(c.movingSeconds, 18);
expect(c.paceTargetSeconds, 330);
expect(c.segmentBreak, isFalse);
expect(c.id, '2026-11-09T12:00:00Z');
h.recorder.dispose();
});
test('a pause is recorded with its segment break', () async {
final c = await checkpointAfter(5, pause: true);
expect(c.phase, RunPhase.paused);
expect(c.segmentBreak, isTrue);
});
});
group('onCheckpoint', () {
test('fires on start, every accepted fix, pause and resume', () async {
final h = PersistHost();
await h.recorder.start();
expect(h.checkpoints, hasLength(1));
await h.feed(straightRun(3));
expect(h.checkpoints, hasLength(4));
await h.feed([fixAt(6, 18, accuracy: 99)]); // dropped: no checkpoint
expect(h.checkpoints, hasLength(4));
h.recorder.pause();
h.recorder.resume();
expect(h.checkpoints.map((c) => c.phase), [
RunPhase.recording,
RunPhase.recording,
RunPhase.recording,
RunPhase.recording,
RunPhase.paused,
RunPhase.recording,
]);
h.recorder.dispose();
});
});
group('restore()', () {
test('re-enters recording with the state and tells the host', () async {
final saved = await checkpointAfter(10);
final h = PersistHost(at: persistT0.add(const Duration(minutes: 10)));
expect(await h.recorder.restore(saved), isTrue);
expect(h.recorder.phase, RunPhase.recording);
expect(h.recorder.seconds, 18);
expect(h.recorder.distanceM, closeTo(54, 0.5));
expect(h.recorder.livePoints.value, hasLength(10));
expect(h.source.subscriptions, 1);
expect(h.suggestions, [RunSuggestion.restored]);
expect(h.autoEnds, 0);
h.recorder.dispose();
});
test('the dead time is bridged and credited at a running pace', () async {
final saved = await checkpointAfter(10); // last fix: 18 s, 54 m
final h = PersistHost(at: persistT0.add(const Duration(minutes: 10)));
await h.recorder.restore(saved);
await h.feed([fixAt(318, 954)]); // 300 s later, 900 m on: 3 m/s
expect(h.recorder.distanceM, closeTo(954, 1));
expect(h.recorder.seconds, 18 + 300);
expect(h.recorder.livePoints.value.last.link, RunLink.bridge);
h.recorder.dispose();
});
test('a vehicle-speed gap is drawn but earns nothing', () async {
final saved = await checkpointAfter(10);
final h = PersistHost(at: persistT0.add(const Duration(minutes: 10)));
await h.recorder.restore(saved);
await h.feed([fixAt(78, 54 + 600)]); // 60 s, 600 m: 36 km/h
expect(h.recorder.distanceM, closeTo(54, 0.5));
expect(h.recorder.seconds, 18);
expect(h.recorder.livePoints.value, hasLength(11));
h.recorder.dispose();
});
test('kilometres already announced are not announced again', () async {
final h0 = PersistHost();
await h0.recorder.start();
await h0.feed(straightRun(340)); // 2 km
final saved = viaJson(h0.recorder.checkpoint()!);
expect(h0.km, [1, 2]);
await h0.recorder.finish();
h0.recorder.dispose();
final h = PersistHost(at: persistT0.add(const Duration(hours: 1)));
await h.recorder.restore(saved);
await h.feed([fixAt(681, 2043)]); // still km 2
expect(h.km, isEmpty);
await h.feed([fixAt(1000, 2043 + 1000)]); // km 3 across a bridge
expect(h.km, [3]);
h.recorder.dispose();
});
test('a paused run comes back paused, ignoring fixes', () async {
final saved = await checkpointAfter(5, pause: true);
final h = PersistHost(at: persistT0.add(const Duration(minutes: 5)));
expect(await h.recorder.restore(saved), isTrue);
expect(h.recorder.phase, RunPhase.paused);
await h.feed([fixAt(300, 900)]);
expect(h.recorder.livePoints.value, hasLength(5));
h.recorder.resume();
await h.feed([fixAt(310, 930)]);
expect(h.recorder.livePoints.value.last.link, RunLink.segmentStart);
expect(h.recorder.distanceM, closeTo(24, 0.5)); // nothing for the walk
h.recorder.dispose();
});
test('the pace target comes back', () async {
final h0 = PersistHost();
await h0.recorder.start();
h0.recorder.setPaceTarget(300);
await h0.feed(straightRun(3));
final saved = viaJson(h0.recorder.checkpoint()!);
h0.recorder.dispose();
final h = PersistHost(at: persistT0.add(const Duration(minutes: 1)));
await h.recorder.restore(saved);
expect(h.recorder.coach.target, 300);
h.recorder.dispose();
});
test('a run with no fix yet restores and then records', () async {
final h0 = PersistHost();
await h0.recorder.start();
final saved = viaJson(h0.recorder.checkpoint()!);
h0.recorder.dispose();
final h = PersistHost(at: persistT0.add(const Duration(minutes: 1)));
expect(await h.recorder.restore(saved), isTrue);
await h.feed(straightRun(3));
expect(h.recorder.livePoints.value, hasLength(3));
final track = (await h.recorder.finish())!;
expect(track.points, hasLength(3));
h.recorder.dispose();
});
test('finishing a restored run saves one track with the bridge', () async {
final saved = await checkpointAfter(10);
final h = PersistHost(at: persistT0.add(const Duration(minutes: 10)));
await h.recorder.restore(saved);
await h.feed([fixAt(318, 954), fixAt(320, 960)]);
final track = (await h.recorder.finish())!;
expect(track.points, hasLength(12));
expect(track.id, '2026-11-09T12:00:00Z');
expect(track.totalSeconds, 18 + 300 + 2);
expect(track.distanceM, closeTo(960, 1));
h.recorder.dispose();
});
test(
'is refused (false, issue set) when location access is gone',
() async {
final saved = await checkpointAfter(3);
final source = ManualPositionSource(access: LocationAccess.denied);
final h = PersistHost(source: source);
expect(await h.recorder.restore(saved), isFalse);
expect(h.recorder.phase, RunPhase.idle);
expect(h.recorder.issue, RunIssue.denied);
expect(h.suggestions, isEmpty);
expect(source.subscriptions, 0);
h.recorder.dispose();
},
);
test('is false when opening the source throws', () async {
final saved = await checkpointAfter(3);
final h = PersistHost(source: ThrowingSource());
expect(await h.recorder.restore(saved), isFalse);
expect(h.recorder.phase, RunPhase.idle);
expect(h.recorder.issue, RunIssue.streamError);
h.recorder.dispose();
});
test('is false when a run is already going', () async {
final saved = await checkpointAfter(3);
final h = PersistHost();
await h.recorder.start();
expect(await h.recorder.restore(saved), isFalse);
expect(h.recorder.phase, RunPhase.recording);
h.recorder.dispose();
});
test(
'runs afterAccess (the foreground service) before listening',
() async {
final saved = await checkpointAfter(3);
final h = PersistHost();
var served = false;
await h.recorder.restore(saved, afterAccess: () async => served = true);
expect(served, isTrue);
h.recorder.dispose();
},
);
test('past 5 h of wall clock it auto-ends at once on restore', () async {
final saved = await checkpointAfter(10);
final h = PersistHost(
at: persistT0.add(const Duration(hours: 5, seconds: 1)),
);
await h.recorder.restore(saved);
expect(h.autoEnds, 1);
expect(h.suggestions, isEmpty);
// The host now finishes; the run saves like a manual finish.
expect(await h.recorder.finish(), isNotNull);
h.recorder.dispose();
});
});
}

View File

@ -0,0 +1,78 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_checkpoint.dart';
import 'package:workout_app/services/run_recorder.dart';
import '../run_test_fixtures.dart';
import '../run_recorder_persist_rig.dart';
void main() {
group('suggestions and auto end, off the timer and the clock', () {
testWidgets('no fix for 5 min suggests finishing, never ends', (
tester,
) async {
final h = PersistHost();
await h.recorder.start();
await h.feed(straightRun(3), tester: tester);
for (var i = 0; i < 61; i++) {
h.now = h.now.add(const Duration(seconds: 5));
await tester.pump(const Duration(seconds: 5));
}
expect(h.suggestions, [RunSuggestion.gpsLost]);
expect(h.recorder.phase, RunPhase.recording);
await h.finishAfter(tester);
h.recorder.dispose();
});
testWidgets('5 h wall clock ends the run once, pauses included', (
tester,
) async {
final h = PersistHost(autoEnd: const Duration(minutes: 2));
await h.recorder.start();
await h.feed(straightRun(3), tester: tester);
h.recorder.pause();
for (var i = 0; i < 30; i++) {
h.now = h.now.add(const Duration(seconds: 5));
await tester.pump(const Duration(seconds: 5));
}
expect(h.autoEnds, 1);
expect(h.suggestions, isEmpty); // paused: only the auto end
expect(await h.finishAfter(tester), isNotNull);
h.recorder.dispose();
});
testWidgets('finish() stops the timer: nothing fires afterwards', (
tester,
) async {
final h = PersistHost(autoEnd: const Duration(minutes: 1));
await h.recorder.start();
await h.feed(straightRun(3), tester: tester);
await h.finishAfter(tester);
h.now = h.now.add(const Duration(hours: 1));
await tester.pump(const Duration(minutes: 10));
expect(h.autoEnds, 0);
expect(h.suggestions, isEmpty);
h.recorder.dispose();
});
test('a car (jump-rejected fixes) suggests finishing', () async {
final h = PersistHost();
await h.recorder.start();
await h.feed(straightRun(2));
await h.feed([for (var s = 4; s <= 100; s += 2) fixAt(s, s * 10.0)]);
expect(h.suggestions, [RunSuggestion.vehicleSpeed]);
h.recorder.dispose();
});
testWidgets('dispose cancels the watchdog timer', (tester) async {
final h = PersistHost(autoEnd: const Duration(seconds: 1));
await h.recorder.start();
h.now = h.now.add(const Duration(hours: 1));
h.recorder.dispose();
await tester.pump(const Duration(seconds: 30));
expect(h.autoEnds, 0);
});
});
}

View File

@ -0,0 +1,97 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/run_phase.dart';
import 'package:workout_app/services/run_task_handler.dart';
import 'package:workout_app/services/run_wire.dart';
import '../fake_audio_platform.dart';
import '../fake_run_engine.dart';
import '../run_host_rig.dart';
void main() {
setUp(installFakeAudioPlatform);
RunTaskHandler handlerFor(HostRig rig) =>
RunTaskHandler(host: rig.host, port: rig.port);
group('onStart', () {
test('a system start with a checkpoint resumes the run', () async {
final rig = HostRig();
rig.store.held = FakeCheckpoint(1);
await handlerFor(rig).onStart(startedBySystem: true);
expect(rig.engine.restored, hasLength(1));
expect(rig.engine.phase, RunPhase.recording);
expect(rig.port.stops, 0);
});
test(
'an app start with a checkpoint resumes it too (force-stop)',
() async {
final rig = HostRig();
rig.store.held = FakeCheckpoint(1);
await handlerFor(rig).onStart(startedBySystem: false);
expect(rig.engine.phase, RunPhase.recording);
},
);
test('a system start with no checkpoint stops itself', () async {
final rig = HostRig();
await handlerFor(rig).onStart(startedBySystem: true);
expect(rig.port.stops, 1);
expect(rig.engines, isEmpty);
});
test(
'an app start with no checkpoint waits for the start command',
() async {
final rig = HostRig();
await handlerFor(rig).onStart(startedBySystem: false);
expect(rig.port.stops, 0);
expect(rig.engines, isEmpty);
},
);
});
group('messages', () {
test('run commands reach the host', () async {
final rig = HostRig();
final handler = handlerFor(rig)..onReceiveData({'cmd': RunCmd.start});
await pumpEventQueue();
expect(rig.engine.phase, RunPhase.recording);
handler.onReceiveData({'cmd': RunCmd.pause});
await pumpEventQueue();
expect(rig.engine.phase, RunPhase.paused);
});
test('a break-service message is ignored', () async {
final rig = HostRig();
handlerFor(rig)
..onReceiveData({'workoutType': 'A', 'restEndsAtMs': 5})
..onReceiveData('nudge');
await pumpEventQueue();
expect(rig.engines, isEmpty);
expect(rig.port.sent, isEmpty);
});
});
test('a notification tap goes to the host', () async {
final rig = HostRig();
handlerFor(rig).onNotificationPressed();
expect(rig.port.launches, 1);
});
test('destroy lets go and never ends the run', () async {
final rig = HostRig();
final handler = handlerFor(rig)..onReceiveData({'cmd': RunCmd.start});
await pumpEventQueue();
handler.onDestroy();
expect(rig.engine.disposed, isTrue);
expect(rig.saved, isEmpty);
expect(rig.store.clears, 0);
});
}

View File

@ -0,0 +1,176 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_phase.dart';
import 'package:workout_app/services/run_view.dart';
import 'package:workout_app/services/run_wire.dart';
import '../fake_run_engine.dart';
Map<String, Object?> snapshot(
FakeRunEngine engine, {
int from = 0,
String? suggestion,
bool prompt = false,
bool done = false,
({bool stored, String reason})? saved,
}) => encodeSnapshot(
engine,
from: from,
suggestion: suggestion,
prompt: prompt,
done: done,
saved: saved,
);
void main() {
test('a snapshot fills every field', () {
final engine = FakeRunEngine()
..paceTarget = 330
..setPhase(RunPhase.recording)
..addFix()
..addFix();
final view = RunView()
..apply(
snapshot(
engine,
suggestion: 'gpsLost',
prompt: true,
done: true,
saved: (stored: true, reason: 'ok'),
),
);
expect(view.phase, RunPhase.recording);
expect(view.seconds, 4);
expect(view.distanceM, 12);
expect(view.paceTarget, 330);
expect(view.pace, isNull);
expect(view.band, isNull);
expect(view.suggestion, 'gpsLost');
expect(view.promptFinish, isTrue);
expect(view.done, isTrue);
expect(view.saved, (stored: true, reason: 'ok'));
expect(view.synced, isTrue);
expect(view.livePoints.value, hasLength(2));
view.dispose();
});
test('a band name decodes', () {
final view = RunView();
final message = snapshot(FakeRunEngine())..['band'] = PaceBand.onPace.name;
view.apply(message);
expect(view.band, PaceBand.onPace);
view.dispose();
});
group('points', () {
test('an increment appends', () {
final engine = FakeRunEngine()
..setPhase(RunPhase.recording)
..addFix();
final view = RunView()..apply(snapshot(engine));
engine.addFix();
view.apply(snapshot(engine, from: 1));
expect(view.livePoints.value, hasLength(2));
view.dispose();
});
test('a gap asks for everything again', () {
final engine = FakeRunEngine()..setPhase(RunPhase.recording);
var asked = 0;
final view = RunView()
..onNeedSync = () {
asked++;
}
..apply(snapshot(engine));
engine
..addFix()
..addFix()
..addFix();
view.apply(snapshot(engine, from: 2));
expect(asked, 1);
expect(view.livePoints.value, isEmpty);
view.apply(snapshot(engine));
expect(view.livePoints.value, hasLength(3));
expect(asked, 1);
view.dispose();
});
test('a count that does not add up asks again', () {
final engine = FakeRunEngine()
..setPhase(RunPhase.recording)
..addFix();
var asked = 0;
final view = RunView()
..onNeedSync = () {
asked++;
};
final message = snapshot(engine)..['total'] = 5;
view.apply(message);
expect(asked, 1);
view.dispose();
});
test('a new run replaces the old points', () {
final engine = FakeRunEngine()
..setPhase(RunPhase.recording)
..addFix()
..addFix();
final view = RunView()..apply(snapshot(engine));
final fresh = FakeRunEngine()..setPhase(RunPhase.recording);
view.apply(snapshot(fresh));
expect(view.livePoints.value, isEmpty);
view.dispose();
});
});
group('access', () {
test('a refusal becomes the issue while idle', () {
final view = RunView()..noteAccess(LocationAccess.deniedForever);
expect(view.issue, RunIssue.deniedForever);
view.noteAccess(LocationAccess.granted);
expect(view.issue, RunIssue.none);
view.noteAccess(LocationAccess.granted);
expect(view.issue, RunIssue.none);
view.dispose();
});
test('an idle host answer does not wipe the UI refusal', () {
final view = RunView()..noteAccess(LocationAccess.denied);
view.apply(snapshot(FakeRunEngine()));
expect(view.issue, RunIssue.denied);
view.dispose();
});
test('a run is never touched by an access check', () {
final engine = FakeRunEngine()..setPhase(RunPhase.recording);
final view = RunView()
..apply(snapshot(engine))
..noteAccess(LocationAccess.denied);
expect(view.issue, RunIssue.none);
view.dispose();
});
test('a host issue while idle shows', () {
final engine = FakeRunEngine()
..setPhase(RunPhase.idle, issue: RunIssue.denied);
final view = RunView()..apply(snapshot(engine));
expect(view.issue, RunIssue.denied);
view.dispose();
});
});
test('wire points round-trip with and without altitude', () {
final engine = FakeRunEngine()..addFix();
final point = engine.points.single;
expect(decodePoint(encodePoint(point)), point);
final withAltitude = decodePoint([0, 1.5, 2.5, 3, 40.0]);
expect(withAltitude.altitudeM, 40);
expect(isRunMessage({'cmd': 'x'}), isFalse);
expect(isRunMessage('x'), isFalse);
});
}

View File

@ -0,0 +1,224 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/run_recorder.dart';
import 'package:workout_app/services/run_watchdog.dart';
import '../run_test_fixtures.dart';
import '../run_watchdog_rig.dart';
void main() {
group('stationary (under 50 m in 10 min)', () {
test('fires after 10 idle minutes and then every 10, with no limit', () {
final r = WatchdogRig()..dog.begin(watchdogStart);
r.idle(30);
expect(r.suggestions, List.filled(3, RunSuggestion.stationary));
});
test('does not fire before 10 minutes', () {
final r = WatchdogRig()..dog.begin(watchdogStart);
r.idle(9);
expect(r.suggestions, isEmpty);
});
test('50 m of progress in the window stays quiet and re-arms', () {
final r = WatchdogRig()..dog.begin(watchdogStart);
r.idle(4);
r.fix(stepM: 50);
r.idle(6);
expect(r.suggestions, isEmpty);
// The next window starts at 10:00 with 50 m banked: 49 m is too few.
r.fix(stepM: 49);
r.idle(10);
expect(r.suggestions, [RunSuggestion.stationary]);
});
test('nothing fires while paused, and resume restarts the window', () {
final r = WatchdogRig()..dog.begin(watchdogStart);
r.idle(8);
r.dog.pause();
r.advance(const Duration(minutes: 30));
expect(r.suggestions, isEmpty);
r.dog.resume();
r.idle(9);
expect(r.suggestions, isEmpty);
r.idle(1);
expect(r.suggestions, [RunSuggestion.stationary]);
});
});
group('no GPS fix for 5 min', () {
test('fires once per loss, not before 5 minutes', () {
final r = WatchdogRig()..dog.begin(watchdogStart);
r.advance(const Duration(minutes: 4, seconds: 59));
expect(r.suggestions, isEmpty);
r.advance(const Duration(seconds: 1));
expect(r.suggestions, [RunSuggestion.gpsLost]);
r.advance(const Duration(minutes: 2));
expect(r.suggestions, [RunSuggestion.gpsLost]);
});
test('a fix re-arms it', () {
final r = WatchdogRig()..dog.begin(watchdogStart);
r.advance(const Duration(minutes: 5));
r.fix();
r.advance(const Duration(minutes: 5));
expect(
r.suggestions.where((s) => s == RunSuggestion.gpsLost),
hasLength(2),
);
});
test('fixes the filter rejects as too inaccurate do not count', () {
final r = WatchdogRig()..dog.begin(watchdogStart);
r.advance(const Duration(minutes: 4));
r.dog.onFix(fixAt(0, 0), FixVerdict.inaccurate, 0);
r.dog.onFix(fixAt(2, 0), FixVerdict.mocked, 0);
r.advance(const Duration(minutes: 1));
expect(r.suggestions, contains(RunSuggestion.gpsLost));
});
test('nothing fires while paused', () {
final r = WatchdogRig()..dog.begin(watchdogStart);
r.dog.pause();
r.advance(const Duration(minutes: 20));
expect(r.suggestions, isEmpty);
});
});
group('vehicle speed (over 25 km/h for 60 s)', () {
// 10 m/s is 36 km/h. Rejected jump fixes still count: a car never
// produces an accepted fix, the filter drops it as too fast.
void drive(WatchdogRig r, {required int seconds, required double mps}) {
for (var s = 0; s <= seconds; s += 2) {
r.dog.onFix(fixAt(s, s * mps), FixVerdict.tooFast, r.metres);
}
}
test('fires once after 60 s of it', () {
final r = WatchdogRig()..dog.begin(watchdogStart);
drive(r, seconds: 120, mps: 10);
expect(r.suggestions, [RunSuggestion.vehicleSpeed]);
});
test('59 s is not sustained', () {
final r = WatchdogRig()..dog.begin(watchdogStart);
drive(r, seconds: 58, mps: 10);
expect(r.suggestions, isEmpty);
});
test('slowing down resets it', () {
final r = WatchdogRig()..dog.begin(watchdogStart);
drive(r, seconds: 50, mps: 10);
r.dog.onFix(fixAt(52, 500), FixVerdict.accepted, 0); // standing
for (var s = 54; s <= 100; s += 2) {
r.dog.onFix(fixAt(s, 500 + (s - 52) * 10.0), FixVerdict.tooFast, 0);
}
expect(r.suggestions, isEmpty);
});
test('running speed never fires it', () {
final r = WatchdogRig()..dog.begin(watchdogStart);
drive(r, seconds: 300, mps: 3);
expect(r.suggestions, isEmpty);
});
test('a second ride after slowing fires again', () {
final r = WatchdogRig()..dog.begin(watchdogStart);
drive(r, seconds: 70, mps: 10);
r.dog.onFix(fixAt(72, 700), FixVerdict.accepted, 0);
for (var s = 74; s <= 200; s += 2) {
r.dog.onFix(fixAt(s, 700 + (s - 72) * 10.0), FixVerdict.tooFast, 0);
}
expect(r.suggestions, [
RunSuggestion.vehicleSpeed,
RunSuggestion.vehicleSpeed,
]);
});
test('same-second fixes and mocked fixes are ignored', () {
final r = WatchdogRig()..dog.begin(watchdogStart);
r.dog.onFix(fixAt(0, 0), FixVerdict.accepted, 0);
r.dog.onFix(fixAt(0, 500), FixVerdict.tooFast, 0);
r.dog.onFix(fixAt(2, 900), FixVerdict.mocked, 0);
expect(r.suggestions, isEmpty);
});
});
group('auto end after 5 h of wall clock', () {
test('fires once at 5 h, pauses and gaps included', () {
final r = WatchdogRig()..dog.begin(watchdogStart);
r.dog.pause();
r.advance(const Duration(hours: 4, minutes: 59));
expect(r.autoEnds, 0);
r.advance(const Duration(minutes: 1));
expect(r.autoEnds, 1);
r.advance(const Duration(hours: 1));
expect(r.autoEnds, 1);
});
test('a shortened limit is honoured', () {
final r = WatchdogRig(autoEnd: const Duration(minutes: 3))
..dog.begin(watchdogStart);
r.advance(const Duration(minutes: 3));
expect(r.autoEnds, 1);
});
test('restored past the limit ends at once, with no restore hint', () {
final r = WatchdogRig();
r.now = watchdogStart.add(const Duration(hours: 6));
r.dog.restored(watchdogStart, paused: false, distanceM: 0);
expect(r.autoEnds, 1);
expect(r.suggestions, isEmpty);
});
test('restored inside the limit suggests finishing', () {
final r = WatchdogRig();
r.now = watchdogStart.add(const Duration(hours: 1));
r.dog.restored(watchdogStart, paused: false, distanceM: 2000);
expect(r.autoEnds, 0);
expect(r.suggestions, [RunSuggestion.restored]);
});
test('restored while paused stays paused: only the restore hint', () {
final r = WatchdogRig();
r.now = watchdogStart.add(const Duration(minutes: 30));
r.dog.restored(watchdogStart, paused: true, distanceM: 0);
r.advance(const Duration(hours: 1));
expect(r.suggestions, [RunSuggestion.restored]);
});
test('stop() silences everything and is safe twice', () {
final r = WatchdogRig()..dog.begin(watchdogStart);
r.dog.stop();
r.dog.stop();
r.advance(const Duration(hours: 6));
expect(r.suggestions, isEmpty);
expect(r.autoEnds, 0);
});
test('fix and pause calls before begin are harmless', () {
final r = WatchdogRig();
r.dog.pause();
r.dog.resume();
r.fix();
r.dog.check();
expect(r.suggestions, isEmpty);
});
});
testWidgets('the timer, not a fix, drives the checks', (tester) async {
var now = watchdogStart;
final suggestions = <RunSuggestion>[];
final dog = RunWatchdog(
clock: () => now,
onSuggest: suggestions.add,
onAutoEnd: () {},
)..begin(watchdogStart);
for (var i = 0; i < 61; i++) {
now = now.add(const Duration(seconds: 5));
await tester.pump(const Duration(seconds: 5));
}
expect(suggestions, contains(RunSuggestion.gpsLost));
dog.stop();
});
}

View File

@ -25,7 +25,7 @@
"@eslint/js": "10.0.1",
"@testing-library/dom": "10.4.2",
"@testing-library/jest-dom": "7.0.1",
"@testing-library/user-event": "14.6.10",
"@testing-library/user-event": "14.6.12",
"@types/node": "26.6.6",
"@vitest/coverage-v8": "5.1.0",
"eslint": "10.15.0",
@ -33,7 +33,7 @@
"globals": "17.14.0",
"jsdom": "31.0.1",
"typescript": "6.0.3",
"typescript-eslint": "8.72.2",
"typescript-eslint": "8.73.0",
"vitest": "5.1.0"
}
}

View File

@ -201,8 +201,8 @@ importers:
specifier: 7.0.1
version: 7.0.1(@testing-library/dom@10.4.2)(vitest@5.1.0)
'@testing-library/user-event':
specifier: 14.6.10
version: 14.6.10(@testing-library/dom@10.4.2)
specifier: 14.6.12
version: 14.6.12(@testing-library/dom@10.4.2)
'@types/node':
specifier: 26.6.6
version: 26.6.6
@ -214,7 +214,7 @@ importers:
version: 10.15.0
eslint-plugin-astro:
specifier: 3.2.1
version: 3.2.1(@typescript-eslint/parser@8.72.2(eslint@10.15.0)(typescript@6.0.3))(eslint@10.15.0)(typescript-eslint@8.72.2(eslint@10.15.0)(typescript@6.0.3))
version: 3.2.1(@typescript-eslint/parser@8.73.0(eslint@10.15.0)(typescript@6.0.3))(eslint@10.15.0)(typescript-eslint@8.73.0(eslint@10.15.0)(typescript@6.0.3))
globals:
specifier: 17.14.0
version: 17.14.0
@ -225,8 +225,8 @@ importers:
specifier: 6.0.3
version: 6.0.3
typescript-eslint:
specifier: 8.72.2
version: 8.72.2(eslint@10.15.0)(typescript@6.0.3)
specifier: 8.73.0
version: 8.73.0(eslint@10.15.0)(typescript@6.0.3)
vitest:
specifier: 5.1.0
version: 5.1.0(@types/node@26.6.6)(@vitest/coverage-v8@5.1.0)(jsdom@31.0.1)(vite@8.3.7(@types/node@26.6.6)(yaml@2.9.1))
@ -926,8 +926,8 @@ packages:
vitest:
optional: true
'@testing-library/user-event@14.6.10':
resolution: {integrity: sha512-tA4stGNp3mLGOGO+lh87UA56Tz4c8NVGBSkyIF58O+W/bs2Re9BCI9xihnL70+DsThncFznE0skS88SM1D2hyg==}
'@testing-library/user-event@14.6.12':
resolution: {integrity: sha512-8yQV8v+eToBhsUO4oYrZY7fzhpTEMZx4IDx0/iuER/x0Xuy0NdqQOhsaaUNlvXE03N7vQ+4RCXUieKC0NJty9w==}
engines: {node: '>=12', npm: '>=6'}
peerDependencies:
'@testing-library/dom': '>=7.21.4'
@ -971,23 +971,23 @@ packages:
'@types/unist@3.0.3':
resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}
'@typescript-eslint/eslint-plugin@8.72.2':
resolution: {integrity: sha512-222PKFXKihmFpi/pS5njoBgdAqsPhj2/GBmFbrNw8Tq8gEG9Sv+kSlKFy4u2q+mJv9ZzJgM2Gkv/bUzRZwZw5g==}
'@typescript-eslint/eslint-plugin@8.73.0':
resolution: {integrity: sha512-UkygMFer53Yzn29MCYFTHf34hGXf5KJhiDWfIm1tXtXRrym1CS6l5H9Y3yCtPWChpC0/f93H88gdj8tN0dd4kw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
'@typescript-eslint/parser': ^8.72.2
'@typescript-eslint/parser': ^8.73.0
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
typescript: '>=4.8.4 <6.1.0'
'@typescript-eslint/parser@8.72.2':
resolution: {integrity: sha512-llP+T1YuJOLlxEciP6OyQGtz5SMxyn+9LA2BvZw5RmToGVa1y4beEDVQL6Gje7T5WFYh19WREjDCN9Ev4gm5AA==}
'@typescript-eslint/parser@8.73.0':
resolution: {integrity: sha512-AuL45bVcmssHfZ3Di3cs9Q0l4gBm4ZFVrJOQEE7VpqW+PVgQaEwSwazz4TVIiFabXkk6U51EprYDwqw+HR8ePw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
typescript: '>=4.8.4 <6.1.0'
'@typescript-eslint/project-service@8.72.2':
resolution: {integrity: sha512-6y5dLTZdHhI8Eh3yIQ/bfQhRKwn5e+TpJj64o18Cngc0iW/BCrVvrr6zGYqXPnYH31u6YXAYiFh0+qxX5mybJw==}
'@typescript-eslint/project-service@8.73.0':
resolution: {integrity: sha512-/pEf8Rc4Mjk+qJnY0uO1+Gadeal8uv50xpuic+srG2vIVatA0XxvWMUeMtFvs6OCHqftiQ7/+qH4aehG5stzIA==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
typescript: '>=4.8.4 <6.1.0'
@ -996,18 +996,18 @@ packages:
resolution: {integrity: sha512-lC/t6eMCZZQAAKZEYGL6RDVSuFehpdmMT6h+nJIjIa6oylN/PwDgDVtEIbB7O9xFfZYtZAYLoLlDNWKJhtF+uQ==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
'@typescript-eslint/scope-manager@8.72.2':
resolution: {integrity: sha512-iIoMJ6/8c1/QpFNyFjU0d1YzPco4MsZjQw0k3V+vfzNWAFmUmvhlyMoYEoYYDQZXc+J6Gi1X5XcxlzW2taIIGQ==}
'@typescript-eslint/scope-manager@8.73.0':
resolution: {integrity: sha512-/TjD738Iq2rzj5z0ixVOi+TsvgjAzZPLPaH1yWdDBytR/HTR5gMpyYWZeCe5WTQZLwk3ho8AV7U3muoQCRtXBQ==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
'@typescript-eslint/tsconfig-utils@8.72.2':
resolution: {integrity: sha512-+h3iCgZXuTNtoLXcnnjP12ZUHLMqoUcIHPfQrFEXTUqvb9dF8QK9b5nv5VtSo5fLkdHuks8ehbTzZj3rImAm9w==}
'@typescript-eslint/tsconfig-utils@8.73.0':
resolution: {integrity: sha512-lmtCFOfYaJfpqZywGuXi4FpNtE+NQ+YLe3T0K9rtEDcW8ZuGWvfI++pj8r05sYMI8vWT2CYK4rWyedmD6Rp4og==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
typescript: '>=4.8.4 <6.1.0'
'@typescript-eslint/type-utils@8.72.2':
resolution: {integrity: sha512-STfkR38qIdhfkLpgtXnUjAzsNy4xouqiBO0lrVc/Wpk9Kem5/aHXUx1J8dGC16zpdYN1+yc2ILQ28er1kXX7ag==}
'@typescript-eslint/type-utils@8.73.0':
resolution: {integrity: sha512-MOC9i4xy1F7KcDde7Ip8jf1SrRiALb2Km4UWxGNjUE2YlhjIEo1ayE27GHIwIQyfWuHTmEonQT14uyurlyC6aA==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
@ -1017,18 +1017,22 @@ packages:
resolution: {integrity: sha512-LmE5IhQet1BWOWEXqBrVtBPsMAOQ6Nzk35d+WLh3mk4EUF33sqlfxjio1MdYeSvKSG5skactKKuixBIKXhL4Rw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
'@typescript-eslint/types@8.72.2':
resolution: {integrity: sha512-Xfn37OLZx03+PCU7qWx9DTv2FCRh1E6fk2+wONeNY15HXIwtcwuveaSwVpGAUptkNmPQegRxW5JyRel9T7wrog==}
'@typescript-eslint/types@8.73.0':
resolution: {integrity: sha512-O/1ytYzflF16QDKXx4/qOXg1IuZp+n7hr9t+S0nv7N/2Tl8rJiNCshztV1gcSUvHbPtoX3+zmNbtSAyVbzxVfw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
'@typescript-eslint/typescript-estree@8.72.2':
resolution: {integrity: sha512-pQEGqIK/cqEvKivVWaFLYpe7XYejFxfuAOi4mu1oAWFvIo36aRHI9esRFTUxcIy/z8N482RJyH+LpZB0ZIU7Ow==}
'@typescript-eslint/typescript-estree@8.73.0':
resolution: {integrity: sha512-InjlBkSdWceIwIBWSwS3ENUp+i0O02PGX3Zv2wnihWJC1WDVGvG7mTHuf8b57uAaITj94d6tRPDH+sUEtXdRQQ==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
'@typescript/native': npm:typescript@>=7.1.0-dev.20261009.1 || >=7.1.0-beta <7.1.0-dev
typescript: '>=4.8.4 <6.1.0'
peerDependenciesMeta:
'@typescript/native':
optional: true
'@typescript-eslint/utils@8.72.2':
resolution: {integrity: sha512-hv3eRYbpPbbpezuax1EfGrzpa3C4ySgNZkPUkLOWOAjU8HsOKowEDAr8C7nsNl1C+SBSKDpvno6VKHnlhvp9iA==}
'@typescript-eslint/utils@8.73.0':
resolution: {integrity: sha512-j2SVJJvVkXdUL0WcEzo4vEH1mO1vIi8KlVukcYA2MgMZvYN2LlZR4PmsW+GTSxSW24j6Q/EP7+MOifLtg5hmsA==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
@ -1038,8 +1042,8 @@ packages:
resolution: {integrity: sha512-SB8xqipSzZHUePCCLNeYxqnxq83X61/qzNhjQGbTfjxGZIeOEP7tBgWYX05Tcd6CgE02WdTJnh5b8kMZJ/+bnQ==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
'@typescript-eslint/visitor-keys@8.72.2':
resolution: {integrity: sha512-NAGrjn0Pitjqzq/GkgMC4kBYm233PQ8GffyQ9+kTA3AlNQYEzOf25EIM02BAHZv5FRJSpHpJk+OGUxVkOB93GQ==}
'@typescript-eslint/visitor-keys@8.73.0':
resolution: {integrity: sha512-k4lsFVpRZICbltkIEEH4hZRkwXkqDF1GHBpClKQOHQY+RkoZAAuyc1ci3I6p+CB6v3U4jaHIUshc4RzzQXZWLg==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
'@ungap/structured-clone@1.4.0':
@ -1804,10 +1808,6 @@ packages:
resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==}
engines: {node: '>=4'}
minimatch@10.2.6:
resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==}
engines: {node: 18 || 20 || >=22}
minimatch@11.0.8:
resolution: {integrity: sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==}
engines: {node: 20 || >=22}
@ -2157,8 +2157,8 @@ packages:
typescript-auto-import-cache@0.3.6:
resolution: {integrity: sha512-RpuHXrknHdVdK7wv/8ug3Fr0WNsNi5l5aB8MYYuXhq2UH5lnEB1htJ1smhtD5VeCsGr2p8mUDtd83LCQDFVgjQ==}
typescript-eslint@8.72.2:
resolution: {integrity: sha512-c/+AKMW1KB81r28Sp0AAdcyXj5dzNmAsZFcsrxKbZTKmcBK2xIwBR31dcSYSDu3bKmzXe8GKrSxO+eDQ401Uzg==}
typescript-eslint@8.73.0:
resolution: {integrity: sha512-+EnKy9rkYPun4l+kG2bDuYWQ6y1tGVgdR/tY1U9AC6h21CjEwOoc7gsjwe0FXB8uWFzk4QiCFbuRWgX758PiAg==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
@ -3176,7 +3176,7 @@ snapshots:
optionalDependencies:
vitest: 5.1.0(@types/node@26.6.6)(@vitest/coverage-v8@5.1.0)(jsdom@31.0.1)(vite@8.3.7(@types/node@26.6.6)(yaml@2.9.1))
'@testing-library/user-event@14.6.10(@testing-library/dom@10.4.2)':
'@testing-library/user-event@14.6.12(@testing-library/dom@10.4.2)':
dependencies:
'@testing-library/dom': 10.4.2
@ -3221,38 +3221,40 @@ snapshots:
'@types/unist@3.0.3': {}
'@typescript-eslint/eslint-plugin@8.72.2(@typescript-eslint/parser@8.72.2(eslint@10.15.0)(typescript@6.0.3))(eslint@10.15.0)(typescript@6.0.3)':
'@typescript-eslint/eslint-plugin@8.73.0(@typescript-eslint/parser@8.73.0(eslint@10.15.0)(typescript@6.0.3))(eslint@10.15.0)(typescript@6.0.3)':
dependencies:
'@eslint-community/regexpp': 4.12.2
'@typescript-eslint/parser': 8.72.2(eslint@10.15.0)(typescript@6.0.3)
'@typescript-eslint/scope-manager': 8.72.2
'@typescript-eslint/type-utils': 8.72.2(eslint@10.15.0)(typescript@6.0.3)
'@typescript-eslint/utils': 8.72.2(eslint@10.15.0)(typescript@6.0.3)
'@typescript-eslint/visitor-keys': 8.72.2
'@typescript-eslint/parser': 8.73.0(eslint@10.15.0)(typescript@6.0.3)
'@typescript-eslint/scope-manager': 8.73.0
'@typescript-eslint/type-utils': 8.73.0(eslint@10.15.0)(typescript@6.0.3)
'@typescript-eslint/utils': 8.73.0(eslint@10.15.0)(typescript@6.0.3)
'@typescript-eslint/visitor-keys': 8.73.0
eslint: 10.15.0
ignore: 7.0.12
natural-compare: 1.4.0
ts-api-utils: 2.5.0(typescript@6.0.3)
typescript: 6.0.3
transitivePeerDependencies:
- '@typescript/native'
- supports-color
'@typescript-eslint/parser@8.72.2(eslint@10.15.0)(typescript@6.0.3)':
'@typescript-eslint/parser@8.73.0(eslint@10.15.0)(typescript@6.0.3)':
dependencies:
'@typescript-eslint/scope-manager': 8.72.2
'@typescript-eslint/types': 8.72.2
'@typescript-eslint/typescript-estree': 8.72.2(typescript@6.0.3)
'@typescript-eslint/visitor-keys': 8.72.2
'@typescript-eslint/scope-manager': 8.73.0
'@typescript-eslint/types': 8.73.0
'@typescript-eslint/typescript-estree': 8.73.0(typescript@6.0.3)
'@typescript-eslint/visitor-keys': 8.73.0
debug: 4.4.3
eslint: 10.15.0
typescript: 6.0.3
transitivePeerDependencies:
- '@typescript/native'
- supports-color
'@typescript-eslint/project-service@8.72.2(typescript@6.0.3)':
'@typescript-eslint/project-service@8.73.0(typescript@6.0.3)':
dependencies:
'@typescript-eslint/tsconfig-utils': 8.72.2(typescript@6.0.3)
'@typescript-eslint/types': 8.72.2
'@typescript-eslint/tsconfig-utils': 8.73.0(typescript@6.0.3)
'@typescript-eslint/types': 8.73.0
debug: 4.4.3
typescript: 6.0.3
transitivePeerDependencies:
@ -3263,39 +3265,40 @@ snapshots:
'@typescript-eslint/types': 8.72.1
'@typescript-eslint/visitor-keys': 8.72.1
'@typescript-eslint/scope-manager@8.72.2':
'@typescript-eslint/scope-manager@8.73.0':
dependencies:
'@typescript-eslint/types': 8.72.2
'@typescript-eslint/visitor-keys': 8.72.2
'@typescript-eslint/types': 8.73.0
'@typescript-eslint/visitor-keys': 8.73.0
'@typescript-eslint/tsconfig-utils@8.72.2(typescript@6.0.3)':
'@typescript-eslint/tsconfig-utils@8.73.0(typescript@6.0.3)':
dependencies:
typescript: 6.0.3
'@typescript-eslint/type-utils@8.72.2(eslint@10.15.0)(typescript@6.0.3)':
'@typescript-eslint/type-utils@8.73.0(eslint@10.15.0)(typescript@6.0.3)':
dependencies:
'@typescript-eslint/types': 8.72.2
'@typescript-eslint/typescript-estree': 8.72.2(typescript@6.0.3)
'@typescript-eslint/utils': 8.72.2(eslint@10.15.0)(typescript@6.0.3)
'@typescript-eslint/types': 8.73.0
'@typescript-eslint/typescript-estree': 8.73.0(typescript@6.0.3)
'@typescript-eslint/utils': 8.73.0(eslint@10.15.0)(typescript@6.0.3)
debug: 4.4.3
eslint: 10.15.0
ts-api-utils: 2.5.0(typescript@6.0.3)
typescript: 6.0.3
transitivePeerDependencies:
- '@typescript/native'
- supports-color
'@typescript-eslint/types@8.72.1': {}
'@typescript-eslint/types@8.72.2': {}
'@typescript-eslint/types@8.73.0': {}
'@typescript-eslint/typescript-estree@8.72.2(typescript@6.0.3)':
'@typescript-eslint/typescript-estree@8.73.0(typescript@6.0.3)':
dependencies:
'@typescript-eslint/project-service': 8.72.2(typescript@6.0.3)
'@typescript-eslint/tsconfig-utils': 8.72.2(typescript@6.0.3)
'@typescript-eslint/types': 8.72.2
'@typescript-eslint/visitor-keys': 8.72.2
'@typescript-eslint/project-service': 8.73.0(typescript@6.0.3)
'@typescript-eslint/tsconfig-utils': 8.73.0(typescript@6.0.3)
'@typescript-eslint/types': 8.73.0
'@typescript-eslint/visitor-keys': 8.73.0
debug: 4.4.3
minimatch: 10.2.6
minimatch: 11.0.8
semver: 7.8.5
tinyglobby: 0.2.17
ts-api-utils: 2.5.0(typescript@6.0.3)
@ -3303,15 +3306,16 @@ snapshots:
transitivePeerDependencies:
- supports-color
'@typescript-eslint/utils@8.72.2(eslint@10.15.0)(typescript@6.0.3)':
'@typescript-eslint/utils@8.73.0(eslint@10.15.0)(typescript@6.0.3)':
dependencies:
'@eslint-community/eslint-utils': 4.10.1(eslint@10.15.0)
'@typescript-eslint/scope-manager': 8.72.2
'@typescript-eslint/types': 8.72.2
'@typescript-eslint/typescript-estree': 8.72.2(typescript@6.0.3)
'@typescript-eslint/scope-manager': 8.73.0
'@typescript-eslint/types': 8.73.0
'@typescript-eslint/typescript-estree': 8.73.0(typescript@6.0.3)
eslint: 10.15.0
typescript: 6.0.3
transitivePeerDependencies:
- '@typescript/native'
- supports-color
'@typescript-eslint/visitor-keys@8.72.1':
@ -3319,9 +3323,9 @@ snapshots:
'@typescript-eslint/types': 8.72.1
eslint-visitor-keys: 5.0.1
'@typescript-eslint/visitor-keys@8.72.2':
'@typescript-eslint/visitor-keys@8.73.0':
dependencies:
'@typescript-eslint/types': 8.72.2
'@typescript-eslint/types': 8.73.0
eslint-visitor-keys: 5.0.1
'@ungap/structured-clone@1.4.0': {}
@ -3746,7 +3750,7 @@ snapshots:
escape-string-regexp@4.0.0: {}
eslint-plugin-astro@3.2.1(@typescript-eslint/parser@8.72.2(eslint@10.15.0)(typescript@6.0.3))(eslint@10.15.0)(typescript-eslint@8.72.2(eslint@10.15.0)(typescript@6.0.3)):
eslint-plugin-astro@3.2.1(@typescript-eslint/parser@8.73.0(eslint@10.15.0)(typescript@6.0.3))(eslint@10.15.0)(typescript-eslint@8.73.0(eslint@10.15.0)(typescript@6.0.3)):
dependencies:
'@eslint-community/eslint-utils': 4.10.1(eslint@10.15.0)
'@jridgewell/sourcemap-codec': 1.6.0
@ -3759,8 +3763,8 @@ snapshots:
postcss-selector-parser: 7.1.7
synckit: 0.11.13
optionalDependencies:
'@typescript-eslint/parser': 8.72.2(eslint@10.15.0)(typescript@6.0.3)
typescript-eslint: 8.72.2(eslint@10.15.0)(typescript@6.0.3)
'@typescript-eslint/parser': 8.73.0(eslint@10.15.0)(typescript@6.0.3)
typescript-eslint: 8.73.0(eslint@10.15.0)(typescript@6.0.3)
transitivePeerDependencies:
- supports-color
@ -4143,10 +4147,6 @@ snapshots:
min-indent@1.0.1: {}
minimatch@10.2.6:
dependencies:
brace-expansion: 5.0.12
minimatch@11.0.8:
dependencies:
'@isaacs/nonrecursive-glob-match': 1.1.0
@ -4515,15 +4515,16 @@ snapshots:
dependencies:
semver: 7.8.5
typescript-eslint@8.72.2(eslint@10.15.0)(typescript@6.0.3):
typescript-eslint@8.73.0(eslint@10.15.0)(typescript@6.0.3):
dependencies:
'@typescript-eslint/eslint-plugin': 8.72.2(@typescript-eslint/parser@8.72.2(eslint@10.15.0)(typescript@6.0.3))(eslint@10.15.0)(typescript@6.0.3)
'@typescript-eslint/parser': 8.72.2(eslint@10.15.0)(typescript@6.0.3)
'@typescript-eslint/typescript-estree': 8.72.2(typescript@6.0.3)
'@typescript-eslint/utils': 8.72.2(eslint@10.15.0)(typescript@6.0.3)
'@typescript-eslint/eslint-plugin': 8.73.0(@typescript-eslint/parser@8.73.0(eslint@10.15.0)(typescript@6.0.3))(eslint@10.15.0)(typescript@6.0.3)
'@typescript-eslint/parser': 8.73.0(eslint@10.15.0)(typescript@6.0.3)
'@typescript-eslint/typescript-estree': 8.73.0(typescript@6.0.3)
'@typescript-eslint/utils': 8.73.0(eslint@10.15.0)(typescript@6.0.3)
eslint: 10.15.0
typescript: 6.0.3
transitivePeerDependencies:
- '@typescript/native'
- supports-color
typescript@6.0.3: {}