From 0175cbede4543c2d9140696a99265fc84832bd39 Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Tue, 17 Nov 2026 21:28:45 +0100 Subject: [PATCH] Persist runs: tests, trims, adapter coverage Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WzxdWW75Epgijvt2eJ1ErR --- .../lib/screens/run_screen_numbers.dart | 5 +- .../lib/services/run_controller.dart | 49 +++------- .../workout_app/lib/services/run_host.dart | 13 +-- .../workout_app/lib/services/run_view.dart | 21 ++++ .../workout_app/test/run_persist_rig.dart | 5 +- .../test/screens/_run_screen_fixtures.dart | 1 - .../test/screens/run_screen_persist_test.dart | 37 ++++---- .../test/screens/run_screen_test.dart | 4 +- .../services/feedback_cues_long_test.dart | 36 +++++++ .../services/run_engine_recorder_test.dart | 95 +++++++++++++++++++ .../test/services/run_host_test.dart | 17 ++-- .../test/services/run_task_handler_test.dart | 33 ++++--- .../test/services/run_view_test.dart | 11 +-- 13 files changed, 227 insertions(+), 100 deletions(-) create mode 100644 stronglift_replacement/workout_app/test/services/feedback_cues_long_test.dart create mode 100644 stronglift_replacement/workout_app/test/services/run_engine_recorder_test.dart diff --git a/stronglift_replacement/workout_app/lib/screens/run_screen_numbers.dart b/stronglift_replacement/workout_app/lib/screens/run_screen_numbers.dart index 395dca6..0ba5801 100644 --- a/stronglift_replacement/workout_app/lib/screens/run_screen_numbers.dart +++ b/stronglift_replacement/workout_app/lib/screens/run_screen_numbers.dart @@ -67,10 +67,7 @@ class _Numbers extends StatelessWidget { small( Icons.speed, const Key('run_pace'), - formatPace( - seconds: view.seconds, - distanceM: view.distanceM, - ), + formatPace(seconds: view.seconds, distanceM: view.distanceM), ), if (view.paceTarget != null) small( diff --git a/stronglift_replacement/workout_app/lib/services/run_controller.dart b/stronglift_replacement/workout_app/lib/services/run_controller.dart index 2d3182c..d6e009e 100644 --- a/stronglift_replacement/workout_app/lib/services/run_controller.dart +++ b/stronglift_replacement/workout_app/lib/services/run_controller.dart @@ -21,8 +21,7 @@ import 'package:workout_app/services/run_saver.dart'; import 'package:workout_app/services/run_view.dart'; import 'package:workout_app/services/run_wire.dart'; -/// How long a command may wait for the host's answer before the screen stops -/// waiting (and says so in the log). +/// 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. @@ -49,10 +48,10 @@ class RunController extends ChangeNotifier { /// What the screen shows. final view = RunView(); - /// How long to wait for the host. + /// How long to wait for the host, and how often [attach] asks again. final Duration hostTimeout; - /// How often [attach] asks again while the host is silent. + /// See [hostTimeout]. final Duration retryEvery; late final IdleLocation _idle; @@ -63,12 +62,11 @@ class RunController extends ChangeNotifier { RunServiceState _serviceState = RunServiceState.none; bool _disposed = false; - bool _attachGaveUp = false; Timer? _pauseTimer; Completer? _pauseDone; /// The host never answered the screen's questions: nothing is there. - bool get attachGaveUp => _attachGaveUp; + bool attachGaveUp = false; /// Whether the foreground service is up (and with a notification). RunServiceState get serviceState => _serviceState; @@ -76,10 +74,7 @@ class RunController extends ChangeNotifier { /// What saving the finished run did, once it ran. RunSaveResult? get saved => view.saved == null ? null - : RunSaveResult( - stored: view.saved!.stored, - reason: view.saved!.reason, - ); + : RunSaveResult(stored: view.saved!.stored, reason: view.saved!.reason); /// True while the finished run is being written. bool get saving => @@ -114,7 +109,7 @@ class RunController extends ChangeNotifier { await _pause(i == 0 ? Duration.zero : retryEvery); } if (!view.synced && !_disposed) { - _attachGaveUp = true; + attachGaveUp = true; _serviceState = RunServiceState.none; } if (!_disposed) notifyListeners(); @@ -154,9 +149,7 @@ class RunController extends ChangeNotifier { /// confirm modal calls this. Future finish() async { _link.send({'cmd': RunCmd.finish}); - await _until( - () => view.phase == RunPhase.finished && view.done, - ); + await _until(() => view.phase == RunPhase.finished && view.done); if (view.phase == RunPhase.finished && !_disposed) { if (_serviceState.isUp) _serviceState = RunServiceState.none; notifyListeners(); @@ -182,26 +175,14 @@ class RunController extends ChangeNotifier { } Future _until(bool Function() done) async { - if (done()) return; - final completer = Completer(); - void check() { - if (done() && !completer.isCompleted) completer.complete(); - } - - view.addListener(check); - try { - await completer.future.timeout(hostTimeout); - } on TimeoutException { - 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, - ); - } finally { - view.removeListener(check); - } + 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 _startService() async { diff --git a/stronglift_replacement/workout_app/lib/services/run_host.dart b/stronglift_replacement/workout_app/lib/services/run_host.dart index 705455d..e751732 100644 --- a/stronglift_replacement/workout_app/lib/services/run_host.dart +++ b/stronglift_replacement/workout_app/lib/services/run_host.dart @@ -2,10 +2,9 @@ /// gives the cues and writes the finished run. /// /// In production this runs in the foreground-service isolate, so a swiped-away -/// app, a killed UI isolate or a dead process cannot end a run: only -/// [RunCmd.finish] (after the screen's confirm modal) or the 5 h limit does. -/// On Linux and in tests the same class runs in the UI isolate behind a -/// loopback link. +/// 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'; @@ -135,11 +134,10 @@ class RunHost { // A second "start" can never restart a live run: it only re-syncs. return _emit(full: true); } - // The idle engine a "hello" made is reused; anything else starts clean. + // Reuse the idle engine a "hello" made; anything else starts clean. final engine = current != null && current.phase == RunPhase.idle ? current : _fresh(); - // The controller already drew the first notification (zeros). final zero = runNotificationCopy(metres: 0, movingSeconds: 0); _lastCopy = '${zero.title}|${zero.body}'; cues.soundOn = message['sound'] as bool? ?? true; @@ -175,8 +173,7 @@ class RunHost { final title = why == null ? copy.title : '${suggestionGlyph(why)} ${copy.title}'; - // Only when the words changed: an update per fix redraws twice a second - // for nothing. + // 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)); diff --git a/stronglift_replacement/workout_app/lib/services/run_view.dart b/stronglift_replacement/workout_app/lib/services/run_view.dart index 1d714cd..1a81859 100644 --- a/stronglift_replacement/workout_app/lib/services/run_view.dart +++ b/stronglift_replacement/workout_app/lib/services/run_view.dart @@ -1,6 +1,8 @@ /// 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'; @@ -119,6 +121,25 @@ class RunView extends ChangeNotifier { if (livePoints.value.length != total) onNeedSync?.call(); } + /// Waits until [done] holds (checked on every snapshot); false on timeout. + Future waitUntil(bool Function() done, Duration timeout) async { + if (done()) return true; + final completer = Completer(); + void check() { + if (done() && !completer.isCompleted) completer.complete(); + } + + addListener(check); + try { + await completer.future.timeout(timeout); + return true; + } on TimeoutException { + return false; + } finally { + removeListener(check); + } + } + @override void dispose() { livePoints.dispose(); diff --git a/stronglift_replacement/workout_app/test/run_persist_rig.dart b/stronglift_replacement/workout_app/test/run_persist_rig.dart index 524c80f..5b3815d 100644 --- a/stronglift_replacement/workout_app/test/run_persist_rig.dart +++ b/stronglift_replacement/workout_app/test/run_persist_rig.dart @@ -101,9 +101,8 @@ class _RigLink implements RunHostLink { Stream> get messages => _rig.port.messages; @override - void send(Map command) => unawaited( - _rig.host.host.handle(command), - ); + void send(Map command) => + unawaited(_rig.host.host.handle(command)); @override Future close() async {} diff --git a/stronglift_replacement/workout_app/test/screens/_run_screen_fixtures.dart b/stronglift_replacement/workout_app/test/screens/_run_screen_fixtures.dart index 4f6c3b6..e71e7ec 100644 --- a/stronglift_replacement/workout_app/test/screens/_run_screen_fixtures.dart +++ b/stronglift_replacement/workout_app/test/screens/_run_screen_fixtures.dart @@ -109,4 +109,3 @@ class RunHarness { await tester.pumpAndSettle(); } } - diff --git a/stronglift_replacement/workout_app/test/screens/run_screen_persist_test.dart b/stronglift_replacement/workout_app/test/screens/run_screen_persist_test.dart index 7167cf1..e4c5472 100644 --- a/stronglift_replacement/workout_app/test/screens/run_screen_persist_test.dart +++ b/stronglift_replacement/workout_app/test/screens/run_screen_persist_test.dart @@ -210,27 +210,28 @@ void main() { 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(); + 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(); + rig.host.host.notificationPressed(); + await tester.pump(); + await tester.pump(); - expect(key('run_finish_dialog'), findsOneWidget); - expect(rig.engine.phase, RunPhase.recording); + 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); - }); + 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); + }, + ); }); group('(c) the app opens on the run', () { diff --git a/stronglift_replacement/workout_app/test/screens/run_screen_test.dart b/stronglift_replacement/workout_app/test/screens/run_screen_test.dart index 69a8c75..369bdb4 100644 --- a/stronglift_replacement/workout_app/test/screens/run_screen_test.dart +++ b/stronglift_replacement/workout_app/test/screens/run_screen_test.dart @@ -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); diff --git a/stronglift_replacement/workout_app/test/services/feedback_cues_long_test.dart b/stronglift_replacement/workout_app/test/services/feedback_cues_long_test.dart new file mode 100644 index 0000000..9cf92d9 --- /dev/null +++ b/stronglift_replacement/workout_app/test/services/feedback_cues_long_test.dart @@ -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 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); + }); + }); + } +} diff --git a/stronglift_replacement/workout_app/test/services/run_engine_recorder_test.dart b/stronglift_replacement/workout_app/test/services/run_engine_recorder_test.dart new file mode 100644 index 0000000..cb54365 --- /dev/null +++ b/stronglift_replacement/workout_app/test/services/run_engine_recorder_test.dart @@ -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? advice, + List? 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 = []; + 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.delayed(const Duration(seconds: 6)); + expect(ended, 1); + await engine.finish(); + engine.dispose(); + }); +} diff --git a/stronglift_replacement/workout_app/test/services/run_host_test.dart b/stronglift_replacement/workout_app/test/services/run_host_test.dart index b428858..601334b 100644 --- a/stronglift_replacement/workout_app/test/services/run_host_test.dart +++ b/stronglift_replacement/workout_app/test/services/run_host_test.dart @@ -297,14 +297,17 @@ void main() { 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); + 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'); - }); + expect(rig.store.held, isNotNull); + expect(rig.port.last['issue'], 'streamError'); + }, + ); }); test('unknown commands are ignored', () async { diff --git a/stronglift_replacement/workout_app/test/services/run_task_handler_test.dart b/stronglift_replacement/workout_app/test/services/run_task_handler_test.dart index 598667d..8170ce8 100644 --- a/stronglift_replacement/workout_app/test/services/run_task_handler_test.dart +++ b/stronglift_replacement/workout_app/test/services/run_task_handler_test.dart @@ -24,12 +24,15 @@ void main() { 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( + '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(); @@ -39,20 +42,22 @@ void main() { 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); + 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); - }); + 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}); + final handler = handlerFor(rig)..onReceiveData({'cmd': RunCmd.start}); await pumpEventQueue(); expect(rig.engine.phase, RunPhase.recording); diff --git a/stronglift_replacement/workout_app/test/services/run_view_test.dart b/stronglift_replacement/workout_app/test/services/run_view_test.dart index 5646640..450caba 100644 --- a/stronglift_replacement/workout_app/test/services/run_view_test.dart +++ b/stronglift_replacement/workout_app/test/services/run_view_test.dart @@ -105,7 +105,8 @@ void main() { ..setPhase(RunPhase.recording) ..addFix(); var asked = 0; - final view = RunView()..onNeedSync = () { + final view = RunView() + ..onNeedSync = () { asked++; }; final message = snapshot(engine)..['total'] = 5; @@ -167,13 +168,7 @@ void main() { 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, - ]); + final withAltitude = decodePoint([0, 1.5, 2.5, 3, 40.0]); expect(withAltitude.altitudeM, 40); expect(isRunMessage({'cmd': 'x'}), isFalse); expect(isRunMessage('x'), isFalse);