Merge: perf round 2 — long chats open with only the visible rows

This commit is contained in:
2026-11-02 00:55:37 +00:00
14 changed files with 771 additions and 58 deletions
@@ -74,27 +74,35 @@ String chatJumpToLatestLabel(int newMessages) {
/// Where a conversation's transcript is placed when it first shows.
///
/// No saved position means the operator has none of their own: open at the
/// newest content. A saved offset is kept, clamped to the current end, so a
/// newest content. A saved offset is kept, clamped to the current extent, so a
/// conversation whose content grew or shrank while it was closed still lands on
/// a real position.
/// a real position. A bottom-anchored transcript measures older rows above its
/// centre, so its offsets (and [minScrollExtent]) can be negative.
double chatRestoreOffset({
required double? savedOffset,
required double maxScrollExtent,
double minScrollExtent = 0,
}) {
if (savedOffset == null) return maxScrollExtent;
return savedOffset.clamp(0.0, maxScrollExtent).toDouble();
return savedOffset.clamp(minScrollExtent, maxScrollExtent).toDouble();
}
/// A saved transcript position: the scroll offset and the message id of the
/// row the transcript was split at (see `chatTranscriptAnchor`), or null for a
/// top-anchored transcript whose offset counts from its first row. An offset
/// only means something measured from the same anchor.
typedef ChatScrollPosition = ({double offset, String? anchor});
/// Per-conversation transcript positions, kept while the chat list stays
/// mounted. A conversation opened again returns to the position the operator
/// left; one they never moved in opens at its newest message.
abstract interface class ChatScrollStore {
/// The offset the operator left this conversation at, or null when they never
/// scrolled away from its end.
double? read(String sessionId);
/// The position the operator left this conversation at, or null when they
/// never scrolled away from its end.
ChatScrollPosition? read(String sessionId);
/// Records a deliberate position away from the end.
void write(String sessionId, double offset);
void write(String sessionId, ChatScrollPosition position);
/// Forgets the position once the operator is following the end again.
void clear(String sessionId);
@@ -107,19 +115,22 @@ abstract interface class ChatScrollStore {
/// client keeps no transcript position on disk and does not import the web's
/// storage keys.
class MemoryChatScrollStore implements ChatScrollStore {
final Map<String, double> _offsets = {};
final Map<String, ChatScrollPosition> _offsets = {};
/// A snapshot of the stored offsets, so a test can tell a cleared
/// A snapshot of the stored positions, so a test can tell a cleared
/// conversation from one that was never moved.
Map<String, double> get entries => Map.unmodifiable(_offsets);
Map<String, ChatScrollPosition> get entries => Map.unmodifiable(_offsets);
@override
double? read(String sessionId) => _offsets[sessionId];
ChatScrollPosition? read(String sessionId) => _offsets[sessionId];
@override
void write(String sessionId, double offset) {
if (!offset.isFinite || offset < 0) return;
_offsets[sessionId] = offset;
void write(String sessionId, ChatScrollPosition position) {
// A top-anchored offset counts from the first row and is never negative;
// a bottom-anchored one is negative above its centre.
if (!position.offset.isFinite) return;
if (position.anchor == null && position.offset < 0) return;
_offsets[sessionId] = position;
}
@override
@@ -35,7 +35,9 @@ import '../../../ui/adaptive/segmented_bar_overlay.dart';
import '../../../ui/layout/app_sheet_header.dart';
import 'chat_reading_width.dart';
import 'chat_thread_header.dart';
import 'chat_transcript_anchor.dart';
import 'chat_transcript_cache.dart';
import 'chat_transcript_scroll_view.dart';
import 'chat_permission_card_model.dart';
import 'chat_permission_group.dart';
import 'chat_transcript_card.dart';
@@ -185,7 +187,12 @@ class _ChatThreadViewState extends State<ChatThreadView> {
/// The conversation's saved position, read when this view is attached and
/// consumed by the first placement after the history arrives.
double? _savedOffset;
ChatScrollPosition? _savedPosition;
/// The message id the transcript is split at (see [chatTranscriptAnchor]),
/// chosen once when the history first arrives; null keeps it top-anchored.
String? _anchor;
bool _anchorChosen = false;
bool _placed = false;
bool _pinScheduled = false;
@@ -196,6 +203,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
double? _restoreOffset;
bool _restoring = false;
double _restoreMeasuredExtent = 0;
double _restoreMeasuredStart = 0;
/// True during a pointer/touch/wheel scroll. Programmatic placement and
/// follow jumps never set it, so they cannot release the follow intent.
@@ -384,7 +392,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
@override
void initState() {
super.initState();
_savedOffset = widget.scrollPositions?.read(widget.sessionId);
_savedPosition = widget.scrollPositions?.read(widget.sessionId);
_adoptCachedTranscript();
_seedCommandNotice();
}
@@ -416,7 +424,9 @@ class _ChatThreadViewState extends State<ChatThreadView> {
_syncGeneration++;
_commandNotices.clear();
_seedCommandNotice();
_savedOffset = widget.scrollPositions?.read(widget.sessionId);
_savedPosition = widget.scrollPositions?.read(widget.sessionId);
_anchor = null;
_anchorChosen = false;
_placed = false;
_following = true;
_distanceFromBottom = null;
@@ -425,6 +435,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
_restoring = false;
_restoreOffset = null;
_restoreMeasuredExtent = 0;
_restoreMeasuredStart = 0;
_lastOffset = 0;
} else if (oldWidget.syncToken != widget.syncToken) {
// The socket was replaced: conditions recorded before the gap are stale,
@@ -489,11 +500,8 @@ class _ChatThreadViewState extends State<ChatThreadView> {
store.clear(id);
return;
}
if (_scroll.hasClients) {
store.write(id, _scroll.position.pixels);
} else {
store.write(id, _lastOffset);
}
final offset = _scroll.hasClients ? _scroll.position.pixels : _lastOffset;
store.write(id, (offset: offset, anchor: _anchor));
}
/// Measured distance from the end for the current content.
@@ -535,11 +543,21 @@ class _ChatThreadViewState extends State<ChatThreadView> {
/// the operator left one, otherwise the newest message.
void _placeFromStore() {
if (!_scroll.hasClients) return;
final saved = _savedPosition;
if (_anchor != null &&
saved == null &&
_scroll.position.minScrollExtent >= 0) {
// The rows above the centre do not fill the viewport, so a bottom-anchored
// list would leave a gap above them. A transcript this short is cheap to
// lay out whole: show it top-anchored, from its first row, as before.
setState(() => _anchor = null);
_scheduleFollow();
return;
}
_placed = true;
final saved = _savedOffset;
_savedOffset = null;
_savedPosition = null;
if (saved != null) {
_restoreOffset = saved;
_restoreOffset = saved.offset;
_restoring = true;
_following = false;
_newestAtRelease = null;
@@ -564,10 +582,12 @@ class _ChatThreadViewState extends State<ChatThreadView> {
final target = chatRestoreOffset(
savedOffset: _restoreOffset,
maxScrollExtent: end,
minScrollExtent: _scroll.position.minScrollExtent,
);
if (_scroll.position.pixels != target) _scroll.jumpTo(target);
_lastOffset = target;
_restoreMeasuredExtent = _scroll.position.maxScrollExtent;
_restoreMeasuredStart = _scroll.position.minScrollExtent;
_distanceFromBottom = chatBottomDistance(
maxScrollExtent: _restoreMeasuredExtent,
pixels: _scroll.position.pixels,
@@ -590,8 +610,12 @@ class _ChatThreadViewState extends State<ChatThreadView> {
}
if (_restoring) {
final measuredBefore = _restoreMeasuredExtent;
final startBefore = _restoreMeasuredStart;
_applyRestore();
if (_scroll.position.maxScrollExtent == measuredBefore) {
// Bottom-anchored, the older rows' estimated extent above the centre
// settles too, and a saved offset there is clamped to it.
if (_scroll.position.maxScrollExtent == measuredBefore &&
_scroll.position.minScrollExtent == startBefore) {
// The measured extent stopped changing: the restored offset is the
// operator's real position again, so follow intent can be judged.
_restoring = false;
@@ -680,6 +704,35 @@ class _ChatThreadViewState extends State<ChatThreadView> {
_restoreOffset = null;
}
/// The index of the row the transcript is split at, or -1 to keep it
/// top-anchored. The anchor is chosen once, when the history first arrives:
/// a saved position keeps the anchor it was measured from.
int _splitFor(List<JsonMap> rows) {
if (!_controller.loaded) return -1;
if (!_anchorChosen) {
_anchorChosen = true;
final saved = _savedPosition;
if (saved != null &&
saved.anchor != null &&
chatTranscriptAnchorIndex(rows, saved.anchor) < 0) {
// The row the position was measured from is gone: the offset no longer
// names a place in this transcript, so it opens at the newest message.
_savedPosition = null;
}
_anchor = _savedPosition == null
? chatTranscriptAnchor(rows)
: _savedPosition!.anchor;
}
var index = chatTranscriptAnchorIndex(rows, _anchor);
if (index < 0 && _anchor != null) {
// A repair replaced the transcript without the anchor row: split the new
// one afresh (a following view is pinned to its end again after layout).
_anchor = chatTranscriptAnchor(rows);
index = chatTranscriptAnchorIndex(rows, _anchor);
}
return index;
}
@override
Widget build(BuildContext context) => AnimatedBuilder(
animation: Listenable.merge([
@@ -743,6 +796,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
// its previous messages, keeping the element (and its open disclosures)
// across paging and streaming.
final keys = _rowKeys.forRows(rows);
final split = _splitFor(rows);
final initialLoad = !_controller.loaded && _controller.loading;
final historyNotice = _noticeOf(
notices,
@@ -825,11 +879,16 @@ class _ChatThreadViewState extends State<ChatThreadView> {
children: [
// At rest the first item starts below the floating bar
// and the last one ends above the floating composer.
ListView(
// Bottom-anchored at the split row, the newest rows are
// laid out first and older ones only when scrolled to.
ChatTranscriptScrollView(
key: ValueKey<String>(
'chat-thread-${widget.sessionId}',
),
controller: _scroll,
splitAfter: split < 0
? null
: ValueKey<String>(keys[split]),
padding: EdgeInsets.fromLTRB(
side,
media.top + 8,
@@ -0,0 +1,69 @@
import '../../../core/api_gateway.dart';
/// Where an opened transcript is split into its older and newer halves.
///
/// Opening a long conversation at its newest message used to lay out every row
/// above it: a top-anchored list can only reach its end by measuring the rows
/// in between. The transcript is instead a two-sided scroll view whose centre
/// sits between an anchor row and the rows after it. The anchor row and every
/// older row grow upwards from the centre; the rows after it (and the queued,
/// unsent and command lines) grow downwards. Opening lays out only what shows.
///
/// The split is fixed for as long as the conversation is open, so growth on
/// either side never moves the other: an older page loaded above, or a reply
/// streaming below, leaves the operator's reading position where it is. The
/// newest message row (and a reply that is still streaming) is never the
/// anchor or above it, because a row above the centre that grew would push the
/// rows above it up while the operator reads them.
///
/// Returns null when the transcript has fewer than two message rows: there is
/// nothing older to keep unmeasured, and the view stays top-anchored.
String? chatTranscriptAnchor(List<JsonMap> rows) {
var cut = -1;
for (var index = rows.length - 1; index >= 0; index--) {
if (_messageIds(rows[index]).isNotEmpty) {
cut = index;
break;
}
}
for (var index = 0; index < rows.length; index++) {
if (rows[index]['streaming'] == true && index < cut) {
cut = index;
break;
}
}
for (var index = cut - 1; index >= 0; index--) {
final ids = _messageIds(rows[index]);
if (ids.isNotEmpty) return ids.last;
}
return null;
}
/// The index of the row that holds [anchor], or -1 when no row does (a repair
/// replaced the transcript) or there is no anchor.
int chatTranscriptAnchorIndex(List<JsonMap> rows, String? anchor) {
if (anchor == null) return -1;
for (var index = rows.length - 1; index >= 0; index--) {
if (_messageIds(rows[index]).contains(anchor)) return index;
}
return -1;
}
/// The stored message ids of one user or assistant row. Cards, activity lines
/// and the pending-response shell carry none and can never be an anchor.
List<String> _messageIds(JsonMap row) {
final kind = row['kind'];
if (kind == 'assistant') {
final listed = row['messageIds'];
if (listed is! List) return const [];
return [
for (final id in listed)
if ('$id'.trim().isNotEmpty) '$id'.trim(),
];
}
if (kind == 'user') {
final id = '${row['key'] ?? ''}'.trim();
return id.isEmpty ? const [] : [id];
}
return const [];
}
@@ -0,0 +1,64 @@
import 'package:flutter/widgets.dart';
/// The transcript's scrollable: older rows above a centre, newer rows below.
///
/// With [splitAfter], the children up to and including the one with that key
/// sit above the centre and the rest below it. The centre is at the viewport's
/// bottom edge at offset zero: the older children grow upwards from it and the
/// newer ones downwards, so the newest rows are laid out first and an older row
/// only when it is scrolled to. Offsets above the centre are negative.
///
/// Without one (or when no child has that key) this is a plain top-anchored
/// list starting at its first child. A transcript that fits its viewport stays
/// top-anchored, so a short conversation still reads from the top.
///
/// [padding] keeps the first child below the floating bar and the last child
/// above the floating composer, as a list's padding would.
class ChatTranscriptScrollView extends StatelessWidget {
const ChatTranscriptScrollView({
super.key,
required this.controller,
required this.padding,
required this.children,
this.splitAfter,
});
static const _centre = ValueKey<String>('chat-thread-newer');
final ScrollController controller;
final EdgeInsets padding;
final List<Widget> children;
final Key? splitAfter;
@override
Widget build(BuildContext context) {
final split = splitAfter == null
? -1
: children.indexWhere((child) => child.key == splitAfter);
final anchored = split >= 0;
return CustomScrollView(
controller: controller,
center: _centre,
anchor: anchored ? 1 : 0,
slivers: [
// Before the centre, a sliver grows upwards: its first child sits at
// the centre, so the older children go in newest-first.
SliverPadding(
padding: anchored ? padding.copyWith(bottom: 0) : EdgeInsets.zero,
sliver: SliverList(
delegate: SliverChildListDelegate([
for (var index = split; index >= 0; index--) children[index],
]),
),
),
SliverPadding(
key: _centre,
padding: anchored ? padding.copyWith(top: 0) : padding,
sliver: SliverList(
delegate: SliverChildListDelegate(children.sublist(split + 1)),
),
),
],
);
}
}