From 3b996bdbc70a01e7c043680e112cf22325560d74 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sun, 1 Nov 2026 23:29:20 +0000 Subject: [PATCH 1/4] 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); }); } From 20bf6202b31e9601af4f5c09283c398cf8474cfa Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sun, 1 Nov 2026 23:41:34 +0000 Subject: [PATCH 2/4] Rebuild only the live chat turn while replies stream Reuse unchanged transcript rows, the composer bar and the header across streamed deltas, and share parsed markdown by text so rows scrolled back into view are not parsed again. Adds a rebuild/parse harness and a release-web frame-timing probe with a long-transcript fixture. --- .../chat/conversation/chat_row_widgets.dart | 74 ++++++++ .../chat/conversation/chat_thread_view.dart | 125 +++++++++----- .../ui/transcript/chat_markdown_cache.dart | 49 ++++++ .../ui/transcript/chat_markdown_view.dart | 3 +- app/notes/chat-stream-perf.md | 58 +++++++ .../conversation/chat_row_widgets_test.dart | 70 ++++++++ .../perf/chat_stream_rebuild_perf_test.dart | 159 ++++++++++++++++++ app/tool/chat_composer_probe_entry.dart | 57 ++++--- app/tool/chat_perf_fixture.dart | 82 +++++++++ app/tool/chat_perf_probe.mjs | 108 ++++++++++++ 10 files changed, 722 insertions(+), 63 deletions(-) create mode 100644 app/lib/features/chat/conversation/chat_row_widgets.dart create mode 100644 app/lib/features/chat/ui/transcript/chat_markdown_cache.dart create mode 100644 app/notes/chat-stream-perf.md create mode 100644 app/test/features/chat/conversation/chat_row_widgets_test.dart create mode 100644 app/test/features/chat/perf/chat_stream_rebuild_perf_test.dart create mode 100644 app/tool/chat_perf_fixture.dart create mode 100644 app/tool/chat_perf_probe.mjs diff --git a/app/lib/features/chat/conversation/chat_row_widgets.dart b/app/lib/features/chat/conversation/chat_row_widgets.dart new file mode 100644 index 00000000..6e105164 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_row_widgets.dart @@ -0,0 +1,74 @@ +import 'package:flutter/widgets.dart'; + +/// Reuses a built widget while the content and inputs it was built from are +/// unchanged: one per transcript row, or per piece of conversation chrome. +/// +/// Every streamed delta rebuilds the conversation, and each build makes a new +/// message widget for every row. Handing Flutter the identical widget instance +/// for an unchanged row lets it skip that row's whole subtree, so during +/// streaming only the live turn rebuilds. Inherited changes (theme, platform +/// style, text scale) still reach the reused subtree through its own +/// dependencies. +class ChatRowWidgets { + final Map _held = {}; + Set _seen = {}; + + /// The widget held for [key] when [row] and [inputs] deep-equal the ones it + /// was built from, else a fresh [build] that is held instead. + /// + /// [row] is decoded JSON (maps, lists and scalars); [inputs] are the other + /// values the row's widget depends on, compared the same way. + Widget widgetFor( + String key, + Object? row, + Object? inputs, + Widget Function() build, + ) { + _seen.add(key); + final held = _held[key]; + if (held != null && + chatJsonEquals(held.row, row) && + chatJsonEquals(held.inputs, inputs)) { + return held.widget; + } + final widget = build(); + _held[key] = (row: row, inputs: inputs, widget: widget); + return widget; + } + + /// Drops rows the last build did not ask for. Call once after each build. + void prune() { + _held.removeWhere((key, _) => !_seen.contains(key)); + _seen = {}; + } + + void clear() { + _held.clear(); + _seen = {}; + } +} + +/// Structural equality for decoded JSON. Strings shared between snapshots are +/// identical, so an unchanged transcript compares in near-constant time per +/// field. +bool chatJsonEquals(Object? a, Object? b) { + if (identical(a, b)) return true; + if (a is Map && b is Map) { + if (a.length != b.length) return false; + for (final entry in a.entries) { + if (!b.containsKey(entry.key) || + !chatJsonEquals(entry.value, b[entry.key])) { + return false; + } + } + return true; + } + if (a is List && b is List) { + if (a.length != b.length) return false; + for (var index = 0; index < a.length; index++) { + if (!chatJsonEquals(a[index], b[index])) return false; + } + return true; + } + return a == b; +} diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 654fb1a8..4abe59c5 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -26,6 +26,7 @@ import 'chat_mode_control.dart'; import 'chat_model_control.dart'; import 'chat_models.dart'; import 'chat_row_keys.dart'; +import 'chat_row_widgets.dart'; import 'chat_scroll.dart'; import 'chat_server_queue.dart'; import 'chat_thread_controller.dart'; @@ -136,6 +137,11 @@ class _ChatThreadViewState extends State { late ChatThreadController _controller = _attach(); late ChatComposerController _composer = _attachComposer(); late ChatRowKeys _rowKeys = ChatRowKeys(); + final _rowWidgets = ChatRowWidgets(); + + /// The floating bar and composer, reused while their inputs hold so a + /// streamed delta does not rebuild the conversation's chrome. + final _chrome = ChatRowWidgets(); /// Sent images' bytes for this server, cached across rebuilds and scrolling. late ChatAttachmentImages _images = ChatAttachmentImages(widget.gateway); @@ -402,6 +408,8 @@ class _ChatThreadViewState extends State { _controller = _attach(); _composer = _attachComposer(); _rowKeys = ChatRowKeys(); + _rowWidgets.clear(); + _chrome.clear(); _dismissals = ChatNoticeDismissals(); _reconnecting = false; _adoptCachedTranscript(); @@ -757,8 +765,13 @@ class _ChatThreadViewState extends State { // The transcript fills the page; the conversation's bar floats over its // top and the frosted composer over its bottom, and history scrolls // behind both. - final column = FloatingBarOverlay( - bar: ChatComposerBar( + // Every input of the composer comes from this widget's configuration, + // the composer, the images and the running state. + final composerBar = _chrome.widgetFor( + 'composer', + _controller.running, + [widget, _composer, _images], + () => ChatComposerBar( key: ValueKey('chat-composer-${widget.sessionId}'), composer: _composer, running: _controller.running, @@ -775,6 +788,9 @@ class _ChatThreadViewState extends State { syncToken: widget.syncToken, ), ), + ); + final column = FloatingBarOverlay( + bar: composerBar, child: SegmentedBarOverlay( bar: _header(context, inShellBar), child: NotificationListener( @@ -787,6 +803,24 @@ class _ChatThreadViewState extends State { // window; the margins beside it still scroll the list. final side = chatReadingInset(constraints.maxWidth); final media = MediaQuery.paddingOf(context); + final transcript = [ + for (var index = 0; index < rows.length; index++) + Padding( + key: ValueKey(keys[index]), + padding: const EdgeInsets.symmetric(horizontal: 16), + child: _transcriptRow( + rows[index], + keys[index], + onDismissCompaction: + compactionNotice != null && + chatNoticeActivityCondition(rows[index]) == + compactionNotice.condition + ? () => _dismiss(compactionNotice) + : null, + ), + ), + ]; + _rowWidgets.prune(); return Stack( children: [ // At rest the first item starts below the floating bar @@ -861,24 +895,7 @@ class _ChatThreadViewState extends State { padding: EdgeInsets.all(16), child: Text('No messages in this chat yet.'), ), - for (var index = 0; index < rows.length; index++) - Padding( - key: ValueKey(keys[index]), - padding: const EdgeInsets.symmetric( - horizontal: 16, - ), - child: _transcriptRow( - rows[index], - onDismissCompaction: - compactionNotice != null && - chatNoticeActivityCondition( - rows[index], - ) == - compactionNotice.condition - ? () => _dismiss(compactionNotice) - : null, - ), - ), + ...transcript, // Messages the server holds queued (one sent before // a reload, or from another device) follow the // transcript: none has reached the harness yet. @@ -952,15 +969,29 @@ class _ChatThreadViewState extends State { /// the model and mode controls. Widget _header(BuildContext context, bool inShellBar) { final session = widget.session; + final canGoBack = inShellBar + ? ModalRoute.of(context)?.impliesAppBarDismissal ?? false + : true; + final answeredBy = latestReplyModel(_controller.messages); + return _chrome.widgetFor('header', answeredBy, [ + widget, + inShellBar, + canGoBack, + ], () => _buildHeader(session, inShellBar, canGoBack, answeredBy)); + } + + Widget _buildHeader( + JsonMap? session, + bool inShellBar, + bool canGoBack, + String answeredBy, + ) { final hasModel = session != null && supportsChatModels('${session['backend'] ?? ''}'); // The mode control has nothing to show (or change) without both facts. final hasMode = '${session?['mode'] ?? ''}'.trim().isNotEmpty && '${session?['mode_name'] ?? ''}'.trim().isNotEmpty; - final canGoBack = inShellBar - ? ModalRoute.of(context)?.impliesAppBarDismissal ?? false - : true; final directory = '${session?['directory'] ?? ''}'.trim(); final folder = directory .split(RegExp(r'[/\\]')) @@ -991,7 +1022,7 @@ class _ChatThreadViewState extends State { sessionId: widget.sessionId, session: session, onChanged: widget.onModelChanged, - answeredBy: latestReplyModel(_controller.messages), + answeredBy: answeredBy, ), ), if (hasMode) @@ -1061,7 +1092,11 @@ class _ChatThreadViewState extends State { }); } - Widget _transcriptRow(JsonMap row, {VoidCallback? onDismissCompaction}) { + Widget _transcriptRow( + JsonMap row, + String key, { + VoidCallback? onDismissCompaction, + }) { final kind = '${row['kind'] ?? ''}'; if (kind == 'activity') { return _ChatActivityLine(row: row, onDismiss: onDismissCompaction); @@ -1090,20 +1125,32 @@ class _ChatThreadViewState extends State { final delivery = message != null ? _composer.deliveries.stateFor(message) : null; - return ChatMessageView( - row: row, - textBuilder: chatMarkdownText, - footer: [ - ...chips, - if (delivery != null) - ChatDeliveryIndicator( - state: delivery, - cupertino: - chatControlsStyleOf(context) == ChatControlsStyle.cupertino, - onRemove: _removeAction('${message?['operation_id'] ?? ''}'), - ), - ], - images: _images, + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final onRemove = _removeAction('${message?['operation_id'] ?? ''}'); + // An unchanged finished row hands back its previous widget, so a streamed + // delta rebuilds only the live turn. Transcript snapshots are copied on + // write, never mutated, so a deep-equal row is the same content. Permission + // chips carry objects that compare by identity, so a row with chips is + // always rebuilt. + return _rowWidgets.widgetFor( + key, + row, + [delivery, cupertino, onRemove != null, _images, _controller, _composer], + () => ChatMessageView( + row: row, + textBuilder: chatMarkdownText, + footer: [ + ...chips, + if (delivery != null) + ChatDeliveryIndicator( + state: delivery, + cupertino: cupertino, + onRemove: onRemove, + ), + ], + images: _images, + ), ); } diff --git a/app/lib/features/chat/ui/transcript/chat_markdown_cache.dart b/app/lib/features/chat/ui/transcript/chat_markdown_cache.dart new file mode 100644 index 00000000..a591b402 --- /dev/null +++ b/app/lib/features/chat/ui/transcript/chat_markdown_cache.dart @@ -0,0 +1,49 @@ +import 'dart:collection'; + +import 'chat_markdown.dart'; + +/// Parsed markdown blocks shared by every markdown view, keyed by the text. +/// +/// A lazily built transcript disposes rows scrolled out of view, so scrolling +/// back would parse the same answer again. Blocks are immutable and depend on +/// the text alone, so one parse serves every later view of that text. Bounded +/// by entries and by held characters, evicting the least recently used first, +/// so a long streamed reply's intermediate texts cannot grow it without limit. +class ChatMarkdownCache { + ChatMarkdownCache({this.maxEntries = 400, this.maxChars = 1000000}); + + final int maxEntries; + final int maxChars; + + /// Least recently used first. + final LinkedHashMap> _blocks = LinkedHashMap(); + int _chars = 0; + + /// How many texts were actually parsed (cache misses). + int parses = 0; + + List blocksFor(String text) { + final held = _blocks.remove(text); + if (held != null) return _blocks[text] = held; + final blocks = List.unmodifiable(parseMarkdown(text)); + parses++; + if (text.length > maxChars) return blocks; + _blocks[text] = blocks; + _chars += text.length; + while (_blocks.length > maxEntries || _chars > maxChars) { + final oldest = _blocks.keys.first; + _blocks.remove(oldest); + _chars -= oldest.length; + } + return blocks; + } + + void clear() { + _blocks.clear(); + _chars = 0; + parses = 0; + } +} + +/// The one cache the transcript's markdown views share. +final chatMarkdownCache = ChatMarkdownCache(); diff --git a/app/lib/features/chat/ui/transcript/chat_markdown_view.dart b/app/lib/features/chat/ui/transcript/chat_markdown_view.dart index 9119ce7d..5f5b15d8 100644 --- a/app/lib/features/chat/ui/transcript/chat_markdown_view.dart +++ b/app/lib/features/chat/ui/transcript/chat_markdown_view.dart @@ -6,6 +6,7 @@ import 'package:flutter/semantics.dart'; import '../../../../ui/adaptive/host.dart'; import '../sessions/chat_adaptive.dart'; import 'chat_markdown.dart'; +import 'chat_markdown_cache.dart'; import 'chat_message_bubble.dart'; /// Renders one assistant text part with native text widgets and the host's own @@ -68,7 +69,7 @@ class _ChatMarkdownViewState extends State { final cupertino = chatControlsStyleOf(context) == ChatControlsStyle.cupertino; final gap = chatParagraphGap(context); - final blocks = parseMarkdown(widget.text); + final blocks = chatMarkdownCache.blocksFor(widget.text); return _rendered = _selectable( context, Column( diff --git a/app/notes/chat-stream-perf.md b/app/notes/chat-stream-perf.md new file mode 100644 index 00000000..5d765f9b --- /dev/null +++ b/app/notes/chat-stream-perf.md @@ -0,0 +1,58 @@ +# Chat thread streaming performance + +Measurement-led round on the chat thread while replies stream and while long +transcripts scroll. No behaviour change. + +## Changes + +- `ChatRowWidgets` (`lib/features/chat/conversation/chat_row_widgets.dart`) + hands back a row's previous `ChatMessageView` while the row deep-equals the + one it was built from (and delivery state, platform style, remove action, + images, controller and composer are unchanged). Snapshots are copy-on-write, + so Flutter skips every finished row's subtree. Rows with permission chips + always rebuild, because those objects compare by identity. +- The composer bar and the floating header are reused the same way while the + thread widget, running state and latest reply model hold. +- `ChatMarkdownCache` (`lib/features/chat/ui/transcript/chat_markdown_cache.dart`) + shares parsed blocks by text, bounded to 400 entries and 1M characters, so a + row scrolled back into view is not parsed again. + +Already in place and left unchanged: `ListView(children:)` lays out lazily +(SliverChildListDelegate) with a `RepaintBoundary` and a stable key for each row. +Thumbnails decode at display size (`ResizeImage`). Activity timers run only on +the streaming turn. + +## Numbers + +Widget harness `test/features/chat/perf/chat_stream_rebuild_perf_test.dart` +streams 200 deltas into a 300-message transcript (debug VM, so compare the +numbers with each other only): + +| | before | after | +| --- | --- | --- | +| ChatMessageView builds | 856 | 200 | +| all widget builds | 83,888 | 20,018 | +| markdown parses while streaming | 200 | 200 (live turn only) | +| frame time per delta (mean / p90) | 7.3 / 10.8 ms | 4.8 / 5.7 ms | +| markdown parses, 80 scroll drags | 43 | 0 | + +Release web probe `node tool/chat_perf_probe.mjs 300 200` (built from +`tool/chat_composer_probe_entry.dart`; headless Chrome renders in software). +Three runs of each, Flutter FrameTiming: + +| | before | after | +| --- | --- | --- | +| streaming build mean | 9.1–10.5 ms | 6.0–6.4 ms | +| streaming build p90 | 14.6–17.4 ms | 7.2–8.5 ms | +| streaming total frame mean | 67–72 ms | 45–50 ms | +| scrolling build mean | 2.5–2.8 ms | 1.6–2.8 ms (within noise) | + +## Findings left open + +- Opening a 300-message transcript builds every row once: jumping to the end of + a top-anchored `SliverList` has to lay out each row in between (~150 parses, + about 0.9 s in the debug harness). A bottom-anchored (reversed) list would + avoid that, but it changes the scroll-restore and follow logic, so it needs a + separate change. +- The fixture logs a `_PlatformViewPlaceholderBox.getTransformTo` null-check + error on web with a long transcript. It also happens before this change. diff --git a/app/test/features/chat/conversation/chat_row_widgets_test.dart b/app/test/features/chat/conversation/chat_row_widgets_test.dart new file mode 100644 index 00000000..93065079 --- /dev/null +++ b/app/test/features/chat/conversation/chat_row_widgets_test.dart @@ -0,0 +1,70 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_row_widgets.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown_cache.dart'; + +void main() { + test('chatJsonEquals compares decoded JSON structurally', () { + expect( + chatJsonEquals( + { + 'a': [ + 1, + 'x', + {'b': true}, + ], + }, + { + 'a': [ + 1, + 'x', + {'b': true}, + ], + }, + ), + isTrue, + ); + expect(chatJsonEquals({'a': 1}, {'a': 2}), isFalse); + expect(chatJsonEquals({'a': 1}, {'b': 1}), isFalse); + expect(chatJsonEquals([1, 2], [1, 2, 3]), isFalse); + expect(chatJsonEquals({'a': null}, {}), isFalse); + }); + + test('ChatRowWidgets reuses a widget until its row or inputs change', () { + final rows = ChatRowWidgets(); + var builds = 0; + Widget build() { + builds++; + return SizedBox(width: builds.toDouble()); + } + + final first = rows.widgetFor('k', {'text': 'a'}, [1], build); + expect(rows.widgetFor('k', {'text': 'a'}, [1], build), same(first)); + expect(builds, 1); + expect(rows.widgetFor('k', {'text': 'b'}, [1], build), isNot(same(first))); + final second = rows.widgetFor('k', {'text': 'b'}, [2], build); + expect(builds, 3); + rows.prune(); + // A row the last build did not ask for is forgotten. + rows.prune(); + expect(rows.widgetFor('k', {'text': 'b'}, [2], build), isNot(same(second))); + expect(builds, 4); + }); + + test('ChatMarkdownCache parses a text once and stays bounded', () { + final cache = ChatMarkdownCache(maxEntries: 2, maxChars: 100); + final blocks = cache.blocksFor('# One'); + expect(cache.blocksFor('# One'), same(blocks)); + expect(cache.parses, 1); + cache.blocksFor('two'); + cache.blocksFor('three'); + // The least recently used text was evicted and parses again. + expect(cache.blocksFor('# One'), isNot(same(blocks))); + expect(cache.parses, 4); + // A text larger than the character budget is parsed but never held. + final long = 'x' * 200; + cache.blocksFor(long); + cache.blocksFor(long); + expect(cache.parses, 6); + }); +} diff --git a/app/test/features/chat/perf/chat_stream_rebuild_perf_test.dart b/app/test/features/chat/perf/chat_stream_rebuild_perf_test.dart new file mode 100644 index 00000000..c6e30703 --- /dev/null +++ b/app/test/features/chat/perf/chat_stream_rebuild_perf_test.dart @@ -0,0 +1,159 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart' as widgets; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown_cache.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown_view.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_message_view.dart'; + +import '../conversation/chat_thread_fixtures.dart'; + +/// Measurement harness: streams 200 text deltas into a 300-message transcript +/// and counts message builds, markdown builds/parses and per-delta frame time; +/// then scrolls the long transcript up and back down. +const _messages = 300; +const _deltas = 200; + +String _answer(int index) => + '## Answer $index\n\nSome **bold** text with `code` and a ' + '[link](https://example.com/$index).\n\n' + '```dart\n' + '${List.generate(30, (line) => 'final v$line = $index * $line;').join('\n')}' + '\n```\n\n' + '- one\n- two\n- three\n'; + +List _transcript() => [ + for (var index = 0; index < _messages; index++) + // The newest message is the operator's, so the reply opens a new turn. + index.isOdd + ? chatMessage( + 'u$index', + 'user', + parts: [ + {'type': 'text', 'text': 'Question $index'}, + ], + ) + : chatMessage( + 'a$index', + 'assistant', + parts: [ + {'type': 'text', 'id': 't$index', 'text': _answer(index)}, + ], + ), +]; + +Future _open(WidgetTester tester) async { + tester.view.physicalSize = const Size(1000, 1600); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => chatPage(_transcript()); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + ), + ), + ); + final watch = Stopwatch()..start(); + await tester.pumpAndSettle(); + watch.stop(); + // ignore: avoid_print + print( + 'PERF open: parses=${chatMarkdownCache.parses} ' + 'settleMs=${watch.elapsedMilliseconds}', + ); + return gateway; +} + +String _stats(List samples) { + final sorted = [...samples]..sort(); + final mean = sorted.reduce((a, b) => a + b) / sorted.length; + return 'meanUs=${mean.round()} p50Us=${sorted[sorted.length ~/ 2]} ' + 'p90Us=${sorted[sorted.length * 9 ~/ 10]} maxUs=${sorted.last}'; +} + +void main() { + setUp(chatMarkdownCache.clear); + testWidgets('streaming deltas rebuild only the live turn', (tester) async { + final gateway = await _open(tester); + var messageBuilds = 0; + var markdownBuilds = 0; + var totalBuilds = 0; + widgets.debugOnRebuildDirtyWidget = (element, _) { + final widget = element.widget; + if (widget is ChatMessageView) messageBuilds++; + if (widget is ChatMarkdownView) markdownBuilds++; + totalBuilds++; + }; + addTearDown(() => widgets.debugOnRebuildDirtyWidget = null); + final parsesBefore = chatMarkdownCache.parses; + final perDelta = []; + final watch = Stopwatch(); + for (var index = 0; index < _deltas; index++) { + gateway.emitEvent( + chatTextFrame( + index == 0 ? 'Live reply ' : 'word$index ', + messageId: 'live', + ), + ); + await tester.idle(); + watch + ..reset() + ..start(); + await tester.pump(); + watch.stop(); + perDelta.add(watch.elapsedMicroseconds); + } + widgets.debugOnRebuildDirtyWidget = null; + final parses = chatMarkdownCache.parses - parsesBefore; + // ignore: avoid_print + print( + 'PERF stream: deltas=$_deltas messages=$_messages ' + 'messageBuilds=$messageBuilds markdownBuilds=$markdownBuilds ' + 'markdownParses=$parses totalBuilds=$totalBuilds frame ${_stats(perDelta)}', + ); + expect( + find.textContaining('word${_deltas - 1}', findRichText: true), + findsOneWidget, + ); + // Only the live turn rebuilds per delta (plus slack for the turn that + // starts the stream); every finished message is left alone. + expect(messageBuilds, lessThanOrEqualTo(_deltas + 10)); + expect(parses, lessThanOrEqualTo(_deltas + 10)); + }); + + testWidgets('scrolling a long transcript reuses parsed markdown', ( + tester, + ) async { + await _open(tester); + final list = find.byKey(const ValueKey('chat-thread-s')); + final parsesBefore = chatMarkdownCache.parses; + var parsesUp = 0; + final frames = []; + final watch = Stopwatch(); + // Up 40 drags and back down 40: the way back revisits parsed rows. + for (final dy in [...List.filled(40, 600.0), ...List.filled(40, -600.0)]) { + await tester.drag(list, Offset(0, dy)); + watch + ..reset() + ..start(); + await tester.pump(const Duration(milliseconds: 16)); + watch.stop(); + frames.add(watch.elapsedMicroseconds); + if (frames.length == 40) { + parsesUp = chatMarkdownCache.parses - parsesBefore; + } + } + await tester.pumpAndSettle(); + final parses = chatMarkdownCache.parses - parsesBefore; + // ignore: avoid_print + print( + 'PERF scroll: drags=${frames.length} markdownParses=$parses ' + '(up=$parsesUp down=${parses - parsesUp}) ' + 'frame ${_stats(frames)}', + ); + }); +} diff --git a/app/tool/chat_composer_probe_entry.dart b/app/tool/chat_composer_probe_entry.dart index 93360aca..e762a1e6 100644 --- a/app/tool/chat_composer_probe_entry.dart +++ b/app/tool/chat_composer_probe_entry.dart @@ -7,6 +7,8 @@ import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart'; import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'chat_perf_fixture.dart'; + /// A live-looking fixture conversation with a deterministic composer. /// /// A successful prompt starts a running turn (so the primary control becomes @@ -43,6 +45,8 @@ class _ProbeGateway implements ApiGateway { return { 'chat_history': { 'messages': [ + // `?perf=`: a long transcript for tool/chat_perf_probe.mjs. + ...chatPerfTranscript(chatPerfMessages), // A long history scrolls behind the floating header. if (_probeLong || _query['long'] == '1') for (var i = 0; i < 12; i++) @@ -62,28 +66,31 @@ class _ProbeGateway implements ApiGateway { // text parts and a second folded message, each with markdown // paragraphs. if (_query['paras'] == '1') ..._chunkedReply, - { - 'id': 'probe-user', - 'role': 'user', - 'parts': [ - { - 'type': 'text', - 'text': 'Show me the composer as an operator would use it.', - }, - ], - }, - { - 'id': 'probe-assistant', - 'role': 'assistant', - 'parts': [ - { - 'type': 'text', - 'text': - 'The composer sits below the conversation with a ' - 'multiline field and one primary control.', - }, - ], - }, + if (chatPerfMessages == 0) ...[ + { + 'id': 'probe-user', + 'role': 'user', + 'parts': [ + { + 'type': 'text', + 'text': + 'Show me the composer as an operator would use it.', + }, + ], + }, + { + 'id': 'probe-assistant', + 'role': 'assistant', + 'parts': [ + { + 'type': 'text', + 'text': + 'The composer sits below the conversation with a ' + 'multiline field and one primary control.', + }, + ], + }, + ], ], 'next_cursor': '', 'has_more': false, @@ -124,6 +131,8 @@ class _ProbeGateway implements ApiGateway { 'step': {'status': 'ended', 'turn_id': 'probe-turn', 'intermediate': false}, }); + void emit(JsonMap body) => _emit(body); + void _emit(JsonMap body) => _frames.add({ 'type': 'chat_event', 'chat_event': {'session_id': _session, ...body}, @@ -200,7 +209,8 @@ const _probeStyle = String.fromEnvironment( /// Browser overrides: `?platform=cupertino|material`, `?theme=dark|light`, /// `?long=1`, `?paras=1` (a chunked multi-paragraph reply), `?tasks=`, `?mode=0` (no permission mode recorded) and -/// `?model=0` (a backend without models). +/// `?model=0` (a backend without models). `?perf=` and `?stream=` are +/// the long-transcript performance fixture (see chat_perf_fixture.dart). /// /// Delivery states: `?send=` types and sends that text once the thread /// has loaded (`hold` never replies, `queued` queues, `refuse` is refused), and @@ -244,6 +254,7 @@ void main() { ), newOperationId: gateway.nextOperation, ); + startChatPerf(gateway.emit); if (_query['send'] != null) { Timer( const Duration(milliseconds: 1200), diff --git a/app/tool/chat_perf_fixture.dart b/app/tool/chat_perf_fixture.dart new file mode 100644 index 00000000..28330e70 --- /dev/null +++ b/app/tool/chat_perf_fixture.dart @@ -0,0 +1,82 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +import 'package:pipelines_app/core/api_gateway.dart'; + +/// Long-transcript performance fixture for `tool/chat_composer_probe_entry.dart`. +/// +/// `?perf=` opens a transcript of n messages whose answers carry headings, +/// inline markdown, a 30-line code block and a list. `?stream=` then streams +/// n text deltas into a new reply, one every 40 ms, starting 6 s after load. +/// With either, every frame's build and raster durations are printed to the +/// console as `PERF_FRAME ` for +/// `tool/chat_perf_probe.mjs`. +int get chatPerfMessages => + int.tryParse(Uri.base.queryParameters['perf'] ?? '') ?? 0; +int get chatPerfDeltas => + int.tryParse(Uri.base.queryParameters['stream'] ?? '') ?? 0; + +String _answer(int index) => + '## Answer $index\n\nSome **bold** text with `code` and a ' + '[link](https://example.com/$index).\n\n' + '```dart\n' + '${List.generate(30, (line) => 'final v$line = $index * $line;').join('\n')}' + '\n```\n\n' + '- one\n- two\n- three\n'; + +/// The fixture history; the newest message is the operator's, so a streamed +/// reply opens a new turn. +List chatPerfTranscript(int count) => [ + for (var index = 0; index < count; index++) + (count - index).isOdd + ? { + 'id': 'perf-u$index', + 'role': 'user', + 'parts': [ + {'type': 'text', 'text': 'Question $index'}, + ], + } + : { + 'id': 'perf-a$index', + 'role': 'assistant', + 'parts': [ + {'type': 'text', 'id': 'perf-t$index', 'text': _answer(index)}, + ], + }, +]; + +/// Starts the frame report and, when asked, the streamed reply through [emit]. +void startChatPerf(void Function(JsonMap body) emit) { + if (chatPerfMessages == 0 && chatPerfDeltas == 0) return; + WidgetsFlutterBinding.ensureInitialized().addTimingsCallback((timings) { + for (final timing in timings) { + // ignore: avoid_print + print( + 'PERF_FRAME ${timing.buildDuration.inMicroseconds} ' + '${timing.rasterDuration.inMicroseconds} ' + '${timing.totalSpan.inMicroseconds}', + ); + } + }); + final deltas = chatPerfDeltas; + if (deltas == 0) return; + Timer(const Duration(milliseconds: 6000), () { + // ignore: avoid_print + print('PERF_STREAM_START'); + var sent = 0; + Timer.periodic(const Duration(milliseconds: 40), (timer) { + emit({ + 'message_id': 'perf-live', + 'kind': 'text', + 'part': {'id': 'perf-live-text', 'type': 'text'}, + 'delta': sent == 0 ? 'Live reply ' : 'word$sent ', + }); + if (++sent >= deltas) { + timer.cancel(); + // ignore: avoid_print + print('PERF_STREAM_END'); + } + }); + }); +} diff --git a/app/tool/chat_perf_probe.mjs b/app/tool/chat_perf_probe.mjs new file mode 100644 index 00000000..e2ae50df --- /dev/null +++ b/app/tool/chat_perf_probe.mjs @@ -0,0 +1,108 @@ +// Release-web frame timings for a long chat transcript, over the capture kit. +// +// Build the fixture once per variant, from app/: +// flutter build web --release --target tool/chat_composer_probe_entry.dart \ +// --output build/chat-perf +// then: +// node tool/chat_perf_probe.mjs build/chat-perf [messages=300] [deltas=200] +// +// Two phases, each on a fresh page: wheel-scroll the transcript up and back +// down, then stream deltas into a new reply. Flutter's own FrameTiming (build, +// raster, total) arrives as console lines from tool/chat_perf_fixture.dart. +// Prints one JSON report. Headless Chrome rasterises in software, so raster +// numbers compare variants rather than predict a device. +import { setTimeout as delay } from 'node:timers/promises'; +import { openBrowser } from './capture/browser.mjs'; +import { flutterPage } from './capture/page.mjs'; +import { serveBuild } from './capture/serve.mjs'; + +const [dir, messagesArg = '300', deltasArg = '200'] = process.argv.slice(2); +if (!dir) { + console.error('usage: node tool/chat_perf_probe.mjs [messages] [deltas]'); + process.exit(2); +} +const messages = Number(messagesArg); +const deltas = Number(deltasArg); + +function stats(frames) { + const pick = (i) => frames.map((f) => f[i]).sort((a, b) => a - b); + const summary = (values) => values.length === 0 ? null : { + meanMs: +(values.reduce((a, b) => a + b, 0) / values.length / 1000).toFixed(2), + p50Ms: +(values[Math.floor(values.length / 2)] / 1000).toFixed(2), + p90Ms: +(values[Math.floor(values.length * 0.9)] / 1000).toFixed(2), + maxMs: +(values[values.length - 1] / 1000).toFixed(2), + }; + const total = pick(2); + return { + frames: frames.length, + build: summary(pick(0)), + raster: summary(pick(1)), + total: summary(total), + over16ms: total.filter((t) => t > 16667).length, + }; +} + +async function phase(origin, query, drive) { + const browser = await openBrowser(); + try { + const page = flutterPage(browser, (m) => console.error(m)); + let recording = false; + let frames = []; + const marks = []; + browser.on('Runtime.consoleAPICalled', (p) => { + const text = p.args.map((a) => a.value ?? '').join(' '); + if (text.startsWith('PERF_FRAME ')) { + if (recording) frames.push(text.split(' ').slice(1).map(Number)); + } else if (text.startsWith('PERF_')) { + marks.push(text); + } + }); + const opened = Date.now(); + try { + await page.open(`${origin}/?${query}`, { width: 880, height: 1000 }); + } catch (error) { + throw new Error(`${error.message}; page errors: ${JSON.stringify(page.errors.slice(0, 5))}`); + } + const openMs = Date.now() - opened; + await delay(1000); + const control = { + page, + marks, + start: () => { frames = []; recording = true; }, + stop: () => { recording = false; return frames; }, + }; + const result = await drive(control); + return { openMs, ...result, errors: page.errors.slice(0, 5) }; + } finally { + await browser.close(); + } +} + +const server = await serveBuild(dir); +try { + const scroll = await phase(server.origin, `perf=${messages}`, async ({ page, start, stop }) => { + start(); + for (const dy of [...Array(60).fill(-400), ...Array(60).fill(400)]) { + await page.scroll(dy); + await delay(50); + } + await delay(500); + return { scroll: stats(stop()) }; + }); + const stream = await phase( + server.origin, + `perf=${messages}&stream=${deltas}`, + async ({ start, stop, marks }) => { + const begin = Date.now() + 15000; + while (!marks.includes('PERF_STREAM_START') && Date.now() < begin) await delay(5); + start(); + const end = Date.now() + deltas * 40 + 15000; + while (!marks.includes('PERF_STREAM_END') && Date.now() < end) await delay(100); + await delay(500); + return { streamed: marks.includes('PERF_STREAM_END'), stream: stats(stop()) }; + }, + ); + console.log(JSON.stringify({ build: dir, messages, deltas, scroll, stream }, null, 2)); +} finally { + await server.close(); +} From 7b1455631b4c2e6e6c1e6fd22a24bf8d3c21296e Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 2 Nov 2026 00:08:29 +0000 Subject: [PATCH 3/4] Rebuild only changed list rows and lay out big artifact sections lazily Runs and chat session rows are memoized on their own data (MemoSubtree), so a run event or a chat's running change rebuilds one row instead of every built row. The artifact gallery's open sections are lazy slivers revealed by a sliver open/close animation, and thumbnails decode at display size. Benches in test/perf measure both. --- .../ui/artifact_thumbnail_image.dart | 78 ++++++++ .../features/artifacts/ui/artifact_tile.dart | 34 +++- .../artifacts/ui/artifact_visit_list.dart | 125 ++++++++----- .../ui/sessions/chat_sessions_screen.dart | 15 +- .../ui/sessions/session_list_cupertino.dart | 43 +---- .../ui/sessions/session_list_material.dart | 43 +---- .../chat/ui/sessions/session_row_memo.dart | 57 ++++++ app/lib/features/runs/ui/runs_list.dart | 24 ++- app/lib/ui/layout/memo_subtree.dart | 65 +++++++ app/lib/ui/layout/sliver_reveal.dart | 152 ++++++++++++++++ app/lib/ui/layout/sticky_section.dart | 51 ++++-- .../ui/artifact_thumbnail_image_test.dart | 18 ++ app/test/perf/background_work_bench_test.dart | 8 +- .../perf/list_and_gallery_bench_test.dart | 170 ++++++++++++++++++ app/test/ui/layout/memo_subtree_test.dart | 51 ++++++ app/test/ui/layout/sliver_reveal_test.dart | 107 +++++++++++ 16 files changed, 889 insertions(+), 152 deletions(-) create mode 100644 app/lib/features/artifacts/ui/artifact_thumbnail_image.dart create mode 100644 app/lib/features/chat/ui/sessions/session_row_memo.dart create mode 100644 app/lib/ui/layout/memo_subtree.dart create mode 100644 app/lib/ui/layout/sliver_reveal.dart create mode 100644 app/test/features/artifacts/ui/artifact_thumbnail_image_test.dart create mode 100644 app/test/perf/list_and_gallery_bench_test.dart create mode 100644 app/test/ui/layout/memo_subtree_test.dart create mode 100644 app/test/ui/layout/sliver_reveal_test.dart diff --git a/app/lib/features/artifacts/ui/artifact_thumbnail_image.dart b/app/lib/features/artifacts/ui/artifact_thumbnail_image.dart new file mode 100644 index 00000000..743169b0 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_thumbnail_image.dart @@ -0,0 +1,78 @@ +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/painting.dart'; + +/// An image's bytes decoded no larger than needed to cover a box of +/// [width] x [height] device pixels (as `BoxFit.cover` shows it), keeping the +/// image's aspect ratio and never upscaling. A gallery of full-size pictures +/// then holds thumbnails, not originals, in memory. +@immutable +class CoverSizedMemoryImage extends ImageProvider { + const CoverSizedMemoryImage( + this.bytes, { + required this.width, + required this.height, + }); + + final Uint8List bytes; + final int width; + final int height; + + @override + Future obtainKey(ImageConfiguration configuration) => + SynchronousFuture(this); + + @override + ImageStreamCompleter loadImage( + CoverSizedMemoryImage key, + ImageDecoderCallback decode, + ) => MultiFrameImageStreamCompleter( + codec: _decode(key, decode), + scale: 1, + debugLabel: 'CoverSizedMemoryImage(${describeIdentity(key.bytes)})', + ); + + static Future _decode( + CoverSizedMemoryImage key, + ImageDecoderCallback decode, + ) async { + final buffer = await ui.ImmutableBuffer.fromUint8List(key.bytes); + return decode( + buffer, + getTargetSize: (intrinsicWidth, intrinsicHeight) => coverTargetSize( + intrinsicWidth, + intrinsicHeight, + width: key.width, + height: key.height, + ), + ); + } + + @override + bool operator ==(Object other) => + other is CoverSizedMemoryImage && + identical(other.bytes, bytes) && + other.width == width && + other.height == height; + + @override + int get hashCode => Object.hash(identityHashCode(bytes), width, height); +} + +/// The decode size that still covers a [width] x [height] box: the picture's +/// aspect ratio scaled down until its shorter side fits, never scaled up. +ui.TargetImageSize coverTargetSize( + int intrinsicWidth, + int intrinsicHeight, { + required int width, + required int height, +}) { + final scale = math.max(width / intrinsicWidth, height / intrinsicHeight); + if (scale >= 1) return const ui.TargetImageSize(); + return ui.TargetImageSize( + width: math.max(1, (intrinsicWidth * scale).ceil()), + height: math.max(1, (intrinsicHeight * scale).ceil()), + ); +} diff --git a/app/lib/features/artifacts/ui/artifact_tile.dart b/app/lib/features/artifacts/ui/artifact_tile.dart index f051d048..4e1f5ae5 100644 --- a/app/lib/features/artifacts/ui/artifact_tile.dart +++ b/app/lib/features/artifacts/ui/artifact_tile.dart @@ -7,6 +7,7 @@ import '../domain/artifact_kind.dart'; import '../domain/artifact_record.dart'; import '../domain/artifact_url.dart'; import 'artifact_row_labels.dart'; +import 'artifact_thumbnail_image.dart'; import 'artifact_viewer_fetch.dart'; /// One artifact in the gallery grid: a thumbnail for an image, otherwise an @@ -139,9 +140,15 @@ class ArtifactThumbnail extends StatefulWidget { State createState() => _ArtifactThumbnailState(); } -class _ArtifactThumbnailState extends State { +class _ArtifactThumbnailState extends State + with AutomaticKeepAliveClientMixin { Future? _image; + /// A loaded picture stays alive when a lazy gallery scrolls it away, so + /// scrolling back does not fetch it again. + @override + bool get wantKeepAlive => _image != null; + @override void initState() { super.initState(); @@ -160,6 +167,7 @@ class _ArtifactThumbnailState extends State { @override Widget build(BuildContext context) { + super.build(context); final cupertino = usesCupertinoHost(context); final icon = Icon( artifactKindIcon(widget.artifact, cupertino: cupertino), @@ -176,11 +184,25 @@ class _ArtifactThumbnailState extends State { if (result == null || !result.ok || result.bytes.isEmpty) { return Center(child: icon); } - return Image.memory( - result.bytes, - fit: BoxFit.cover, - gaplessPlayback: true, - errorBuilder: (_, _, _) => Center(child: icon), + return LayoutBuilder( + builder: (context, constraints) { + final ratio = MediaQuery.devicePixelRatioOf(context); + // Decoded at the size shown, not the picture's full size. + final sized = + constraints.hasBoundedWidth && constraints.hasBoundedHeight + ? CoverSizedMemoryImage( + result.bytes, + width: (constraints.maxWidth * ratio).ceil(), + height: (constraints.maxHeight * ratio).ceil(), + ) + : null; + return Image( + image: sized ?? MemoryImage(result.bytes), + fit: BoxFit.cover, + gaplessPlayback: true, + errorBuilder: (_, _, _) => Center(child: icon), + ); + }, ); }, ); diff --git a/app/lib/features/artifacts/ui/artifact_visit_list.dart b/app/lib/features/artifacts/ui/artifact_visit_list.dart index 243370fd..87dc4d16 100644 --- a/app/lib/features/artifacts/ui/artifact_visit_list.dart +++ b/app/lib/features/artifacts/ui/artifact_visit_list.dart @@ -1,3 +1,5 @@ +import 'dart:math' as math; + import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -143,19 +145,25 @@ class _ArtifactVisitListState extends State { key: key, title: artifactGroupLabel(group), count: group.artifacts.length, - body: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ + // Lazy: a visit with hundreds of artifacts builds and lays out + // only the rows on screen. + body: SliverMainAxisGroup( + slivers: [ if (group.artifacts.isNotEmpty) _mode == ArtifactGalleryMode.grid ? _grid(group) : _list(group), if (widget.showTurnDocuments && group.documents.isNotEmpty) - ArtifactDocumentSection( - group: group, - selectedIdentity: widget.selectedIdentity, - onSelected: widget.onSelected, - showHeader: false, + SliverToBoxAdapter( + child: _inkSurface( + context, + ArtifactDocumentSection( + group: group, + selectedIdentity: widget.selectedIdentity, + onSelected: widget.onSelected, + showHeader: false, + ), + ), ), ], ), @@ -194,7 +202,7 @@ class _ArtifactVisitListState extends State { child: Text('$count'), ), ], - body: body, + sliverBody: body, ); Widget _modeSwitch(BuildContext context) { @@ -241,70 +249,89 @@ class _ArtifactVisitListState extends State { ); } + /// Rows keep a Material surface for their ink, as the section body's own + /// surface was when it was one box around every row. + Widget _inkSurface(BuildContext context, Widget child) => + usesCupertinoHost(context) + ? child + : Material(type: MaterialType.transparency, child: child); + /// The list view: one row per artifact with a small thumbnail beside it. - Widget _list(ArtifactGroup group) => Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - for (var index = 0; index < group.artifacts.length; index += 1) + Widget _list(ArtifactGroup group) => SliverList.builder( + itemCount: group.artifacts.length, + itemBuilder: (context, index) { + final artifact = group.artifacts[index]; + final identity = artifactVisitIdentity(group, artifact); + return _inkSurface( + context, ArtifactRecordRow( - key: ValueKey( - '${artifactVisitIdentity(group, group.artifacts[index])}' - '\u0000$index', - ), + key: ValueKey('$identity\u0000$index'), group: group, - artifact: group.artifacts[index], - selected: - widget.selectedIdentity == - artifactVisitIdentity(group, group.artifacts[index]), + artifact: artifact, + selected: widget.selectedIdentity == identity, onSelected: widget.onSelected, leading: ClipRRect( borderRadius: BorderRadius.circular(6), child: SizedBox.square( dimension: 44, child: ArtifactThumbnail( - artifact: group.artifacts[index], + artifact: artifact, configuredEndpoint: widget.configuredEndpoint, fetch: widget.fetch, ), ), ), ), - ], + ); + }, ); /// A group's artifacts as a grid: two tiles across on a phone, more as the - /// pane widens. - Widget _grid(ArtifactGroup group) => LayoutBuilder( + /// pane widens. Each line of tiles is one lazy item, top-aligned like the + /// runs of a wrap. + Widget _grid(ArtifactGroup group) => SliverLayoutBuilder( builder: (context, constraints) { const gap = 12.0; - final width = constraints.maxWidth - 32; + final width = constraints.crossAxisExtent - 32; final columns = (width / 170).floor().clamp(2, 6); final tile = (width - gap * (columns - 1)) / columns; - return Padding( + final artifacts = group.artifacts; + return SliverPadding( padding: const EdgeInsets.fromLTRB(16, 4, 16, 8), - child: Wrap( - spacing: gap, - runSpacing: gap, - children: [ - for (var index = 0; index < group.artifacts.length; index += 1) - SizedBox( - width: tile, - child: ArtifactTile( - key: ValueKey( - '${artifactVisitIdentity(group, group.artifacts[index])}' - '\u0000$index', - ), - group: group, - artifact: group.artifacts[index], - selected: - widget.selectedIdentity == - artifactVisitIdentity(group, group.artifacts[index]), - configuredEndpoint: widget.configuredEndpoint, - fetch: widget.fetch, - onSelected: widget.onSelected, - ), + sliver: SliverList.builder( + itemCount: (artifacts.length + columns - 1) ~/ columns, + itemBuilder: (context, line) { + final first = line * columns; + final end = math.min(first + columns, artifacts.length); + return Padding( + padding: EdgeInsets.only(top: line == 0 ? 0 : gap), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (var index = first; index < end; index += 1) ...[ + if (index > first) const SizedBox(width: gap), + SizedBox( + width: tile, + child: ArtifactTile( + key: ValueKey( + '${artifactVisitIdentity(group, artifacts[index])}' + '\u0000$index', + ), + group: group, + artifact: artifacts[index], + selected: + widget.selectedIdentity == + artifactVisitIdentity(group, artifacts[index]), + configuredEndpoint: widget.configuredEndpoint, + fetch: widget.fetch, + onSelected: widget.onSelected, + ), + ), + ], + ], ), - ], + ); + }, ), ); }, diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart index 17b7c416..c9146548 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -175,6 +175,13 @@ class _ChatSessionsScreenState extends State { widget.onOpen(session); } + // Methods rather than closures, so the list's memoized rows see the same + // callbacks from one build to the next. + void _reopen(JsonMap session) => _controller.reopen(_sessionId(session)); + + void _star(JsonMap session) => + _controller.star(_sessionId(session), session['starred'] != true); + Future _hide(JsonMap session) async { await _controller.hide(_sessionId(session)); _undoTimer?.cancel(); @@ -226,12 +233,8 @@ class _ChatSessionsScreenState extends State { onOpen: _open, onRename: _rename, onClose: _close, - onReopen: (session) => - _controller.reopen(_sessionId(session)), - onStar: (session) => _controller.star( - _sessionId(session), - session['starred'] != true, - ), + onReopen: _reopen, + onStar: _star, onHide: _hide, onClearSearch: () { _search.clear(); diff --git a/app/lib/features/chat/ui/sessions/session_list_cupertino.dart b/app/lib/features/chat/ui/sessions/session_list_cupertino.dart index 6f85e87e..851fc476 100644 --- a/app/lib/features/chat/ui/sessions/session_list_cupertino.dart +++ b/app/lib/features/chat/ui/sessions/session_list_cupertino.dart @@ -5,8 +5,7 @@ import '../../../../core/api_gateway.dart'; import '../../domain/chat_sessions.dart'; import 'chat_adaptive.dart'; import 'chat_sessions_body.dart'; -import 'session_actions.dart'; -import 'session_row_content.dart'; +import 'session_row_memo.dart'; import '../../../../ui/adaptive/floating_bar_layout.dart'; class CupertinoSessionList extends StatelessWidget { @@ -96,7 +95,7 @@ class CupertinoSessionList extends StatelessWidget { final id = '${session['id'] ?? ''}'; final error = errorFor(id); return [ - ChatSessionRow( + memoChatSessionRow( session: session, selected: id == activeSessionId, duplicateTitles: duplicateTitles, @@ -104,15 +103,11 @@ class CupertinoSessionList extends StatelessWidget { // A refusal below the row separates it instead. divider: divider && error == null, onOpen: onOpen, - onAction: (action) => _dispatch( - action, - session, - onStar: onStar, - onRename: onRename, - onClose: onClose, - onReopen: onReopen, - onHide: onHide, - ), + onStar: onStar, + onRename: onRename, + onClose: onClose, + onReopen: onReopen, + onHide: onHide, ), if (error != null) ChatRowError( @@ -124,30 +119,6 @@ class CupertinoSessionList extends StatelessWidget { } } -/// Routes a row's menu choice to the list's callbacks. -void _dispatch( - SessionAction action, - JsonMap session, { - required ValueChanged onStar, - required ValueChanged onRename, - required ValueChanged onClose, - required ValueChanged onReopen, - required ValueChanged onHide, -}) { - switch (action) { - case SessionAction.star: - onStar(session); - case SessionAction.rename: - onRename(session); - case SessionAction.close: - onClose(session); - case SessionAction.reopen: - onReopen(session); - case SessionAction.hide: - onHide(session); - } -} - /// A directory's name above its chats, like a grouped table's header. class _DirectoryHeader extends StatelessWidget { const _DirectoryHeader(this.directory); diff --git a/app/lib/features/chat/ui/sessions/session_list_material.dart b/app/lib/features/chat/ui/sessions/session_list_material.dart index 3a37c0d4..57ede799 100644 --- a/app/lib/features/chat/ui/sessions/session_list_material.dart +++ b/app/lib/features/chat/ui/sessions/session_list_material.dart @@ -6,8 +6,7 @@ import '../../../../core/api_gateway.dart'; import '../../domain/chat_sessions.dart'; import 'chat_adaptive.dart'; import 'chat_sessions_body.dart'; -import 'session_actions.dart'; -import 'session_row_content.dart'; +import 'session_row_memo.dart'; class MaterialSessionList extends StatelessWidget { const MaterialSessionList({ @@ -97,7 +96,7 @@ class MaterialSessionList extends StatelessWidget { final id = '${session['id'] ?? ''}'; final error = errorFor(id); return [ - ChatSessionRow( + memoChatSessionRow( session: session, selected: id == activeSessionId, duplicateTitles: duplicateTitles, @@ -105,15 +104,11 @@ class MaterialSessionList extends StatelessWidget { // A refusal below the row separates it instead. divider: divider && error == null, onOpen: onOpen, - onAction: (action) => _dispatch( - action, - session, - onStar: onStar, - onRename: onRename, - onClose: onClose, - onReopen: onReopen, - onHide: onHide, - ), + onStar: onStar, + onRename: onRename, + onClose: onClose, + onReopen: onReopen, + onHide: onHide, ), if (error != null) ChatRowError( @@ -124,27 +119,3 @@ class MaterialSessionList extends StatelessWidget { ]; } } - -/// Routes a row's menu choice to the list's callbacks. -void _dispatch( - SessionAction action, - JsonMap session, { - required ValueChanged onStar, - required ValueChanged onRename, - required ValueChanged onClose, - required ValueChanged onReopen, - required ValueChanged onHide, -}) { - switch (action) { - case SessionAction.star: - onStar(session); - case SessionAction.rename: - onRename(session); - case SessionAction.close: - onClose(session); - case SessionAction.reopen: - onReopen(session); - case SessionAction.hide: - onHide(session); - } -} diff --git a/app/lib/features/chat/ui/sessions/session_row_memo.dart b/app/lib/features/chat/ui/sessions/session_row_memo.dart new file mode 100644 index 00000000..40914040 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/session_row_memo.dart @@ -0,0 +1,57 @@ +import 'package:flutter/widgets.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../../../ui/layout/memo_subtree.dart'; +import '../../domain/chat_sessions.dart'; +import 'session_actions.dart'; +import 'session_row_content.dart'; + +/// A chat row that rebuilds only when its own session or state changes, so a +/// running-state change in one chat does not rebuild every row of the list. +/// +/// The list's callbacks are part of the memo: the screen passes its own +/// methods, so they compare equal from one build to the next. +Widget memoChatSessionRow({ + required JsonMap session, + required bool selected, + required Set duplicateTitles, + required bool unseen, + required bool divider, + required ValueChanged onOpen, + required ValueChanged onStar, + required ValueChanged onRename, + required ValueChanged onClose, + required ValueChanged onReopen, + required ValueChanged onHide, +}) => MemoSubtree( + key: ValueKey('chat-row-memo-${session['id'] ?? ''}'), + memo: ( + MemoMap(session), + selected, + // The row reads the set only for its own title. + duplicateTitles.contains(chatSessionTitle(session)), + unseen, + divider, + onOpen, + onStar, + onRename, + onClose, + onReopen, + onHide, + ), + builder: (_) => ChatSessionRow( + session: session, + selected: selected, + duplicateTitles: duplicateTitles, + unseen: unseen, + divider: divider, + onOpen: onOpen, + onAction: (action) => switch (action) { + SessionAction.star => onStar(session), + SessionAction.rename => onRename(session), + SessionAction.close => onClose(session), + SessionAction.reopen => onReopen(session), + SessionAction.hide => onHide(session), + }, + ), +); diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart index 3ad338ac..ef3d7083 100644 --- a/app/lib/features/runs/ui/runs_list.dart +++ b/app/lib/features/runs/ui/runs_list.dart @@ -5,6 +5,7 @@ import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import '../../../ui/adaptive/floating_bar_layout.dart'; import '../../../ui/adaptive/host.dart'; +import '../../../ui/layout/memo_subtree.dart'; import '../../attention/notify/notification_controller.dart'; import '../../attention/runtime/attention_controller.dart'; import '../../attention/runtime/attention_store.dart'; @@ -300,6 +301,27 @@ class RunsList extends StatelessWidget { Widget _runTile(BuildContext context, JsonMap run, {bool divider = true}) { final id = run['id']; + final selection = controller.selection; + final now = DateTime.now(); + // A run event for one run rebuilds only that run's row: the others keep + // their built subtree (their menu, ripple and tooltip included). + return MemoSubtree( + memo: ( + MemoMap(run), + divider, + selection.active, + selection.contains(id), + id == controller.selectedRunId, + controller, + onSelected, + // An executing run's duration reads the clock, as before. + run['executing'] == true ? runRowFacts(run, now).duration : null, + ), + builder: (context) => _runRow(run, id, now, divider: divider), + ); + } + + Widget _runRow(JsonMap run, Object? id, DateTime now, {bool divider = true}) { final selection = controller.selection; return RunListRow( selecting: selection.active, @@ -311,7 +333,7 @@ class RunsList extends StatelessWidget { run: run, divider: divider, selected: id == controller.selectedRunId, - now: DateTime.now(), + now: now, onTap: id is num ? () => onSelected(id) : null, gateway: controller.repository.gateway, onRunChanged: controller.acceptRunDetail, diff --git a/app/lib/ui/layout/memo_subtree.dart b/app/lib/ui/layout/memo_subtree.dart new file mode 100644 index 00000000..0df0a782 --- /dev/null +++ b/app/lib/ui/layout/memo_subtree.dart @@ -0,0 +1,65 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +/// Builds [builder] once and hands Flutter the same child until [memo] +/// changes, so a list that rebuilds on every notification skips the rows +/// whose own data did not change. +/// +/// [memo] must capture everything the built subtree shows or calls: the +/// row's data and every callback or controller its closures use (compare +/// callbacks by `==`, so a tear-off of the same method still matches). The +/// subtree's own inherited dependencies (theme, host, media) still rebuild +/// it directly, as they mark its elements rather than this one. +class MemoSubtree extends StatefulWidget { + const MemoSubtree({super.key, required this.memo, required this.builder}); + + final Object? memo; + final WidgetBuilder builder; + + @override + State createState() => _MemoSubtreeState(); +} + +class _MemoSubtreeState extends State { + Widget? _child; + + @override + void didUpdateWidget(MemoSubtree oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.memo != widget.memo) _child = null; + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + // A builder that read an inherited widget through this context. + _child = null; + } + + @override + void reassemble() { + super.reassemble(); + _child = null; + } + + @override + Widget build(BuildContext context) => _child ??= widget.builder(context); +} + +/// A JSON row map as a [MemoSubtree] memo: equal when it is the same map or +/// has the same entries (nested values compare by `==`, so a rebuilt nested +/// map counts as a change). +@immutable +class MemoMap { + const MemoMap(this.map); + + final Map? map; + + @override + bool operator ==(Object other) => + other is MemoMap && + (identical(map, other.map) || mapEquals(map, other.map)); + + @override + int get hashCode => map?.length ?? 0; +} diff --git a/app/lib/ui/layout/sliver_reveal.dart b/app/lib/ui/layout/sliver_reveal.dart new file mode 100644 index 00000000..31ff98a7 --- /dev/null +++ b/app/lib/ui/layout/sliver_reveal.dart @@ -0,0 +1,152 @@ +import 'dart:math' as math; + +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +/// Opens and closes a sliver by growing or shrinking it from its top, the +/// sliver counterpart of a clipped `AnimatedSize` with top alignment. The +/// sliver stays lazy: only its visible part is built and laid out, however +/// long it is. Closed, it takes no space and builds nothing. +class SliverReveal extends StatefulWidget { + const SliverReveal({ + super.key, + required this.open, + required this.duration, + required this.curve, + required this.sliver, + }); + + final bool open; + final Duration duration; + final Curve curve; + final Widget sliver; + + @override + State createState() => _SliverRevealState(); +} + +class _SliverRevealState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _controller = AnimationController( + vsync: this, + duration: widget.duration, + value: widget.open ? 1 : 0, + ); + + @override + void didUpdateWidget(SliverReveal oldWidget) { + super.didUpdateWidget(oldWidget); + _controller.duration = widget.duration; + if (widget.open == oldWidget.open) return; + if (widget.duration == Duration.zero) { + _controller.value = widget.open ? 1 : 0; + } else if (widget.open) { + _controller.forward(); + } else { + _controller.reverse(); + } + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => AnimatedBuilder( + animation: _controller, + builder: (context, sliver) { + if (_controller.isDismissed) return const SliverToBoxAdapter(); + final value = _controller.value; + return _SliverExtentFactor( + factor: value >= 1 ? 1 : widget.curve.transform(value), + sliver: sliver, + ); + }, + child: widget.sliver, + ); +} + +class _SliverExtentFactor extends SingleChildRenderObjectWidget { + const _SliverExtentFactor({required this.factor, Widget? sliver}) + : super(child: sliver); + + final double factor; + + @override + RenderObject createRenderObject(BuildContext context) => + _RenderSliverExtentFactor(factor); + + @override + void updateRenderObject( + BuildContext context, + _RenderSliverExtentFactor renderObject, + ) => renderObject.factor = factor; +} + +/// Lays its sliver out normally and reports [factor] of its extent, clipping +/// what lies beyond. +class _RenderSliverExtentFactor extends RenderProxySliver { + _RenderSliverExtentFactor(this._factor); + + double _factor; + set factor(double value) { + if (value == _factor) return; + _factor = value; + markNeedsLayout(); + } + + bool get _clipped => _factor < 1; + + @override + void performLayout() { + final child = this.child!; + child.layout(constraints, parentUsesSize: true); + final full = child.geometry!; + if (!_clipped || full.scrollOffsetCorrection != null) { + geometry = full; + return; + } + final extent = full.scrollExtent * _factor; + final paintExtent = math.min( + calculatePaintOffset(constraints, from: 0, to: extent), + full.paintExtent, + ); + geometry = SliverGeometry( + scrollExtent: extent, + paintExtent: paintExtent, + layoutExtent: paintExtent, + maxPaintExtent: extent, + cacheExtent: calculateCacheOffset(constraints, from: 0, to: extent), + hasVisualOverflow: true, + ); + } + + @override + void paint(PaintingContext context, Offset offset) { + if (child == null || geometry!.paintExtent <= 0) return; + if (!_clipped) return super.paint(context, offset); + final extent = geometry!.paintExtent; + final cross = constraints.crossAxisExtent; + final clip = switch (constraints.axis) { + Axis.vertical => Rect.fromLTWH(0, 0, cross, extent), + Axis.horizontal => Rect.fromLTWH(0, 0, extent, cross), + }; + _clip.layer = context.pushClipRect( + needsCompositing, + offset, + clip, + super.paint, + oldLayer: _clip.layer, + ); + } + + final _clip = LayerHandle(); + + @override + void dispose() { + _clip.layer = null; + super.dispose(); + } +} diff --git a/app/lib/ui/layout/sticky_section.dart b/app/lib/ui/layout/sticky_section.dart index ec6af6e1..fa47650c 100644 --- a/app/lib/ui/layout/sticky_section.dart +++ b/app/lib/ui/layout/sticky_section.dart @@ -7,6 +7,7 @@ import '../adaptive/host.dart'; import '../theme/app_theme.dart'; import '../motion/motion.dart'; import 'section_heading.dart'; +import 'sliver_reveal.dart'; /// A collapsible section for a [CustomScrollView]: its title stays pinned at /// the top while its content scrolls under it, so it can always be closed @@ -17,17 +18,22 @@ class StickySection extends StatelessWidget { required this.title, required this.open, required this.onToggle, - required this.body, + this.body, + this.sliverBody, this.trailing = const [], this.titleColor, - }); + }) : assert((body == null) != (sliverBody == null)); final String title; final bool open; final VoidCallback onToggle; /// The content shown while open (a box widget). - final Widget body; + final Widget? body; + + /// The content shown while open as a sliver, in place of [body]: a long + /// body (hundreds of items) then builds and lays out only what is visible. + final Widget? sliverBody; /// Small actions beside the title (a count, a copy button). final List trailing; @@ -54,18 +60,30 @@ class StickySection extends StatelessWidget { ), // The content grows and shrinks under the pinned title, on its own // surface with the title's accent continuing down its edge. - SliverToBoxAdapter( - child: ClipRect( - child: AnimatedSize( - duration: Motion.of(context, Motion.standard), - curve: Motion.curve, - alignment: Alignment.topCenter, - child: open - ? _SectionBody(child: body) - : const SizedBox(width: double.infinity), + if (sliverBody case final sliver?) + SliverReveal( + open: open, + duration: Motion.of(context, Motion.standard), + curve: Motion.curve, + // The body's padding; its rows bring their own ink surface. + sliver: SliverPadding( + padding: _SectionBody.padding, + sliver: sliver, + ), + ) + else + SliverToBoxAdapter( + child: ClipRect( + child: AnimatedSize( + duration: Motion.of(context, Motion.standard), + curve: Motion.curve, + alignment: Alignment.topCenter, + child: open + ? _SectionBody(child: body!) + : const SizedBox(width: double.infinity), + ), ), ), - ), ], ); } @@ -254,12 +272,11 @@ class _SectionBody extends StatelessWidget { final Widget child; + static const padding = EdgeInsets.only(top: 12, bottom: 4); + @override Widget build(BuildContext context) { - final content = Padding( - padding: const EdgeInsets.only(top: 12, bottom: 4), - child: child, - ); + final content = Padding(padding: padding, child: child); if (usesCupertinoHost(context)) { return content; } diff --git a/app/test/features/artifacts/ui/artifact_thumbnail_image_test.dart b/app/test/features/artifacts/ui/artifact_thumbnail_image_test.dart new file mode 100644 index 00000000..48095615 --- /dev/null +++ b/app/test/features/artifacts/ui/artifact_thumbnail_image_test.dart @@ -0,0 +1,18 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_thumbnail_image.dart'; + +void main() { + test('decodes a large picture just big enough to cover its box', () { + // Landscape into a square: the height binds, the width overflows. + final wide = coverTargetSize(4000, 2000, width: 200, height: 200); + expect((wide.width, wide.height), (400, 200)); + // Portrait into a 4:3 tile: the width binds. + final tall = coverTargetSize(1000, 3000, width: 400, height: 300); + expect((tall.width, tall.height), (400, 1200)); + }); + + test('never upscales a picture smaller than its box', () { + final small = coverTargetSize(100, 80, width: 200, height: 200); + expect((small.width, small.height), (null, null)); + }); +} diff --git a/app/test/perf/background_work_bench_test.dart b/app/test/perf/background_work_bench_test.dart index fc924bb7..e5ca8117 100644 --- a/app/test/perf/background_work_bench_test.dart +++ b/app/test/perf/background_work_bench_test.dart @@ -80,6 +80,9 @@ List _runs(int count, DateTime now) => [ }, ]; +// The app passes a stable tear-off (`_select`), never a fresh closure. +void _open(num _) {} + void main() { late _Gateway gateway; late RunsController controller; @@ -105,7 +108,7 @@ void main() { AppDestination.runs: (_) => AnimatedBuilder( animation: controller, builder: (_, _) => - RunsList(controller: controller, onSelected: (_) {}), + RunsList(controller: controller, onSelected: _open), ), AppDestination.pipelines: (_) => const Center(child: Text('pipelines')), }, @@ -234,6 +237,9 @@ void main() { ); // Only the ten frames that advance a step change anything visible. expect(notifications, lessThanOrEqualTo(10)); + // Each notification rebuilds the one row whose run changed, not every + // built row (16 rows rebuilt per notification before memoized rows). + expect(rebuilds.of(RunListRow), lessThanOrEqualTo(notifications)); await tester.pumpWidget(const SizedBox()); }); } diff --git a/app/test/perf/list_and_gallery_bench_test.dart b/app/test/perf/list_and_gallery_bench_test.dart new file mode 100644 index 00000000..76e3bc5c --- /dev/null +++ b/app/test/perf/list_and_gallery_bench_test.dart @@ -0,0 +1,170 @@ +// Measures the work a list does for data that did not change: the chat +// sessions list on a running-state change, and the artifact gallery opening a +// visit with hundreds of artifacts. Each scenario prints `BENCH ...` numbers +// and asserts the budget the memoized rows and lazy gallery keep. +import 'dart:typed_data'; + +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/artifacts/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_tile.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_fetch.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_body.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/session_row_content.dart'; + +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); +} + +int _elements(WidgetTester tester) { + var count = 0; + void visit(Element element) { + count++; + element.visitChildren(visit); + } + + tester.binding.rootElement!.visitChildren(visit); + return count; +} + +// Stable callbacks, as the screen passes its own methods. +void _session(JsonMap _) {} +void _clear() {} +bool _unseen(JsonMap _) => false; +String? _noError(String _) => null; +Future _fetch(Uri _) async => + ArtifactFetchResult(status: 404, bytes: Uint8List(0)); + +void main() { + Future sizeView(WidgetTester tester) async { + tester.view.physicalSize = const Size(400, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + } + + testWidgets('chat sessions list: 50 running-state changes', (tester) async { + await sizeView(tester); + final sessions = ValueNotifier>([ + for (var i = 0; i < 200; i++) + { + 'id': 's$i', + 'title': 'Chat $i', + 'directory': '/repo/${i % 3}', + 'harness': 'claude', + 'running': false, + 'updated_at': DateTime.now() + .subtract(Duration(minutes: i)) + .toIso8601String(), + }, + ]); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ValueListenableBuilder( + valueListenable: sessions, + builder: (_, list, _) => ChatSessionsBody( + sessions: list, + query: '', + loading: false, + error: null, + onOpen: _session, + onRename: _session, + onClose: _session, + onReopen: _session, + onStar: _session, + onHide: _session, + onClearSearch: _clear, + isUnseen: _unseen, + errorFor: _noError, + ), + ), + ), + ), + ); + await tester.pump(); + final built = find.byType(ChatSessionRow).evaluate().length; + final rebuilds = _Rebuilds()..install(); + for (var i = 0; i < 50; i++) { + // The controller replaces only the changed row's map. + final id = i % 5; + sessions.value = [ + for (final s in sessions.value) + s['id'] == 's$id' ? {...s, 'running': s['running'] != true} : s, + ]; + await tester.pump(); + } + rebuilds.uninstall(); + // ignore: avoid_print + print( + 'BENCH chatSessions200 builtRows=$built ' + 'rowRebuilds=${rebuilds.of(ChatSessionRow)} ' + 'totalRebuilds=${rebuilds.total}', + ); + // One row per change, not all 200 (10,000 row rebuilds before). + expect(rebuilds.of(ChatSessionRow), 50); + }); + + testWidgets('gallery: open a visit with 500 artifacts', (tester) async { + await sizeView(tester); + final group = ArtifactGroup( + stageKey: 'render', + visit: 1, + artifacts: [ + for (var i = 0; i < 500; i++) + ArtifactRecord.fromJson({ + 'name': 'frame-$i.png', + 'url': '/artifacts/1/frame-$i.png', + 'content_type': 'image/png', + 'size_bytes': 1000 + i, + }), + ], + ); + for (final mode in ArtifactGalleryMode.values) { + ArtifactVisitList.lastMode = mode; + final watch = Stopwatch()..start(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ArtifactVisitList( + key: ValueKey(mode), + groups: [group], + initiallyCollapsed: false, + fetch: _fetch, + ), + ), + ), + ); + await tester.pumpAndSettle(); + final settle = watch.elapsedMilliseconds; + final tiles = + find.byType(ArtifactTile).evaluate().length + + find.byType(ArtifactThumbnail).evaluate().length; + final elements = _elements(tester); + // A scroll frame through the open section. + watch.reset(); + await tester.drag(find.byType(CustomScrollView), const Offset(0, -2000)); + await tester.pump(); + final scroll = watch.elapsedMicroseconds; + // ignore: avoid_print + print( + 'BENCH gallery500 mode=${mode.name} builtItems=$tiles ' + 'elements=$elements openMs=$settle scrollFrameUs=$scroll', + ); + // Only the visible tiles are built (all 500 were before). + expect(tiles, lessThan(100)); + await tester.pumpWidget(const SizedBox()); + } + ArtifactVisitList.lastMode = ArtifactGalleryMode.grid; + }); +} diff --git a/app/test/ui/layout/memo_subtree_test.dart b/app/test/ui/layout/memo_subtree_test.dart new file mode 100644 index 00000000..c28ea2e5 --- /dev/null +++ b/app/test/ui/layout/memo_subtree_test.dart @@ -0,0 +1,51 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/layout/memo_subtree.dart'; + +void main() { + testWidgets('rebuilds only when the memo changes', (tester) async { + var builds = 0; + Widget host(Object memo) => Directionality( + textDirection: TextDirection.ltr, + child: MemoSubtree( + memo: memo, + builder: (_) { + builds++; + return Text('$memo'); + }, + ), + ); + await tester.pumpWidget(host((MemoMap({'id': 1, 'a': 'x'}), true))); + // An equal map (a new instance) and equal props keep the built child. + await tester.pumpWidget(host((MemoMap({'id': 1, 'a': 'x'}), true))); + expect(builds, 1); + await tester.pumpWidget(host((MemoMap({'id': 1, 'a': 'y'}), true))); + expect(builds, 2); + await tester.pumpWidget(host((MemoMap({'id': 1, 'a': 'y'}), false))); + expect(builds, 3); + }); + + testWidgets('the built subtree still follows its inherited widgets', ( + tester, + ) async { + Widget host(Color color) => MaterialApp( + theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: color)), + home: MemoSubtree( + memo: 1, + builder: (_) => Builder( + builder: (context) => ColoredBox( + key: const Key('box'), + color: Theme.of(context).colorScheme.primary, + ), + ), + ), + ); + Color shown() => + tester.widget(find.byKey(const Key('box'))).color; + await tester.pumpWidget(host(Colors.red)); + final before = shown(); + await tester.pumpWidget(host(Colors.blue)); + await tester.pumpAndSettle(); + expect(shown(), isNot(before)); + }); +} diff --git a/app/test/ui/layout/sliver_reveal_test.dart b/app/test/ui/layout/sliver_reveal_test.dart new file mode 100644 index 00000000..efbd94a3 --- /dev/null +++ b/app/test/ui/layout/sliver_reveal_test.dart @@ -0,0 +1,107 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/layout/sliver_reveal.dart'; + +void main() { + Widget host({ + required bool open, + Duration duration = kThemeAnimationDuration, + }) => MaterialApp( + home: CustomScrollView( + slivers: [ + SliverReveal( + open: open, + duration: duration, + curve: Curves.easeInOut, + sliver: SliverList.builder( + itemCount: 1000, + itemBuilder: (_, index) => + SizedBox(height: 50, child: Text('item $index')), + ), + ), + const SliverToBoxAdapter(child: Text('after')), + ], + ), + ); + + double afterTop(WidgetTester tester) => + tester.getTopLeft(find.text('after')).dy; + + testWidgets('closed builds nothing; open builds only the visible items', ( + tester, + ) async { + await tester.pumpWidget(host(open: false)); + expect(find.textContaining('item'), findsNothing); + expect(afterTop(tester), 0); + + await tester.pumpWidget(host(open: true)); + await tester.pump(kThemeAnimationDuration ~/ 2); + // Part-way open: the items reveal from the top, clipped at the extent. + expect(find.text('item 0'), findsOneWidget); + await tester.pumpAndSettle(); + expect(find.text('item 0'), findsOneWidget); + expect(find.text('item 999', skipOffstage: false), findsNothing); + expect(tester.widgetList(find.textContaining('item')).length, lessThan(40)); + }); + + testWidgets('closing shrinks the extent, then drops the items', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: [ + SliverReveal( + open: true, + duration: kThemeAnimationDuration, + curve: Curves.linear, + sliver: SliverList.list( + children: [ + for (var i = 0; i < 4; i++) + SizedBox(height: 50, child: Text('item $i')), + ], + ), + ), + const SliverToBoxAdapter(child: Text('after')), + ], + ), + ), + ); + expect(afterTop(tester), 200); + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: [ + SliverReveal( + open: false, + duration: kThemeAnimationDuration, + curve: Curves.linear, + sliver: SliverList.list( + children: [ + for (var i = 0; i < 4; i++) + SizedBox(height: 50, child: Text('item $i')), + ], + ), + ), + const SliverToBoxAdapter(child: Text('after')), + ], + ), + ), + ); + await tester.pump(kThemeAnimationDuration ~/ 2); + expect(afterTop(tester), closeTo(100, 1)); + await tester.pumpAndSettle(); + expect(afterTop(tester), 0); + expect(find.textContaining('item'), findsNothing); + }); + + testWidgets('no motion opens and closes at once', (tester) async { + await tester.pumpWidget(host(open: false, duration: Duration.zero)); + await tester.pumpWidget(host(open: true, duration: Duration.zero)); + await tester.pump(); + expect(find.text('item 0'), findsOneWidget); + await tester.pumpWidget(host(open: false, duration: Duration.zero)); + await tester.pump(); + expect(find.textContaining('item'), findsNothing); + }); +} From 27dc4840e2233681a2cdff2725521cb1a89d4ed1 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 2 Nov 2026 00:22:22 +0000 Subject: [PATCH 4/4] Allow the runs burst bench for executing rows' clock-driven durations --- app/test/perf/background_work_bench_test.dart | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/app/test/perf/background_work_bench_test.dart b/app/test/perf/background_work_bench_test.dart index e5ca8117..30ce037c 100644 --- a/app/test/perf/background_work_bench_test.dart +++ b/app/test/perf/background_work_bench_test.dart @@ -211,9 +211,11 @@ void main() { controller.addListener(() => notifications++); await tester.pumpWidget(shell(AppDestination.runs)); await tester.pump(); + final rows = find.byType(RunListRow).evaluate().length; rebuilds ..reset() ..install(); + final wall = Stopwatch()..start(); // Frames arrive between frames on a real socket: pump after each. for (var i = 0; i < 50; i++) { frame(i); @@ -221,6 +223,7 @@ void main() { } await tester.pump(); rebuilds.uninstall(); + final seconds = wall.elapsed.inSeconds; // ignore: avoid_print print( 'BENCH visibleBurst50 controllerNotifications=$notifications ' @@ -238,8 +241,13 @@ void main() { // Only the ten frames that advance a step change anything visible. expect(notifications, lessThanOrEqualTo(10)); // Each notification rebuilds the one row whose run changed, not every - // built row (16 rows rebuilt per notification before memoized rows). - expect(rebuilds.of(RunListRow), lessThanOrEqualTo(notifications)); + // built row (16 rows rebuilt per notification before memoized rows). An + // executing row also rebuilds when its wall-clock duration text moves to + // the next second, at most once per second the burst took. + expect( + rebuilds.of(RunListRow), + lessThanOrEqualTo(notifications + rows * (seconds + 1)), + ); await tester.pumpWidget(const SizedBox()); }); }