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.
This commit is contained in:
2026-11-02 00:08:29 +00:00
parent b3b761c56d
commit 7b1455631b
16 changed files with 889 additions and 152 deletions
@@ -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<CoverSizedMemoryImage> {
const CoverSizedMemoryImage(
this.bytes, {
required this.width,
required this.height,
});
final Uint8List bytes;
final int width;
final int height;
@override
Future<CoverSizedMemoryImage> obtainKey(ImageConfiguration configuration) =>
SynchronousFuture<CoverSizedMemoryImage>(this);
@override
ImageStreamCompleter loadImage(
CoverSizedMemoryImage key,
ImageDecoderCallback decode,
) => MultiFrameImageStreamCompleter(
codec: _decode(key, decode),
scale: 1,
debugLabel: 'CoverSizedMemoryImage(${describeIdentity(key.bytes)})',
);
static Future<ui.Codec> _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()),
);
}
@@ -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<ArtifactThumbnail> createState() => _ArtifactThumbnailState();
}
class _ArtifactThumbnailState extends State<ArtifactThumbnail> {
class _ArtifactThumbnailState extends State<ArtifactThumbnail>
with AutomaticKeepAliveClientMixin {
Future<ArtifactFetchResult>? _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<ArtifactThumbnail> {
@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<ArtifactThumbnail> {
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),
);
},
);
},
);
@@ -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<ArtifactVisitList> {
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<ArtifactVisitList> {
child: Text('$count'),
),
],
body: body,
sliverBody: body,
);
Widget _modeSwitch(BuildContext context) {
@@ -241,70 +249,89 @@ class _ArtifactVisitListState extends State<ArtifactVisitList> {
);
}
/// 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<String>(
'${artifactVisitIdentity(group, group.artifacts[index])}'
'\u0000$index',
),
key: ValueKey<String>('$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<String>(
'${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<String>(
'${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,
),
),
],
],
),
],
);
},
),
);
},
@@ -175,6 +175,13 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
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<void> _hide(JsonMap session) async {
await _controller.hide(_sessionId(session));
_undoTimer?.cancel();
@@ -226,12 +233,8 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
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();
@@ -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<JsonMap> onStar,
required ValueChanged<JsonMap> onRename,
required ValueChanged<JsonMap> onClose,
required ValueChanged<JsonMap> onReopen,
required ValueChanged<JsonMap> 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);
@@ -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<JsonMap> onStar,
required ValueChanged<JsonMap> onRename,
required ValueChanged<JsonMap> onClose,
required ValueChanged<JsonMap> onReopen,
required ValueChanged<JsonMap> 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);
}
}
@@ -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<String> duplicateTitles,
required bool unseen,
required bool divider,
required ValueChanged<JsonMap> onOpen,
required ValueChanged<JsonMap> onStar,
required ValueChanged<JsonMap> onRename,
required ValueChanged<JsonMap> onClose,
required ValueChanged<JsonMap> onReopen,
required ValueChanged<JsonMap> 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),
},
),
);
+23 -1
View File
@@ -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,