Merge: running durations tick live in runs list, summary and timeline

This commit is contained in:
2026-11-04 17:48:34 +00:00
15 changed files with 735 additions and 44 deletions
@@ -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<Map>()) {
if (known['sequence'] == step['sequence']) {
return _blank(known['started_at']);
}
}
return true;
}
String _word(dynamic value) => '${value ?? ''}'.trim().toLowerCase();
@@ -24,6 +24,7 @@ typedef DetailVisit = ({
String outcome,
String target,
String? duration,
DateTime? runningSince,
String? tokens,
});
@@ -152,6 +153,7 @@ List<DetailVisit> detailTimeline(dynamic steps) {
outcome: '${step['outcome'] ?? ''}'.trim(),
target: '${step['target'] ?? ''}'.trim(),
duration: _visitDuration(step),
runningSince: _visitRunningSince(step),
tokens: switch (stageTokenUsage(JsonMap.from(step))) {
final usage? => stageTokenRowLabel(usage),
null => null,
@@ -212,6 +214,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;
@@ -25,7 +25,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<DetailSummaryRow> detailSummaryRows(JsonMap run) {
///
/// An executing run with no recorded finish shows its elapsed Duration up to
/// [now]; without [now] it has none.
List<DetailSummaryRow> detailSummaryRows(JsonMap run, {DateTime? now}) {
final rows = <DetailSummaryRow>[];
void add(
String label,
@@ -50,10 +53,10 @@ List<DetailSummaryRow> 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));
// What the run occupies on disk and what it spent, as the server measured
// and the harness reported; an unmeasured size or unreported usage has no
@@ -94,6 +97,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();
@@ -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<DetailSummaryRow> 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)
@@ -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 && visit.tokens == null
? null
+35 -19
View File
@@ -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';
@@ -63,7 +64,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();
@@ -82,24 +82,40 @@ class RunListRow extends StatelessWidget {
final usage = runTokenUsage(run);
final tokens = usage == null ? null : tokenUsageLabel(usage);
final createdAt = DateTime.tryParse('${run['created_at'] ?? ''}');
final subtitle = [
?pipelineLabel,
if (scheduled) 'Scheduled',
?facts.duration,
?facts.progress,
?size,
?tokens,
].join(' · ');
String subtitle(DateTime now) {
final facts = runRowFacts(run, now);
return [
?pipelineLabel,
if (scheduled) 'Scheduled',
?facts.duration,
?facts.progress,
?size,
?tokens,
].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,
?tokens,
].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,
?tokens,
].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'),
@@ -117,8 +133,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:
@@ -276,7 +276,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
+1 -2
View File
@@ -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),
);
+148
View File
@@ -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<Object, ({DateTime since, VoidCallback onTick})> _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<ElapsedClockScope>()?.clock ??
ElapsedClock.shared;
@override
bool updateShouldNotify(ElapsedClockScope oldWidget) =>
clock != oldWidget.clock;
}
+83
View File
@@ -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<LiveElapsedBuilder> createState() => _LiveElapsedBuilderState();
}
class _LiveElapsedBuilderState extends State<LiveElapsedBuilder> {
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();
}
}