From e7d00b85ff91032679e8b5d19f719209ae5e69a5 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 4 Nov 2026 17:43:29 +0000 Subject: [PATCH] Runs: running run and stage durations tick live One shared ElapsedClock (single timer, only while a visible running item is watched and the app is visible; cadence follows formatDuration precision) and a LiveElapsedBuilder that repaints only its own text. Running list rows, the Summary Duration and running timeline visits tick. A stage start re-reads the open detail, since step deltas carry no started_at. Fixture ?running=1 for captures. --- app/lib/features/runs/domain/run_events.dart | 16 ++ .../features/runs/ui/run_detail_content.dart | 10 + .../runs/ui/run_detail_summary_fields.dart | 22 +- .../runs/ui/run_detail_tab_bodies.dart | 41 ++-- .../features/runs/ui/run_detail_timeline.dart | 11 + app/lib/features/runs/ui/run_list_row.dart | 50 ++-- app/lib/features/runs/ui/runs_controller.dart | 4 +- app/lib/features/runs/ui/runs_list.dart | 3 +- app/lib/ui/text/elapsed_clock.dart | 148 ++++++++++++ app/lib/ui/text/live_elapsed_builder.dart | 83 +++++++ app/notes/live-run-durations.md | 33 +++ .../runs/ui/run_live_duration_test.dart | 215 ++++++++++++++++++ app/test/perf/background_work_bench_test.dart | 5 +- app/test/ui/text/elapsed_clock_test.dart | 111 +++++++++ app/tool/search_selection_probe_entry.dart | 23 ++ 15 files changed, 733 insertions(+), 42 deletions(-) create mode 100644 app/lib/ui/text/elapsed_clock.dart create mode 100644 app/lib/ui/text/live_elapsed_builder.dart create mode 100644 app/notes/live-run-durations.md create mode 100644 app/test/features/runs/ui/run_live_duration_test.dart create mode 100644 app/test/ui/text/elapsed_clock_test.dart diff --git a/app/lib/features/runs/domain/run_events.dart b/app/lib/features/runs/domain/run_events.dart index 20d4fb1f..d24917aa 100644 --- a/app/lib/features/runs/domain/run_events.dart +++ b/app/lib/features/runs/domain/run_events.dart @@ -239,4 +239,20 @@ bool runDetailNeedsFullSync(JsonMap frame) { stepLifecycleRank(stepStatus) == 2; } +/// A step delta carries no timestamps, so a visit that started running after +/// the detail was read has no `started_at` (and no elapsed time) until the +/// detail is read again. +bool runDetailLacksStepStart(JsonMap? detail, JsonMap frame) { + final step = frame['step']; + if (step is! Map || _word(step['status']) != 'running') return false; + final steps = detail?['steps']; + if (steps is! List) return false; + for (final known in steps.whereType()) { + if (known['sequence'] == step['sequence']) { + return _blank(known['started_at']); + } + } + return true; +} + String _word(dynamic value) => '${value ?? ''}'.trim().toLowerCase(); diff --git a/app/lib/features/runs/ui/run_detail_content.dart b/app/lib/features/runs/ui/run_detail_content.dart index 1412fc13..abea9648 100644 --- a/app/lib/features/runs/ui/run_detail_content.dart +++ b/app/lib/features/runs/ui/run_detail_content.dart @@ -23,6 +23,7 @@ typedef DetailVisit = ({ String outcome, String target, String? duration, + DateTime? runningSince, }); /// The run's primary label: the stored title, else the pipeline name, and only @@ -149,6 +150,7 @@ List detailTimeline(dynamic steps) { outcome: '${step['outcome'] ?? ''}'.trim(), target: '${step['target'] ?? ''}'.trim(), duration: _visitDuration(step), + runningSince: _visitRunningSince(step), ); }(), ]; @@ -205,6 +207,14 @@ String? _visitDuration(Map step) { return seconds < 0 ? null : formatDuration(seconds); } +/// When a running visit started, so its row can show the elapsed time; null +/// for a visit that is not running, finished, or recorded no start. +DateTime? _visitRunningSince(Map step) { + if ('${step['status'] ?? ''}'.trim().toLowerCase() != 'running') return null; + if ('${step['finished_at'] ?? ''}'.trim().isNotEmpty) return null; + return DateTime.tryParse('${step['started_at'] ?? ''}'.trim()); +} + String _text(dynamic value, String fallback) { final text = '${value ?? ''}'.trim(); return text.isEmpty ? fallback : text; diff --git a/app/lib/features/runs/ui/run_detail_summary_fields.dart b/app/lib/features/runs/ui/run_detail_summary_fields.dart index 0234eb57..87905eb8 100644 --- a/app/lib/features/runs/ui/run_detail_summary_fields.dart +++ b/app/lib/features/runs/ui/run_detail_summary_fields.dart @@ -23,7 +23,10 @@ typedef DetailSummaryRow = ({ /// `summaryRows` in the web client does. A run with no pipeline id shows its /// recorded pipeline name, and shows no Pipeline row at all when it recorded /// neither. -List detailSummaryRows(JsonMap run) { +/// +/// An executing run with no recorded finish shows its elapsed Duration up to +/// [now]; without [now] it has none. +List detailSummaryRows(JsonMap run, {DateTime? now}) { final rows = []; void add( String label, @@ -48,10 +51,10 @@ List detailSummaryRows(JsonMap run) { add('Content hash', _text(run['content_hash']), monospace: true); add('Started', formatLocalTimestamp(_text(run['created_at']))); add('Finished', formatLocalTimestamp(_text(run['finished_at']))); - final seconds = durationSeconds( - _text(run['created_at']), - _text(run['finished_at']), - ); + final since = detailRunningSince(run); + final seconds = since != null + ? now?.difference(since).inSeconds + : durationSeconds(_text(run['created_at']), _text(run['finished_at'])); if (seconds != null) add('Duration', formatDuration(seconds)); final retryOf = _number(run['retry_of'])?.toInt() ?? 0; if (retryOf > 0) add('Retry of', 'run $retryOf'); @@ -82,6 +85,15 @@ String detailSummaryIdentity(JsonMap run) { '${visits(completed, 'completed')}'; } +/// When the run started, while it is executing and has no recorded finish; +/// null otherwise, so its Duration is the recorded one (or none). +DateTime? detailRunningSince(JsonMap run) { + if (run['executing'] != true || _text(run['finished_at']) != null) { + return null; + } + return parseInstant(_text(run['created_at'])); +} + String? _text(dynamic value) { if (value == null) return null; final text = '$value'.trim(); diff --git a/app/lib/features/runs/ui/run_detail_tab_bodies.dart b/app/lib/features/runs/ui/run_detail_tab_bodies.dart index fd5ae2c6..c03d7824 100644 --- a/app/lib/features/runs/ui/run_detail_tab_bodies.dart +++ b/app/lib/features/runs/ui/run_detail_tab_bodies.dart @@ -9,6 +9,7 @@ import 'run_field_body.dart'; import '../../../ui/adaptive/host.dart'; import '../../../ui/layout/facts_grid.dart'; import '../../../ui/layout/sticky_section.dart'; +import '../../../ui/text/live_elapsed_builder.dart'; import '../../../ui/text/monospace.dart'; import '../../../ui/adaptive/floating_bar_layout.dart'; @@ -37,10 +38,12 @@ Widget runDetailSummaryTab({ // The top bar's subtitle already names the run's pipeline (and its title // opens it), so a Pipeline fact would only repeat it. final pipelineInBar = '${run['name'] ?? ''}'.trim().isNotEmpty; - final facts = [ - for (final row in rows) + List facts(DateTime now) => [ + for (final row in detailSummaryRows(run, now: now)) if (!row.block && !(pipelineInBar && row.label == 'Pipeline')) row, ]; + // An executing run's Duration ticks; only the facts grid rebuilds with it. + final runningSince = detailRunningSince(run); return CustomScrollView( key: const Key('run-detail-tab-body-summary'), slivers: [ @@ -63,21 +66,27 @@ Widget runDetailSummaryTab({ ), // The facts sit on the page as one grid, the same on both hosts: no // grouped card, so a single fact starts at the leading edge. - if (facts.isNotEmpty) - SliverToBoxAdapter( - child: FactsGrid( - key: const Key('run-detail-summary-facts'), - items: [ - for (final row in facts) - FactsGridItem( - key: ValueKey('run-detail-summary-${_slug(row.label)}'), - label: row.label, - value: row.value, - monospace: row.monospace, - ), - ], - ), + SliverToBoxAdapter( + child: LiveElapsedBuilder( + since: runningSince, + builder: (context, now) { + final shown = facts(now); + if (shown.isEmpty) return const SizedBox.shrink(); + return FactsGrid( + key: const Key('run-detail-summary-facts'), + items: [ + for (final row in shown) + FactsGridItem( + key: ValueKey('run-detail-summary-${_slug(row.label)}'), + label: row.label, + value: row.value, + monospace: row.monospace, + ), + ], + ); + }, ), + ), // Long blocks (the Diagnostic), Input and Output are sticky // collapsibles: each title stays pinned while its content scrolls. for (final row in rows) diff --git a/app/lib/features/runs/ui/run_detail_timeline.dart b/app/lib/features/runs/ui/run_detail_timeline.dart index 60372328..20b214d2 100644 --- a/app/lib/features/runs/ui/run_detail_timeline.dart +++ b/app/lib/features/runs/ui/run_detail_timeline.dart @@ -5,6 +5,8 @@ import '../../../ui/layout/app_list_avatar.dart'; import '../../../ui/layout/app_list_row.dart'; import '../../../ui/status/outcome_palette.dart'; import '../../../ui/status/run_status_icon.dart'; +import '../../../ui/text/live_elapsed_builder.dart'; +import '../../pipelines/pipeline_format.dart' show formatDuration; import '../domain/run_models.dart'; import 'run_detail_content.dart'; @@ -151,6 +153,15 @@ class RunTimelineRow extends StatelessWidget { ), title: Text(visit.title), time: visit.duration, + // A running visit's elapsed time ticks; only that label rebuilds. + timeWidget: visit.runningSince == null + ? null + : LiveElapsedBuilder( + since: visit.runningSince, + builder: (context, now) => Text( + formatDuration(now.difference(visit.runningSince!).inSeconds), + ), + ), subtitleLeading: _outcome(context), subtitle: visit.target.isEmpty ? null : Text('→ ${visit.target}'), ); diff --git a/app/lib/features/runs/ui/run_list_row.dart b/app/lib/features/runs/ui/run_list_row.dart index 36f1d065..31873884 100644 --- a/app/lib/features/runs/ui/run_list_row.dart +++ b/app/lib/features/runs/ui/run_list_row.dart @@ -6,6 +6,7 @@ import '../../../ui/adaptive/host.dart'; import '../../../ui/layout/app_list_avatar.dart'; import '../../../ui/layout/app_list_row.dart'; import '../../../ui/status/run_status_icon.dart'; +import '../../../ui/text/live_elapsed_builder.dart'; import '../../../ui/text/relative_time_label.dart'; import '../domain/run_deletion.dart'; import '../domain/run_models.dart'; @@ -62,7 +63,6 @@ class RunListRow extends StatelessWidget { final identity = runIdentity(run['title'], run['name']); final id = run['id']; final title = identity.label.isEmpty ? 'Run $id' : identity.label; - final facts = runRowFacts(run, now); // A run without its own title is named by its pipeline, so the pipeline // line does not repeat it. final pipeline = identity.pipeline?.trim(); @@ -78,22 +78,38 @@ class RunListRow extends StatelessWidget { final bytes = runSizeBytes(run); final size = bytes == null ? null : formatByteSize(bytes); final createdAt = DateTime.tryParse('${run['created_at'] ?? ''}'); - final subtitle = [ - ?pipelineLabel, - if (scheduled) 'Scheduled', - ?facts.duration, - ?facts.progress, - ?size, - ].join(' · '); + String subtitle(DateTime now) { + final facts = runRowFacts(run, now); + return [ + ?pipelineLabel, + if (scheduled) 'Scheduled', + ?facts.duration, + ?facts.progress, + ?size, + ].join(' · '); + } + // A narrow pane keeps the decision facts: the pipeline, and progress // while executing (duration only when there is no pipeline to show). - final compactSubtitle = [ - ?pipelineLabel, - if (scheduled) 'Scheduled', - if (run['executing'] == true && facts.progress != null) facts.progress!, - if (pipelineLabel == null && facts.duration != null) facts.duration!, - ?size, - ].join(' · '); + String compactSubtitle(DateTime now) { + final facts = runRowFacts(run, now); + return [ + ?pipelineLabel, + if (scheduled) 'Scheduled', + if (run['executing'] == true && facts.progress != null) facts.progress!, + if (pipelineLabel == null && facts.duration != null) facts.duration!, + ?size, + ].join(' · '); + } + + // An executing run's duration ticks; only its fact line rebuilds. + final runningSince = run['executing'] == true ? createdAt : null; + Widget line(String Function(DateTime now) text) => runningSince == null + ? Text(text(now)) + : LiveElapsedBuilder( + since: runningSince, + builder: (context, now) => Text(text(now)), + ); final state = runStateOf(run['status']); return AppListRow( key: ValueKey('run-row-$id'), @@ -111,8 +127,8 @@ class RunListRow extends StatelessWidget { timeWidget: createdAt == null ? null : RelativeTimeLabel(instant: createdAt, now: now), - subtitle: Text(subtitle), - compactSubtitle: Text(compactSubtitle), + subtitle: line(subtitle), + compactSubtitle: line(compactSubtitle), // Kept in a narrow list pane too, so every run's actions stay one tap // away from the list. menu: diff --git a/app/lib/features/runs/ui/runs_controller.dart b/app/lib/features/runs/ui/runs_controller.dart index 3ac6854d..b24f0ed4 100644 --- a/app/lib/features/runs/ui/runs_controller.dart +++ b/app/lib/features/runs/ui/runs_controller.dart @@ -283,7 +283,9 @@ class RunsController extends ChangeNotifier { final selected = _selectedId; if (selected != null && frame['run_id'] == selected && - (folded.needsResync || runDetailNeedsFullSync(frame))) { + (folded.needsResync || + runDetailNeedsFullSync(frame) || + runDetailLacksStepStart(detail, frame))) { _scheduleDetailRefresh(selected); } // A frame that changed neither the list nor the open detail shows diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart index 83cb4be6..7c22d8df 100644 --- a/app/lib/features/runs/ui/runs_list.dart +++ b/app/lib/features/runs/ui/runs_list.dart @@ -330,8 +330,7 @@ class RunsList extends StatelessWidget { id == controller.selectedRunId, controller, onSelected, - // An executing run's duration reads the clock, as before. - run['executing'] == true ? runRowFacts(run, now).duration : null, + // An executing run's duration ticks inside the row, not from here. ), builder: (context) => _runRow(run, id, now, divider: divider), ); diff --git a/app/lib/ui/text/elapsed_clock.dart b/app/lib/ui/text/elapsed_clock.dart new file mode 100644 index 00000000..fbc2595f --- /dev/null +++ b/app/lib/ui/text/elapsed_clock.dart @@ -0,0 +1,148 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +/// One clock shared by every live elapsed-time label (a running run's or +/// stage's duration). +/// +/// It runs a single timer, only while some label watches a start instant and +/// the app is visible, and wakes when the soonest watched duration next +/// changes its displayed text: every second under an hour (`3m 5s`), on the +/// minute under a day (`1h 2m`) and on the hour after that (`2d 3h`). Labels +/// rebuild themselves on a tick; nothing else in the tree does. +class ElapsedClock with WidgetsBindingObserver { + /// [now] reads the time; tests pass a fake clock. + ElapsedClock({DateTime Function()? now}) : _read = now ?? DateTime.now; + + /// The clock the app's labels share. + static final ElapsedClock shared = ElapsedClock(); + + final DateTime Function() _read; + final Map _watchers = {}; + Timer? _timer; + bool _observing = false; + bool _hidden = false; + + /// The boundary the last tick was due at. The next tick is scheduled from + /// it when the wall clock lags the timer (a test's fake timers), so a tick + /// always moves on to the next boundary rather than re-arming for the same + /// one. + DateTime? _reached; + + DateTime get now => _read(); + + /// Whether a tick is scheduled (a label watches and the app is visible). + @visibleForTesting + bool get ticking => _timer != null; + + /// Calls [onTick] whenever a duration measured from [since] may have + /// changed its text, until [unwatch] with the same [key]. + void watch(Object key, DateTime since, VoidCallback onTick) { + _watchers[key] = (since: since, onTick: onTick); + if (!_observing) { + _hidden = switch (WidgetsBinding.instance.lifecycleState) { + AppLifecycleState.hidden || + AppLifecycleState.paused || + AppLifecycleState.detached => true, + _ => false, + }; + WidgetsBinding.instance.addObserver(this); + _observing = true; + } + _schedule(); + } + + void unwatch(Object key) { + if (_watchers.remove(key) == null) return; + if (_watchers.isNotEmpty) { + _schedule(); + return; + } + _stop(); + _reached = null; + if (_observing) { + WidgetsBinding.instance.removeObserver(this); + _observing = false; + } + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) { + _hidden = false; + _notify(); + _schedule(); + } else if (state == AppLifecycleState.hidden || + // Not inactive: a desktop window that lost focus is still visible. + state == AppLifecycleState.paused || + state == AppLifecycleState.detached) { + _hidden = true; + _stop(); + } + } + + void _schedule() { + _stop(); + if (_hidden || _watchers.isEmpty) return; + final wall = _read(); + final reached = _reached; + final from = reached != null && reached.isAfter(wall) ? reached : wall; + Duration? delay; + for (final watcher in _watchers.values) { + final next = elapsedTextChangesIn(from.difference(watcher.since)); + if (delay == null || next < delay) delay = next; + } + final due = from.add(delay!); + _timer = Timer(delay, () { + _timer = null; + _reached = due; + _notify(); + _schedule(); + }); + } + + void _notify() { + for (final watcher in [..._watchers.values]) { + watcher.onTick(); + } + } + + void _stop() { + _timer?.cancel(); + _timer = null; + } +} + +/// How long until an elapsed duration shown at `formatDuration` precision +/// (seconds under an hour, minutes under a day, then hours) shows new text. +/// A negative elapsed (clock skew) reads `0s` until it reaches one second. +@visibleForTesting +Duration elapsedTextChangesIn(Duration elapsed) { + if (elapsed.isNegative) return -elapsed + const Duration(seconds: 1); + final unit = elapsed < const Duration(hours: 1) + ? const Duration(seconds: 1) + : elapsed < const Duration(days: 1) + ? const Duration(minutes: 1) + : const Duration(hours: 1); + final into = elapsed.inMicroseconds % unit.inMicroseconds; + return Duration(microseconds: unit.inMicroseconds - into); +} + +/// Supplies the [ElapsedClock] below it; [ElapsedClock.shared] without one. +class ElapsedClockScope extends InheritedWidget { + const ElapsedClockScope({ + super.key, + required this.clock, + required super.child, + }); + + final ElapsedClock clock; + + static ElapsedClock of(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()?.clock ?? + ElapsedClock.shared; + + @override + bool updateShouldNotify(ElapsedClockScope oldWidget) => + clock != oldWidget.clock; +} diff --git a/app/lib/ui/text/live_elapsed_builder.dart b/app/lib/ui/text/live_elapsed_builder.dart new file mode 100644 index 00000000..f7beaf04 --- /dev/null +++ b/app/lib/ui/text/live_elapsed_builder.dart @@ -0,0 +1,83 @@ +import 'package:flutter/widgets.dart'; + +import 'elapsed_clock.dart'; + +/// Builds a running item's elapsed-time text from the [ElapsedClock], and +/// rebuilds only itself as that duration advances. +/// +/// With a null [since] (nothing running) it builds once from the clock's time +/// and watches nothing, so no timer runs. While its tickers are muted (an +/// offstage tab or a covered route) it stops watching and catches up when +/// shown again. +class LiveElapsedBuilder extends StatefulWidget { + const LiveElapsedBuilder({ + super.key, + required this.since, + required this.builder, + }); + + /// When the running item started; null when it is not running. + final DateTime? since; + + /// Builds the text for the clock's current time. + final Widget Function(BuildContext context, DateTime now) builder; + + @override + State createState() => _LiveElapsedBuilderState(); +} + +class _LiveElapsedBuilderState extends State { + ElapsedClock? _clock; + bool _shown = true; + bool _watching = false; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final clock = ElapsedClockScope.of(context); + if (clock != _clock) { + _unwatch(); + _clock = clock; + } + _shown = TickerMode.valuesOf(context).enabled; + _sync(); + } + + @override + void didUpdateWidget(LiveElapsedBuilder oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.since != widget.since) { + _unwatch(); + _sync(); + } + } + + void _sync() { + final since = widget.since; + if (since == null || !_shown) { + _unwatch(); + } else if (!_watching) { + _clock!.watch(this, since, _tick); + _watching = true; + } + } + + void _unwatch() { + if (!_watching) return; + _clock?.unwatch(this); + _watching = false; + } + + void _tick() { + if (mounted) setState(() {}); + } + + @override + Widget build(BuildContext context) => widget.builder(context, _clock!.now); + + @override + void dispose() { + _unwatch(); + super.dispose(); + } +} diff --git a/app/notes/live-run-durations.md b/app/notes/live-run-durations.md new file mode 100644 index 00000000..112752a4 --- /dev/null +++ b/app/notes/live-run-durations.md @@ -0,0 +1,33 @@ +# Live run durations + +Running runs and stages now show durations that update on their own, without a refresh. + +- `lib/ui/text/elapsed_clock.dart` has one shared `ElapsedClock`. It runs a single + timer only while some label is watching, and only while the app is visible. The + timer wakes when the shortest watched duration would next change its text: every + second under an hour (`3m 5s`), every minute under a day (`1h 2m`), then every hour. + `ElapsedClockScope` lets tests inject a fake clock (`ElapsedClock(now: ...)`). +- `lib/ui/text/live_elapsed_builder.dart` rebuilds only its own subtree. With a null + `since` it watches nothing. It also stops watching while muted (an offstage tab or a + covered route) and catches up when shown again. +- Runs list: an executing row's fact lines tick (`run_list_row.dart`). The list's memo + no longer keys on the clock. +- Run detail: an executing run's Summary shows a ticking Duration fact + (`detailSummaryRows(run, now:)`). A running Timeline visit's time ticks too + (`DetailVisit.runningSince`). +- Status and finish times already arrive through `run_event` frames. The terminal + frame carries `finished_at`, so a row changes from a ticking duration to the + recorded one without a refresh. A step delta carries no `started_at`, so a stage + start re-reads the open detail (`runDetailLacksStepStart`). +- Bench budget (`test/perf/background_work_bench_test.dart`): with 20 visible running + rows there are 2 active timers (minute labels plus elapsed clock) and 61 timers + per minute. Before this change it was 1 timer, because running rows did not tick. + +Evidence: `test/ui/text/elapsed_clock_test.dart` and +`test/features/runs/ui/run_live_duration_test.dart` use fake clocks. The browser +capture used `?running=1` on the full-app fixture, at `/runs` 880x1000. Seven +seconds apart, the row read `release-train · 3m 53s` and then +`release-train · 4m 0s`. + +Not covered: the visit pane's Duration fact is still the recorded one. A `waiting` +run does not tick, which matches the list's existing rule. diff --git a/app/test/features/runs/ui/run_live_duration_test.dart b/app/test/features/runs/ui/run_live_duration_test.dart new file mode 100644 index 00000000..a7244a68 --- /dev/null +++ b/app/test/features/runs/ui/run_live_duration_test.dart @@ -0,0 +1,215 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_content.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_tab_bodies.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_timeline.dart'; +import 'package:pipelines_app/features/runs/ui/run_list_row.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; +import 'package:pipelines_app/ui/text/elapsed_clock.dart'; + +final _start = DateTime.utc(2026, 11, 4, 12); + +final _running = { + 'id': 9, + 'title': 'Nightly build', + 'name': 'release', + 'status': 'running', + 'executing': true, + 'created_at': '2026-11-04T12:00:00Z', + 'finished_at': '', + 'current_stage': 'build', +}; + +final _succeeded = { + ..._running, + 'status': 'succeeded', + 'executing': false, + 'finished_at': '2026-11-04T12:02:05Z', +}; + +/// A fake wall clock advanced together with the test's fake timers. +class _Time { + _Time(this.value); + DateTime value; + late final clock = ElapsedClock(now: () => value); + Future advance(WidgetTester tester, Duration by) async { + value = value.add(by); + await tester.pump(by); + } +} + +Widget _host(_Time time, Widget child) => MaterialApp( + home: ElapsedClockScope( + clock: time.clock, + child: Scaffold(body: child), + ), +); + +Finder _textContaining(String text) => find.textContaining(text); + +class _Gateway implements ApiGateway { + final framesController = StreamController.broadcast(); + final detailRequests = >[]; + @override + Stream get frames => framesController.stream; + @override + Future call(String type, [JsonMap fields = const {}]) { + final request = Completer(); + if (type == 'get_run') detailRequests.add(request); + return request.future; + } +} + +void main() { + testWidgets('a running row ticks and stops once the run completes', ( + tester, + ) async { + final time = _Time(_start.add(const Duration(seconds: 45))); + Widget row(JsonMap run) => + _host(time, RunListRow(run: run, now: time.value)); + + await tester.pumpWidget(row(_running)); + expect(_textContaining('45s'), findsOneWidget); + await time.advance(tester, const Duration(seconds: 1)); + expect(_textContaining('46s'), findsOneWidget); + await time.advance(tester, const Duration(seconds: 14)); + expect(_textContaining('1m 0s'), findsOneWidget); + expect(time.clock.ticking, isTrue); + + // The terminal frame's row: the recorded duration, no timer. + await tester.pumpWidget(row(_succeeded)); + expect(_textContaining('2m 5s'), findsOneWidget); + expect(time.clock.ticking, isFalse); + }); + + testWidgets('no timer runs when no row is running', (tester) async { + final time = _Time(_start.add(const Duration(minutes: 5))); + await tester.pumpWidget( + _host( + time, + Column( + children: [ + RunListRow(run: _succeeded, now: time.value), + RunListRow( + run: {..._running, 'status': 'waiting', 'executing': false}, + now: time.value, + ), + ], + ), + ), + ); + expect(time.clock.ticking, isFalse); + }); + + testWidgets('the Summary Duration of a running run ticks', (tester) async { + final time = _Time(_start.add(const Duration(seconds: 59))); + await tester.pumpWidget( + _host( + time, + Builder( + builder: (context) => runDetailSummaryTab( + context: context, + run: _running, + cupertino: false, + copying: false, + copyStatus: null, + onCopy: () {}, + ), + ), + ), + ); + expect(find.text('59s'), findsOneWidget); + await time.advance(tester, const Duration(seconds: 1)); + expect(find.text('1m 0s'), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + expect(time.clock.ticking, isFalse); + }); + + testWidgets('a running stage row ticks; finished rows keep their time', ( + tester, + ) async { + final time = _Time(_start.add(const Duration(minutes: 3, seconds: 4))); + final steps = [ + { + 'stage': 'plan', + 'sequence': 1, + 'status': 'completed', + 'outcome': 'success', + 'started_at': '2026-11-04T11:58:00Z', + 'finished_at': '2026-11-04T12:00:00Z', + }, + { + 'stage': 'build', + 'sequence': 2, + 'status': 'running', + 'started_at': '2026-11-04T12:00:00Z', + }, + ]; + await tester.pumpWidget( + _host( + time, + RunTimelineList( + visits: detailTimeline(steps), + cupertino: false, + onSelected: (_) {}, + ), + ), + ); + expect(find.text('2m 0s'), findsOneWidget); + expect(find.text('3m 4s'), findsOneWidget); + await time.advance(tester, const Duration(seconds: 1)); + expect(find.text('3m 5s'), findsOneWidget); + expect(find.text('2m 0s'), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + expect(time.clock.ticking, isFalse); + }); + + test('a terminal frame finishes the row without a list refresh', () async { + final gateway = _Gateway(); + final controller = RunsController(RunsRepository(gateway)) + ..runs = [_running] + ..listen(gateway.frames); + addTearDown(() { + controller.dispose(); + gateway.framesController.close(); + }); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 9, + 'status': 'succeeded', + 'finished_at': '2026-11-04T12:02:05Z', + }); + await Future.delayed(Duration.zero); + final row = controller.runs.single; + expect(row['status'], 'succeeded'); + expect(row['executing'], isFalse); + expect(row['finished_at'], '2026-11-04T12:02:05Z'); + }); + + test('a stage start re-reads the open detail for its start time', () async { + final gateway = _Gateway(); + final controller = RunsController(RunsRepository(gateway)); + addTearDown(() { + controller.dispose(); + gateway.framesController.close(); + }); + final select = controller.select(9); + gateway.detailRequests.single.complete({ + 'run_detail': {..._running, 'steps': []}, + }); + await select; + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 9, + 'status': 'running', + 'step': {'sequence': 1, 'stage': 'build', 'status': 'running'}, + }); + await Future.delayed(const Duration(milliseconds: 200)); + expect(gateway.detailRequests, hasLength(2)); + }); +} diff --git a/app/test/perf/background_work_bench_test.dart b/app/test/perf/background_work_bench_test.dart index 30ce037c..ce00e351 100644 --- a/app/test/perf/background_work_bench_test.dart +++ b/app/test/perf/background_work_bench_test.dart @@ -163,7 +163,10 @@ void main() { 'totalRebuildsPerMinute=${rebuilds.total} ' 'timersScheduledPerMinute=$perMinute', ); - expect(active, lessThanOrEqualTo(1)); + // One shared minute clock for the relative times and one shared clock + // for the 20 running rows' ticking durations; never a timer per row. + expect(active, lessThanOrEqualTo(2)); + expect(perMinute, lessThanOrEqualTo(61)); await tester.pumpWidget(const SizedBox()); expect(timers.active, 0); }); diff --git a/app/test/ui/text/elapsed_clock_test.dart b/app/test/ui/text/elapsed_clock_test.dart new file mode 100644 index 00000000..8b57cbb8 --- /dev/null +++ b/app/test/ui/text/elapsed_clock_test.dart @@ -0,0 +1,111 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/text/elapsed_clock.dart'; +import 'package:pipelines_app/ui/text/live_elapsed_builder.dart'; + +/// A fake wall clock the test advances together with the fake timers. +class _Time { + _Time(this.value); + DateTime value; + Future advance(WidgetTester tester, Duration by) async { + value = value.add(by); + await tester.pump(by); + } +} + +void main() { + test('wakes when the displayed precision next changes', () { + expect(elapsedTextChangesIn(Duration.zero), const Duration(seconds: 1)); + expect( + elapsedTextChangesIn(const Duration(seconds: 59, milliseconds: 400)), + const Duration(milliseconds: 600), + ); + // `1h 2m` shows minutes, `2d 3h` hours. + expect( + elapsedTextChangesIn(const Duration(hours: 1, minutes: 2, seconds: 15)), + const Duration(seconds: 45), + ); + expect( + elapsedTextChangesIn(const Duration(days: 2, minutes: 30)), + const Duration(minutes: 30), + ); + // Clock skew reads 0s until a second has passed. + expect( + elapsedTextChangesIn(const Duration(seconds: -2)), + const Duration(seconds: 3), + ); + }); + + testWidgets('a live label ticks, stops when no longer running and on ' + 'dispose', (tester) async { + final start = DateTime.utc(2026, 11, 4, 12); + final time = _Time(start.add(const Duration(seconds: 5))); + final clock = ElapsedClock(now: () => time.value); + var builds = 0; + Widget app(DateTime? since) => Directionality( + textDirection: TextDirection.ltr, + child: ElapsedClockScope( + clock: clock, + child: LiveElapsedBuilder( + since: since, + builder: (context, now) { + builds += 1; + return Text('${now.difference(start).inSeconds}s'); + }, + ), + ), + ); + + await tester.pumpWidget(app(start)); + expect(find.text('5s'), findsOneWidget); + expect(clock.ticking, isTrue); + await time.advance(tester, const Duration(seconds: 1)); + expect(find.text('6s'), findsOneWidget); + await time.advance(tester, const Duration(seconds: 1)); + expect(find.text('7s'), findsOneWidget); + + // Finished: no longer watched, so the timer stops. + await tester.pumpWidget(app(null)); + expect(clock.ticking, isFalse); + final settled = builds; + await time.advance(tester, const Duration(seconds: 5)); + expect(builds, settled); + + await tester.pumpWidget(app(start)); + expect(clock.ticking, isTrue); + await tester.pumpWidget(const SizedBox()); + expect(clock.ticking, isFalse); + }); + + testWidgets('a muted label stops ticking and catches up when shown', ( + tester, + ) async { + final start = DateTime.utc(2026, 11, 4, 12); + final time = _Time(start); + final clock = ElapsedClock(now: () => time.value); + Widget app({required bool shown}) => Directionality( + textDirection: TextDirection.ltr, + child: ElapsedClockScope( + clock: clock, + child: TickerMode( + enabled: shown, + child: LiveElapsedBuilder( + since: start, + builder: (context, now) => + Text('${now.difference(start).inSeconds}s'), + ), + ), + ), + ); + + await tester.pumpWidget(app(shown: true)); + expect(clock.ticking, isTrue); + await tester.pumpWidget(app(shown: false)); + expect(clock.ticking, isFalse); + await time.advance(tester, const Duration(seconds: 30)); + await tester.pumpWidget(app(shown: true)); + expect(find.text('30s'), findsOneWidget); + expect(clock.ticking, isTrue); + await tester.pumpWidget(const SizedBox()); + }); +} diff --git a/app/tool/search_selection_probe_entry.dart b/app/tool/search_selection_probe_entry.dart index 15365dee..918e9323 100644 --- a/app/tool/search_selection_probe_entry.dart +++ b/app/tool/search_selection_probe_entry.dart @@ -123,6 +123,10 @@ JsonMap _probeChanges(List paths) => { int _fillerRunCount = 0; int _fillerStepCount = 0; +/// `?running=1`: run 8 executes, started 3m 50s before the page loaded, so a +/// capture shows its duration ticking. Absent by default. +DateTime? _runningSince; + List _fillerSteps() => [ for (var i = 0; i < _fillerStepCount; i++) { @@ -151,6 +155,19 @@ List _fillerRuns() => [ ]; List probeRuns() => [ + if (_runningSince != null) + { + 'id': 8, + 'title': 'Live deploy run', + 'name': 'release-train', + 'status': 'running', + 'executing': true, + 'current_stage': 'deploy', + 'completed_steps': 2, + 'created_at': _runningSince!.toUtc().toIso8601String(), + 'finished_at': '', + 'pipeline_id': 24, + }, { 'id': 7, 'title': 'Release train run', @@ -583,6 +600,7 @@ class _FixtureSink implements WebSocketSink { /// `?route=/runs/7/stage/build%3Fvisit%3D1` opens that app location; /// `?runs=200` / `?steps=60` append filler runs / run-7 steps for scroll /// performance captures; +/// `?running=1` adds an executing run 8 whose duration ticks; /// `?q=release` types that query into Search once its field is shown; /// `?platform=cupertino` renders the Cupertino host (`material`, the /// default, renders Material as browsers do); @@ -606,6 +624,11 @@ void main() { configurePerfFixture(params); _fillerRunCount = int.tryParse(params['runs'] ?? '') ?? 0; _fillerStepCount = int.tryParse(params['steps'] ?? '') ?? 0; + if (params['running'] == '1') { + _runningSince = DateTime.now().subtract( + const Duration(minutes: 3, seconds: 50), + ); + } final cupertino = params['platform'] == 'cupertino'; final route = params['route']; final opensRoute = route != null && route.startsWith('/');