Merge: perf round 1 — chat streaming rebuilds only the live turn
This commit is contained in:
@@ -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,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
Reference in New Issue
Block a user