From 3b996bdbc70a01e7c043680e112cf22325560d74 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sun, 1 Nov 2026 23:29:20 +0000 Subject: [PATCH] Share one minute clock across time labels and narrow shell and runs rebuilds Relative-time labels follow one wall-minute RelativeTimeClock instead of a timer per row, skip ticks while their tab is offstage and rebuild only when their text changes. The shell rebuilds its top bar only for the focused destination's published bar and its tab bar only for badge changes. Run events that repeat a row's state no longer notify, and the runs list filters and sorts once per build. Adds a rebuild/timer benchmark. --- app/lib/features/runs/domain/run_events.dart | 16 +- app/lib/features/runs/ui/runs_controller.dart | 6 + app/lib/features/runs/ui/runs_list.dart | 18 +- app/lib/shell/adaptive_shell.dart | 173 +++++++------ app/lib/shell/shell_bar.dart | 41 ++- app/lib/ui/text/relative_time_clock.dart | 105 ++++++++ app/lib/ui/text/relative_time_label.dart | 109 ++++---- app/test/perf/background_work_bench_test.dart | 239 ++++++++++++++++++ .../ui/text/relative_time_label_test.dart | 78 +++++- 9 files changed, 621 insertions(+), 164 deletions(-) create mode 100644 app/lib/ui/text/relative_time_clock.dart create mode 100644 app/test/perf/background_work_bench_test.dart diff --git a/app/lib/features/runs/domain/run_events.dart b/app/lib/features/runs/domain/run_events.dart index 4c1d7a2f..20d4fb1f 100644 --- a/app/lib/features/runs/domain/run_events.dart +++ b/app/lib/features/runs/domain/run_events.dart @@ -187,12 +187,26 @@ JsonMap? newRunSummaryFromFrame(JsonMap frame) { : (runs: [row, ...runs], needsResync: false); } final updated = _mergeRunFields(runs[index], frame); - if (identical(updated, runs[index])) return (runs: runs, needsResync: false); + // A frame that repeats the row's state (a busy run's progress stream) + // keeps the same list, so its holders can skip a rebuild. + if (identical(updated, runs[index]) || _sameFields(updated, runs[index])) { + return (runs: runs, needsResync: false); + } final next = [...runs]; next[index] = updated; return (runs: next, needsResync: false); } +/// Shallow equality: nested values compare by identity, so a rebuilt nested +/// map counts as a change. +bool _sameFields(JsonMap a, JsonMap b) { + if (a.length != b.length) return false; + for (final entry in a.entries) { + if (!b.containsKey(entry.key) || b[entry.key] != entry.value) return false; + } + return true; +} + JsonMap? foldRunEventDetail(JsonMap? detail, JsonMap frame) { if (detail == null || detail['id'] != frame['run_id']) return detail; if (_stale(detail['status'], frame['status'], runLifecycleRank) && diff --git a/app/lib/features/runs/ui/runs_controller.dart b/app/lib/features/runs/ui/runs_controller.dart index 7c3e5a35..3ac6854d 100644 --- a/app/lib/features/runs/ui/runs_controller.dart +++ b/app/lib/features/runs/ui/runs_controller.dart @@ -271,6 +271,7 @@ class RunsController extends ChangeNotifier { void _event(JsonMap frame) { if (_removed.contains(frame['run_id'])) return; final folded = foldRunEvent(runs, frame); + final before = (runs: runs, detail: detail); runs = folded.runs; selection.retain(runs); if (detail?['id'] == frame['run_id']) { @@ -285,6 +286,11 @@ class RunsController extends ChangeNotifier { (folded.needsResync || runDetailNeedsFullSync(frame))) { _scheduleDetailRefresh(selected); } + // A frame that changed neither the list nor the open detail shows + // nothing new; the refreshes above notify for themselves. + if (identical(before.runs, runs) && identical(before.detail, detail)) { + return; + } notifyListeners(); } diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart index 67a99479..3ad338ac 100644 --- a/app/lib/features/runs/ui/runs_list.dart +++ b/app/lib/features/runs/ui/runs_list.dart @@ -146,7 +146,9 @@ class RunsList extends StatelessWidget { RunsDeleteReport(controller: controller), RunsFilters(controller: controller), ]; - if (controller.visibleRuns.isNotEmpty) return _groupedRuns(context, header); + // Filtered and sorted once per build: the getter recomputes every read. + final visible = controller.visibleRuns; + if (visible.isNotEmpty) return _groupedRuns(context, header, visible); return BelowTopBar( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, @@ -169,15 +171,17 @@ class RunsList extends StatelessWidget { ); } - Widget _groupedRuns(BuildContext context, List header) { + Widget _groupedRuns( + BuildContext context, + List header, + List visible, + ) { final entries = <_Entry>[]; if (flatRunSorts.contains(controller.sort)) { // An order by size is one flat list: day headings would split it. - entries.addAll( - controller.visibleRuns.map((run) => (day: null, run: run)), - ); + entries.addAll(visible.map((run) => (day: null, run: run))); } else { - final groups = groupRunsByDay(controller.visibleRuns, DateTime.now()); + final groups = groupRunsByDay(visible, DateTime.now()); for (final group in groups) { entries.add((day: group, run: null)); entries.addAll(group.runs.map((run) => (day: null, run: run))); @@ -185,7 +189,7 @@ class RunsList extends StatelessWidget { } // Runs that start while the list is open enter with a short fade. return ArrivalScope( - ids: [for (final run in controller.visibleRuns) '${run['id']}'], + ids: [for (final run in visible) '${run['id']}'], child: _entriesList(entries, header), ); } diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart index c8fba5d6..1a93acd6 100644 --- a/app/lib/shell/adaptive_shell.dart +++ b/app/lib/shell/adaptive_shell.dart @@ -140,78 +140,81 @@ class _AdaptiveShellState extends State { ), ); }).toList(); - return ListenableBuilder( - listenable: _bar, - builder: (context, _) { - final spec = _bar.specFor(_selected); - // One floating glass tab bar at every width: full width on a phone, - // sized to its tabs at the right edge on a wide window (the bar judges - // that itself, live). Content keeps the whole width and scrolls behind - // it, learning the bar's height as its bottom media padding. Neither - // scaffold's structure depends on the width, so resizing never - // remounts a destination. - // - // While the tab shows its list beside an open item the bar keeps - // the same place, bottom right near the thumb: the item pane learns - // the bar's height (see ListDetailPanes) and floats its own tabs or - // composer above it, so the two never overlap. - final split = _bar.split(_selected); - final bar = FloatingDestinationBar( - cupertino: widget.cupertino, - currentIndex: index, - onTap: (value) => _select(shellTabDestinations[value]), - items: _destinationItems(), - ); - // Destinations reach the top edge and scroll behind the floating top - // bar too: each learns the bar's height as its top media padding and - // pads its own lists by it (see withTopBarClearance). - final topBar = _ListPaneBar( - split: split, - bar: _segmentedBar(spec, details.label, page: page), - ); - // The scaffolds below swap the system insets for their bars' - // heights; panes beside a list read the real ones from here. - final system = MediaQuery.paddingOf(context); - // A page (Settings) closes to Pipelines on the system Back too. The - // scope is always there, so opening the page never remounts the shell. - Widget backable(Widget child) => PopScope( - canPop: !page, - onPopInvokedWithResult: (didPop, _) { - if (!didPop) _closePage(); - }, - child: child, - ); - if (widget.cupertino) { - return backable( - ShellSystemInsets( - padding: system, - child: CupertinoPageScaffold( - navigationBar: topBar, - child: SafeArea( - top: false, - bottom: false, - child: FloatingBarOverlay( - bar: bar, - child: _destinationStack(contents), - ), - ), + // Only the bar shows the registry's state, so a published bar or badge + // rebuilds its bar alone; the destinations and scaffold stay as built. + _bar.focus = _selected; + // One floating glass tab bar at every width: full width on a phone, + // sized to its tabs at the right edge on a wide window (the bar judges + // that itself, live). Content keeps the whole width and scrolls behind + // it, learning the bar's height as its bottom media padding. Neither + // scaffold's structure depends on the width, so resizing never + // remounts a destination. + // + // While the tab shows its list beside an open item the bar keeps + // the same place, bottom right near the thumb: the item pane learns + // the bar's height (see ListDetailPanes) and floats its own tabs or + // composer above it, so the two never overlap. + final bar = ListenableBuilder( + listenable: _bar.badges, + builder: (context, _) => FloatingDestinationBar( + cupertino: widget.cupertino, + currentIndex: index, + onTap: (value) => _select(shellTabDestinations[value]), + items: _destinationItems(), + ), + ); + // Destinations reach the top edge and scroll behind the floating top + // bar too: each learns the bar's height as its top media padding and + // pads its own lists by it (see withTopBarClearance). + SegmentedBar currentBar() => + _segmentedBar(_bar.specFor(_selected), details.label, page: page); + final topBar = _ListPaneBar( + listenable: _bar.bar, + initial: currentBar(), + split: () => _bar.split(_selected), + bar: currentBar, + ); + // The scaffolds below swap the system insets for their bars' + // heights; panes beside a list read the real ones from here. + final system = MediaQuery.paddingOf(context); + // A page (Settings) closes to Pipelines on the system Back too. The + // scope is always there, so opening the page never remounts the shell. + Widget backable(Widget child) => PopScope( + canPop: !page, + onPopInvokedWithResult: (didPop, _) { + if (!didPop) _closePage(); + }, + child: child, + ); + if (widget.cupertino) { + return backable( + ShellSystemInsets( + padding: system, + child: CupertinoPageScaffold( + navigationBar: topBar, + child: SafeArea( + top: false, + bottom: false, + child: FloatingBarOverlay( + bar: bar, + child: _destinationStack(contents), ), ), - ); - } - return backable( - ShellSystemInsets( - padding: system, - child: Scaffold( - extendBodyBehindAppBar: true, - appBar: topBar, - body: _destinationStack(contents), - extendBody: true, - bottomNavigationBar: bar, - ), ), - ); - }, + ), + ); + } + return backable( + ShellSystemInsets( + padding: system, + child: Scaffold( + extendBodyBehindAppBar: true, + appBar: topBar, + body: _destinationStack(contents), + extendBody: true, + bottomNavigationBar: bar, + ), + ), ); } @@ -328,24 +331,38 @@ class _AdaptiveShellState extends State { /// beside an open item ([ShellPaneSplit]); the item's own bar takes the rest /// of the same row. The bar keeps its place in the scaffold either way, so a /// split never remounts it. +/// +/// It rebuilds itself when [listenable] (the focused destination's published +/// bar) changes; [initial] supplies the size and obstruction, which do not +/// depend on the published contents. class _ListPaneBar extends StatelessWidget implements ObstructingPreferredSizeWidget { - const _ListPaneBar({required this.split, required this.bar}); + const _ListPaneBar({ + required this.listenable, + required this.initial, + required this.split, + required this.bar, + }); - final bool split; - final SegmentedBar bar; + final Listenable listenable; + final SegmentedBar initial; + final bool Function() split; + final SegmentedBar Function() bar; @override - Size get preferredSize => bar.preferredSize; + Size get preferredSize => initial.preferredSize; @override bool shouldFullyObstruct(BuildContext context) => - bar.shouldFullyObstruct(context); + initial.shouldFullyObstruct(context); @override - Widget build(BuildContext context) => ListPaneWidth( - split: split, - alignment: AlignmentDirectional.topStart, - child: bar, + Widget build(BuildContext context) => ListenableBuilder( + listenable: listenable, + builder: (context, _) => ListPaneWidth( + split: split(), + alignment: AlignmentDirectional.topStart, + child: bar(), + ), ); } diff --git a/app/lib/shell/shell_bar.dart b/app/lib/shell/shell_bar.dart index e621426b..1324e64c 100644 --- a/app/lib/shell/shell_bar.dart +++ b/app/lib/shell/shell_bar.dart @@ -53,9 +53,37 @@ class ShellBarSpec { } /// The bar contents each tab's open screen has published. +/// +/// It notifies its own listeners of every visible change. A host that shows +/// one destination's bar at a time sets [focus] and may listen to [bar] and +/// [badges] separately: a hidden tab republishing its bar (a list rebuilding +/// on a run event) then rebuilds nothing, and a badge change rebuilds only +/// the tab bar. class ShellBarRegistry extends ChangeNotifier { final Map _specs = {}; final Map<(AppDestination, ShellBadgeKind), int> _badges = {}; + final _Notifier _bar = _Notifier(); + final _Notifier _badgeNotifier = _Notifier(); + + /// The destination whose bar is on screen; null treats every destination + /// as shown. Bar changes of other destinations are kept without notifying: + /// the host rebuilds when it changes the focus. + AppDestination? focus; + + /// Notifies when the focused destination's bar spec or split changes. + Listenable get bar => _bar; + + /// Notifies when any tab badge count changes. + Listenable get badges => _badgeNotifier; + + bool _shown(AppDestination destination) => + focus == null || focus == destination; + + void _barChanged(AppDestination destination) { + if (!_shown(destination)) return; + _bar.notify(); + notifyListeners(); + } final Map _splits = {}; @@ -68,7 +96,7 @@ class ShellBarRegistry extends ChangeNotifier { if (_disposed) return; final before = split(destination); _splits[destination] = (_splits[destination] ?? 0) + (value ? 1 : -1); - if (split(destination) != before) notifyListeners(); + if (split(destination) != before) _barChanged(destination); } /// The count a tab's screen published for [kind], 0 when none. @@ -78,6 +106,7 @@ class ShellBarRegistry extends ChangeNotifier { void _setBadge(AppDestination destination, ShellBadgeKind kind, int count) { if (_disposed || badge(destination, kind) == count) return; _badges[(destination, kind)] = count; + _badgeNotifier.notify(); notifyListeners(); } @@ -86,6 +115,8 @@ class ShellBarRegistry extends ChangeNotifier { @override void dispose() { _disposed = true; + _bar.dispose(); + _badgeNotifier.dispose(); super.dispose(); } @@ -99,17 +130,21 @@ class ShellBarRegistry extends ChangeNotifier { // A screen's update can land after the shell itself has gone. if (_disposed) return; _specs[destination] = (owner, spec); - notifyListeners(); + _barChanged(destination); } void _clear(AppDestination destination, Object owner) { if (_disposed) return; if (_specs[destination]?.$1 != owner) return; _specs.remove(destination); - notifyListeners(); + _barChanged(destination); } } +class _Notifier extends ChangeNotifier { + void notify() => notifyListeners(); +} + /// Places one tab's content under the shell's bar registry. class ShellBarScope extends InheritedWidget { const ShellBarScope({ diff --git a/app/lib/ui/text/relative_time_clock.dart b/app/lib/ui/text/relative_time_clock.dart new file mode 100644 index 00000000..2f532fb2 --- /dev/null +++ b/app/lib/ui/text/relative_time_clock.dart @@ -0,0 +1,105 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +/// One minute clock shared by every relative-time label. +/// +/// A list of rows used to run one timer per row; this clock runs a single +/// timer, aligned to the start of each wall-clock minute, only while some +/// label listens and the app is visible. Labels re-read [now] when it +/// notifies and rebuild only if their text changed. +class RelativeTimeClock extends ChangeNotifier with WidgetsBindingObserver { + RelativeTimeClock(); + + /// The clock the app's labels share. + static final RelativeTimeClock shared = RelativeTimeClock(); + + DateTime _now = DateTime.now(); + Timer? _timer; + bool _observing = false; + bool _hidden = false; + + /// The clock's current minute-resolution time. It advances by the elapsed + /// delay on each tick, which keeps it consistent under a fake clock. + DateTime get now => _now; + + /// Whether a tick is scheduled (a label listens and the app is visible). + @visibleForTesting + bool get ticking => _timer != null; + + @override + void addListener(VoidCallback listener) { + final first = !hasListeners; + super.addListener(listener); + if (!first) return; + _now = DateTime.now(); + _hidden = switch (WidgetsBinding.instance.lifecycleState) { + AppLifecycleState.hidden || + AppLifecycleState.paused || + AppLifecycleState.detached => true, + _ => false, + }; + if (!_observing) { + WidgetsBinding.instance.addObserver(this); + _observing = true; + } + _schedule(); + } + + @override + void removeListener(VoidCallback listener) { + super.removeListener(listener); + if (hasListeners) return; + _stop(); + if (_observing) { + WidgetsBinding.instance.removeObserver(this); + _observing = false; + } + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) { + _hidden = false; + _now = DateTime.now(); + notifyListeners(); + _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() { + _timer?.cancel(); + _timer = null; + if (_hidden || !hasListeners) return; + final intoMinute = Duration( + seconds: _now.second, + milliseconds: _now.millisecond, + microseconds: _now.microsecond, + ); + final delay = const Duration(minutes: 1) - intoMinute; + _timer = Timer(delay, () { + _timer = null; + _now = _now.add(delay); + notifyListeners(); + _schedule(); + }); + } + + void _stop() { + _timer?.cancel(); + _timer = null; + } + + @override + void dispose() { + _stop(); + if (_observing) WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } +} diff --git a/app/lib/ui/text/relative_time_label.dart b/app/lib/ui/text/relative_time_label.dart index 8851e300..ade282ed 100644 --- a/app/lib/ui/text/relative_time_label.dart +++ b/app/lib/ui/text/relative_time_label.dart @@ -1,93 +1,79 @@ -import 'dart:async'; - import 'package:flutter/widgets.dart'; import 'relative_time.dart'; +import 'relative_time_clock.dart'; -/// A relative-time label that rebuilds only itself when its formatter can -/// change. It stops its timer while the app is backgrounded. +/// A relative-time label that rebuilds only itself, and only when its text +/// changes. Every label follows one shared minute [RelativeTimeClock] rather +/// than a timer of its own; a label whose tickers are muted (an offstage tab +/// or a covered route) skips the ticks and catches up when shown again. class RelativeTimeLabel extends StatefulWidget { - const RelativeTimeLabel({super.key, required this.instant, this.now}); + const RelativeTimeLabel({ + super.key, + required this.instant, + this.now, + this.clock, + }); final DateTime? instant; + + /// The time the label starts from; the shared clock advances it. final DateTime? now; + /// The clock to follow; [RelativeTimeClock.shared] when null. + final RelativeTimeClock? clock; + @override State createState() => _RelativeTimeLabelState(); } -class _RelativeTimeLabelState extends State - with WidgetsBindingObserver { - Timer? _timer; - DateTime _now = DateTime.now(); +class _RelativeTimeLabelState extends State { + late RelativeTimeClock _clock; + late DateTime _now; + bool _shown = true; + bool _stale = false; @override void initState() { super.initState(); - WidgetsBinding.instance.addObserver(this); - _schedule(); + _now = widget.now ?? DateTime.now(); + _clock = widget.clock ?? RelativeTimeClock.shared; + _clock.addListener(_tick); } @override void didUpdateWidget(RelativeTimeLabel oldWidget) { super.didUpdateWidget(oldWidget); - if (oldWidget.instant != widget.instant) _schedule(); + final clock = widget.clock ?? RelativeTimeClock.shared; + if (clock == _clock) return; + _clock.removeListener(_tick); + _clock = clock..addListener(_tick); } @override - void didChangeAppLifecycleState(AppLifecycleState state) { - if (state == AppLifecycleState.resumed) { - _now = DateTime.now(); - if (mounted) setState(() {}); - _schedule(current: _now); - } else if (state == AppLifecycleState.hidden || - // Not inactive: a desktop window that lost focus is still visible. - state == AppLifecycleState.paused || - state == AppLifecycleState.detached) { - _timer?.cancel(); - _timer = null; - } + void didChangeDependencies() { + super.didChangeDependencies(); + _shown = TickerMode.valuesOf(context).enabled; + if (_shown && _stale) _advance(); } - void _schedule({DateTime? current}) { - _timer?.cancel(); - final instant = widget.instant; - if (instant == null) return; - final now = current ?? widget.now ?? DateTime.now(); - _now = now; - final next = _nextBoundary(instant, now); - final delay = next.difference(now); - _timer = Timer(delay.isNegative ? Duration.zero : delay, () { - if (!mounted) return; - _now = _now.add(delay); - setState(() {}); - _schedule(current: _now); - }); + /// Moves to the clock's time; true when the text changed. + bool _advance() { + _stale = false; + final next = _clock.now; + if (!next.isAfter(_now)) return false; + final before = formatRelativeTime(widget.instant, now: _now); + _now = next; + return formatRelativeTime(widget.instant, now: _now) != before; } - DateTime _nextBoundary(DateTime instant, DateTime now) { - final difference = now.difference(instant); - final age = difference.abs(); - final unit = age < const Duration(hours: 1) - ? const Duration(minutes: 1) - : age < const Duration(days: 1) - ? const Duration(hours: 1) - : age < const Duration(days: 7) - ? const Duration(days: 1) - : null; - if (unit != null) { - final units = age.inMilliseconds ~/ unit.inMilliseconds; - final boundary = difference.isNegative - // Future labels use a decreasing count. Add a second so an exact - // boundary does not immediately schedule another zero-delay timer. - ? instant.subtract(unit * units).add(const Duration(seconds: 1)) - : instant.add(unit * (units + 1)); - if (boundary.isAfter(now)) return boundary; + void _tick() { + if (!mounted || widget.instant == null) return; + if (!_shown) { + _stale = true; + return; } - final midnight = DateTime(now.year, now.month, now.day + 1); - return midnight.isAfter(now) - ? midnight - : now.add(const Duration(minutes: 1)); + if (_advance()) setState(() {}); } @override @@ -102,8 +88,7 @@ class _RelativeTimeLabelState extends State @override void dispose() { - _timer?.cancel(); - WidgetsBinding.instance.removeObserver(this); + _clock.removeListener(_tick); super.dispose(); } } diff --git a/app/test/perf/background_work_bench_test.dart b/app/test/perf/background_work_bench_test.dart new file mode 100644 index 00000000..fc924bb7 --- /dev/null +++ b/app/test/perf/background_work_bench_test.dart @@ -0,0 +1,239 @@ +// Measures wasted background work outside the chat transcript: timers kept +// alive by list rows, rebuilds per minute tick, offstage tabs' work and the +// rebuilds a burst of run events causes. Each scenario prints its numbers +// (`BENCH ...`) and asserts the budgets the shared clock and the narrowed +// notifications keep. +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/runs_controller.dart'; +import 'package:pipelines_app/features/runs/ui/runs_list.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:pipelines_app/ui/adaptive/floating_destination_bar.dart'; +import 'package:pipelines_app/ui/text/relative_time_label.dart'; + +class _Gateway implements ApiGateway { + final controller = StreamController.broadcast(sync: true); + List runs = []; + + @override + Stream get frames => controller.stream; + + @override + Future call(String type, [JsonMap fields = const {}]) async => { + 'runs': [for (final run in runs) Map.of(run)], + }; +} + +/// Counts element rebuilds by widget type while installed. +class _Rebuilds { + final Map counts = {}; + void install() => debugOnRebuildDirtyWidget = (element, _) => counts.update( + element.widget.runtimeType, + (n) => n + 1, + ifAbsent: () => 1, + ); + void uninstall() => debugOnRebuildDirtyWidget = null; + int of(Type type) => counts[type] ?? 0; + int get total => counts.values.fold(0, (a, b) => a + b); + void reset() => counts.clear(); +} + +/// Tracks every Timer created in its zone (one-shot and periodic). +class _Timers { + final List created = []; + int get active => created.where((t) => t.isActive).length; + late final ZoneSpecification spec = ZoneSpecification( + createTimer: (self, parent, zone, duration, f) { + final timer = parent.createTimer(zone, duration, f); + created.add(timer); + return timer; + }, + createPeriodicTimer: (self, parent, zone, period, f) { + final timer = parent.createPeriodicTimer(zone, period, f); + created.add(timer); + return timer; + }, + ); +} + +List _runs(int count, DateTime now) => [ + for (var i = 0; i < count; i++) + { + 'id': i + 1, + 'name': 'Pipeline ${i % 7}', + 'title': 'Run ${i + 1}', + 'status': i < 20 ? 'running' : 'succeeded', + 'executing': i < 20, + 'completed_steps': 1, + // The lifecycle fields a server list row carries. + 'notify_mode': 'auto', + 'resource_wait': null, + 'cancel_requested': false, + 'cleanup_unconfirmed': false, + // Every 20 seconds back: the newest rows change label each minute. + 'created_at': now.subtract(Duration(seconds: 20 * i)).toIso8601String(), + }, +]; + +void main() { + late _Gateway gateway; + late RunsController controller; + final rebuilds = _Rebuilds(); + + setUp(() async { + gateway = _Gateway()..runs = _runs(300, DateTime.now()); + controller = RunsController(RunsRepository(gateway)); + controller.listen(gateway.frames); + await controller.load(); + }); + + tearDown(() async { + rebuilds.uninstall(); + controller.dispose(); + await gateway.controller.close(); + }); + + Widget shell(AppDestination destination) => MaterialApp( + home: AdaptiveShell( + destination: destination, + destinationBodies: { + AppDestination.runs: (_) => AnimatedBuilder( + animation: controller, + builder: (_, _) => + RunsList(controller: controller, onSelected: (_) {}), + ), + AppDestination.pipelines: (_) => const Center(child: Text('pipelines')), + }, + ), + ); + + /// Sends frame [i] of a busy stream: most frames repeat a running row's + /// current state; every fifth advances its step count. + void frame(int i) { + final id = 1 + i % 20; + final row = gateway.runs[id - 1]; + if (i % 5 == 0) row['completed_steps'] = 2 + i; + gateway.controller.add({ + 'type': 'run_event', + 'run_id': id, + 'status': 'running', + 'completed_steps': row['completed_steps'], + }); + } + + Future sizeView(WidgetTester tester) async { + tester.view.physicalSize = const Size(400, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + } + + testWidgets('300-run list: timers and rebuilds per minute tick', ( + tester, + ) async { + await sizeView(tester); + final timers = _Timers(); + await runZoned(zoneSpecification: timers.spec, () async { + await tester.pumpWidget(shell(AppDestination.runs)); + await tester.pump(); + final labels = find.byType(RelativeTimeLabel).evaluate().length; + final active = timers.active; + // Measure one whole minute after the first tick, wherever it falls. + await tester.pump(const Duration(minutes: 1)); + await tester.pump(); + final created = timers.created.length; + rebuilds + ..reset() + ..install(); + await tester.pump(const Duration(minutes: 1)); + await tester.pump(); + final perMinute = timers.created.length - created; + rebuilds.uninstall(); + // ignore: avoid_print + print( + 'BENCH list300 mountedLabels=$labels activeTimers=$active ' + 'labelRebuildsPerMinute=${rebuilds.of(RelativeTimeLabel)} ' + 'totalRebuildsPerMinute=${rebuilds.total} ' + 'timersScheduledPerMinute=$perMinute', + ); + expect(active, lessThanOrEqualTo(1)); + await tester.pumpWidget(const SizedBox()); + expect(timers.active, 0); + }); + }); + + testWidgets('offstage Runs tab: minute ticks and run events', (tester) async { + await sizeView(tester); + final timers = _Timers(); + await runZoned(zoneSpecification: timers.spec, () async { + await tester.pumpWidget(shell(AppDestination.runs)); + await tester.pump(); + await tester.pumpWidget(shell(AppDestination.pipelines)); + await tester.pump(const Duration(seconds: 1)); // fade-through done + final active = timers.active; + rebuilds + ..reset() + ..install(); + await tester.pump(const Duration(minutes: 2)); + await tester.pump(); + final tick = rebuilds.of(RelativeTimeLabel); + rebuilds.reset(); + for (var i = 0; i < 50; i++) { + frame(i); + await tester.pump(); + } + await tester.pump(); + rebuilds.uninstall(); + // ignore: avoid_print + print( + 'BENCH offstage activeTimers=$active labelRebuildsIn2Minutes=$tick ' + 'burst50: runsListRebuilds=${rebuilds.of(RunsList)} ' + 'shellBarRebuilds=${rebuilds.of(FloatingDestinationBar)} ' + 'totalRebuilds=${rebuilds.total}', + ); + expect(tick, 0); + expect(rebuilds.of(FloatingDestinationBar), 0); + await tester.pumpWidget(const SizedBox()); + expect(timers.active, 0); + }); + }); + + testWidgets('visible Runs tab: a 50-frame run_event burst', (tester) async { + await sizeView(tester); + var notifications = 0; + controller.addListener(() => notifications++); + await tester.pumpWidget(shell(AppDestination.runs)); + await tester.pump(); + rebuilds + ..reset() + ..install(); + // Frames arrive between frames on a real socket: pump after each. + for (var i = 0; i < 50; i++) { + frame(i); + await tester.pump(); + } + await tester.pump(); + rebuilds.uninstall(); + // ignore: avoid_print + print( + 'BENCH visibleBurst50 controllerNotifications=$notifications ' + 'runsListRebuilds=${rebuilds.of(RunsList)} ' + 'runRowRebuilds=${rebuilds.of(RunListRow)} ' + 'shellBarRebuilds=${rebuilds.of(FloatingDestinationBar)} ' + 'totalRebuilds=${rebuilds.total}', + ); + final top = rebuilds.counts.entries.toList() + ..sort((a, b) => b.value - a.value); + // ignore: avoid_print + print( + 'BENCH top ${top.take(15).map((e) => '${e.key}=${e.value}').join(' ')}', + ); + // Only the ten frames that advance a step change anything visible. + expect(notifications, lessThanOrEqualTo(10)); + await tester.pumpWidget(const SizedBox()); + }); +} diff --git a/app/test/ui/text/relative_time_label_test.dart b/app/test/ui/text/relative_time_label_test.dart index 70c8474a..f3071240 100644 --- a/app/test/ui/text/relative_time_label_test.dart +++ b/app/test/ui/text/relative_time_label_test.dart @@ -1,45 +1,96 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/text/relative_time.dart'; +import 'package:pipelines_app/ui/text/relative_time_clock.dart'; import 'package:pipelines_app/ui/text/relative_time_label.dart'; +/// The start of the current wall-clock minute, where the shared clock ticks. +DateTime _minute() { + final now = DateTime.now(); + return DateTime(now.year, now.month, now.day, now.hour, now.minute); +} + void main() { - testWidgets('updates at the next relative-time boundary', (tester) async { - final instant = DateTime.now().subtract(const Duration(minutes: 4)); + final clock = RelativeTimeClock.shared; + + testWidgets('updates on the next minute tick', (tester) async { + final instant = _minute().subtract(const Duration(minutes: 4)); await tester.pumpWidget( MaterialApp(home: RelativeTimeLabel(instant: instant)), ); expect(find.text('4m'), findsOneWidget); - await tester.pump(const Duration(minutes: 1, seconds: 1)); + await tester.pump(const Duration(minutes: 1)); expect(find.text('5m'), findsOneWidget); }); - testWidgets('future labels schedule their next boundary', (tester) async { - final instant = DateTime.now().add(const Duration(minutes: 4)); + testWidgets('future labels count down on the ticks', (tester) async { + final instant = _minute().add( + const Duration(minutes: 4, milliseconds: 500), + ); await tester.pumpWidget( MaterialApp(home: RelativeTimeLabel(instant: instant)), ); - expect(find.text('in 3m'), findsOneWidget); + expect(find.text(formatRelativeTime(instant)!), findsOneWidget); - await tester.pump(const Duration(minutes: 1, seconds: 1)); + await tester.pump(const Duration(minutes: 2)); expect(find.text('in 2m'), findsOneWidget); }); - testWidgets('cancels its timer when disposed', (tester) async { + testWidgets('many labels share one timer, released when disposed', ( + tester, + ) async { + final instant = DateTime.now().subtract(const Duration(minutes: 4)); await tester.pumpWidget( MaterialApp( - home: RelativeTimeLabel( - instant: DateTime.now().subtract(const Duration(minutes: 4)), + home: Wrap( + children: [ + for (var i = 0; i < 50; i++) RelativeTimeLabel(instant: instant), + ], ), ), ); + expect(clock.ticking, isTrue); await tester.pumpWidget(const MaterialApp(home: SizedBox())); + expect(clock.ticking, isFalse); await tester.pump(const Duration(hours: 1)); }); + testWidgets('a muted label skips ticks and catches up when shown', ( + tester, + ) async { + final instant = _minute().subtract(const Duration(minutes: 4)); + var builds = 0; + Widget app(bool enabled) => MaterialApp( + home: TickerMode( + enabled: enabled, + child: Builder( + builder: (_) { + builds++; + return RelativeTimeLabel(instant: instant); + }, + ), + ), + ); + await tester.pumpWidget(app(false)); + final label = find.byType(RelativeTimeLabel); + var labelBuilds = 0; + debugOnRebuildDirtyWidget = (element, _) { + if (element.widget is RelativeTimeLabel) labelBuilds++; + }; + addTearDown(() => debugOnRebuildDirtyWidget = null); + await tester.pump(const Duration(minutes: 1)); + expect(labelBuilds, 0); + expect(find.descendant(of: label, matching: find.text('4m')), findsOneWidget); + + await tester.pumpWidget(app(true)); + expect(find.text('5m'), findsOneWidget); + expect(builds, 2); + }); + testWidgets('keeps ticking while inactive, pauses while hidden and ' 'refreshes on resume', (tester) async { - final instant = DateTime.now().subtract(const Duration(minutes: 4)); + final instant = _minute().subtract(const Duration(minutes: 4)); await tester.pumpWidget( MaterialApp(home: RelativeTimeLabel(instant: instant)), ); @@ -49,12 +100,13 @@ void main() { WidgetsBinding.instance.handleAppLifecycleStateChanged( AppLifecycleState.inactive, ); - await tester.pump(const Duration(minutes: 1, seconds: 1)); + await tester.pump(const Duration(minutes: 1)); expect(find.text('5m'), findsOneWidget); WidgetsBinding.instance.handleAppLifecycleStateChanged( AppLifecycleState.hidden, ); + expect(clock.ticking, isFalse); await tester.pump(const Duration(minutes: 1, seconds: 1)); expect(find.text('5m'), findsOneWidget); @@ -64,8 +116,8 @@ void main() { WidgetsBinding.instance.handleAppLifecycleStateChanged( AppLifecycleState.resumed, ); + expect(clock.ticking, isTrue); await tester.pump(); - await tester.pump(const Duration(minutes: 1, seconds: 1)); expect(find.text('5m'), findsOneWidget); }); }