From 7b1455631b4c2e6e6c1e6fd22a24bf8d3c21296e Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 2 Nov 2026 00:08:29 +0000 Subject: [PATCH 1/2] 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 2/2] 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()); }); }