Persist runs: tests, trims, adapter coverage

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

Claude-Session: https://claude.ai/code/session_01WzxdWW75Epgijvt2eJ1ErR
This commit is contained in:
Krzysztof Rudnicki 2026-11-17 21:28:45 +01:00
parent cfc2cd553a
commit 0175cbede4
13 changed files with 227 additions and 100 deletions

View File

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

View File

@ -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<void>? _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<void> 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<void> _until(bool Function() done) async {
if (done()) return;
final completer = Completer<void>();
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<void> _startService() async {

View File

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

View File

@ -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<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 {
return false;
} finally {
removeListener(check);
}
}
@override
void dispose() {
livePoints.dispose();

View File

@ -101,9 +101,8 @@ class _RigLink implements RunHostLink {
Stream<Map<Object?, Object?>> get messages => _rig.port.messages;
@override
void send(Map<String, Object?> command) => unawaited(
_rig.host.host.handle(command),
);
void send(Map<String, Object?> command) =>
unawaited(_rig.host.host.handle(command));
@override
Future<void> close() async {}

View File

@ -109,4 +109,3 @@ class RunHarness {
await tester.pumpAndSettle();
}
}

View File

@ -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', () {

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

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

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

View File

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

View File

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