Merge main
This commit is contained in:
@@ -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,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
@@ -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<String, ({Object? row, Object? inputs, Widget widget})> _held = {};
|
||||
Set<String> _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;
|
||||
}
|
||||
@@ -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<ChatThreadView> {
|
||||
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<ChatThreadView> {
|
||||
_controller = _attach();
|
||||
_composer = _attachComposer();
|
||||
_rowKeys = ChatRowKeys();
|
||||
_rowWidgets.clear();
|
||||
_chrome.clear();
|
||||
_dismissals = ChatNoticeDismissals();
|
||||
_reconnecting = false;
|
||||
_adoptCachedTranscript();
|
||||
@@ -757,8 +765,13 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
// 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<String>('chat-composer-${widget.sessionId}'),
|
||||
composer: _composer,
|
||||
running: _controller.running,
|
||||
@@ -775,6 +788,9 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
syncToken: widget.syncToken,
|
||||
),
|
||||
),
|
||||
);
|
||||
final column = FloatingBarOverlay(
|
||||
bar: composerBar,
|
||||
child: SegmentedBarOverlay(
|
||||
bar: _header(context, inShellBar),
|
||||
child: NotificationListener<ScrollMetricsNotification>(
|
||||
@@ -787,6 +803,24 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
// 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<String>(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<ChatThreadView> {
|
||||
padding: EdgeInsets.all(16),
|
||||
child: Text('No messages in this chat yet.'),
|
||||
),
|
||||
for (var index = 0; index < rows.length; index++)
|
||||
Padding(
|
||||
key: ValueKey<String>(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<ChatThreadView> {
|
||||
/// 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<ChatThreadView> {
|
||||
sessionId: widget.sessionId,
|
||||
session: session,
|
||||
onChanged: widget.onModelChanged,
|
||||
answeredBy: latestReplyModel(_controller.messages),
|
||||
answeredBy: answeredBy,
|
||||
),
|
||||
),
|
||||
if (hasMode)
|
||||
@@ -1061,7 +1092,11 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
});
|
||||
}
|
||||
|
||||
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<ChatThreadView> {
|
||||
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,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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),
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -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<String, List<MarkdownBlock>> _blocks = LinkedHashMap();
|
||||
int _chars = 0;
|
||||
|
||||
/// How many texts were actually parsed (cache misses).
|
||||
int parses = 0;
|
||||
|
||||
List<MarkdownBlock> blocksFor(String text) {
|
||||
final held = _blocks.remove(text);
|
||||
if (held != null) return _blocks[text] = held;
|
||||
final blocks = List<MarkdownBlock>.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();
|
||||
@@ -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<ChatMarkdownView> {
|
||||
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(
|
||||
|
||||
@@ -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) &&
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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';
|
||||
@@ -146,7 +147,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 +172,17 @@ class RunsList extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _groupedRuns(BuildContext context, List<Widget> header) {
|
||||
Widget _groupedRuns(
|
||||
BuildContext context,
|
||||
List<Widget> header,
|
||||
List<JsonMap> 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 +190,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),
|
||||
);
|
||||
}
|
||||
@@ -296,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,
|
||||
@@ -307,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,
|
||||
|
||||
Reference in New Issue
Block a user