From e4c196d75bb305435a0f968276758e03f73a78d4 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 17:15:14 +0100 Subject: [PATCH] feat(app): follow streamed chat and restore its read position Transcripts pin to the newest end while following, release on the operator's upward scroll, and offer a native Jump to latest control carrying the count of messages that arrived meanwhile. The chat destination keeps each conversation's saved position so reopening restores it. --- .../chat/conversation/chat_scroll.dart | 125 ++++ .../chat/conversation/chat_thread_view.dart | 648 ++++++++++++++---- app/lib/features/chat/screen.dart | 6 + .../chat/conversation/chat_scroll_test.dart | 142 ++++ .../conversation/chat_thread_scroll_test.dart | 284 ++++++++ 5 files changed, 1063 insertions(+), 142 deletions(-) create mode 100644 app/lib/features/chat/conversation/chat_scroll.dart create mode 100644 app/test/features/chat/conversation/chat_scroll_test.dart create mode 100644 app/test/features/chat/conversation/chat_thread_scroll_test.dart diff --git a/app/lib/features/chat/conversation/chat_scroll.dart b/app/lib/features/chat/conversation/chat_scroll.dart new file mode 100644 index 00000000..90334da5 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_scroll.dart @@ -0,0 +1,125 @@ +import 'dart:math' as math; + +/// How close the transcript's end must be to the viewport's bottom edge before +/// the view counts as following it. A deliberate position further up is the +/// operator's own and must never be snapped back by a streamed frame. +const double chatFollowThresholdPx = 32; + +/// The pixels the transcript's end still sits below the viewport's bottom edge. +/// +/// Zero means the end is in view; null means the list has no content to measure. +/// A viewport that is overscrolled past the end never reports a negative +/// distance, so following is a simple threshold check. +double? chatBottomDistance({ + required double maxScrollExtent, + required double pixels, + required int itemCount, +}) { + if (itemCount <= 0) return null; + return math.max(0, maxScrollExtent - pixels); +} + +/// Whether the end of the transcript is at (or within the follow threshold of) +/// the viewport's bottom edge. +bool chatFollowsAt( + double? distanceFromBottom, { + required int itemCount, + double threshold = chatFollowThresholdPx, +}) => + itemCount > 0 && + distanceFromBottom != null && + distanceFromBottom <= threshold; + +/// Whether to offer the jump-to-latest control: only while the view is not +/// following and something is below the fold. A list that fits its viewport is +/// never offered the control, because there is nothing to return to. +bool chatShowsJumpToLatest({ + required bool following, + required double? distanceFromBottom, + required int itemCount, + double threshold = chatFollowThresholdPx, +}) => + !following && + itemCount > 0 && + !chatFollowsAt( + distanceFromBottom, + itemCount: itemCount, + threshold: threshold, + ); + +/// How many messages arrived after the operator left the bottom. +/// +/// [newestAtRelease] is the id of the last message at the moment the operator +/// scrolled away. Only messages after that id count, so an older page that is +/// prepended while they read is not reported as an arrival and a delta growing +/// the held answer is not a new message. An id that no longer exists (a repair +/// replaced the transcript) reports no arrivals until the operator returns. +int chatNewMessageCount(List messageIds, String? newestAtRelease) { + if (newestAtRelease == null) return 0; + final index = messageIds.lastIndexOf(newestAtRelease); + if (index < 0) return 0; + return messageIds.length - index - 1; +} + +/// The jump control's words, with the web's action and the arrival count the +/// native client adds while the operator is reading above the end. +String chatJumpToLatestLabel(int newMessages) { + if (newMessages <= 0) return 'Jump to latest'; + final suffix = newMessages == 1 ? '1 new message' : '$newMessages new messages'; + return 'Jump to latest · $suffix'; +} + +/// 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 +/// conversation whose content grew or shrank while it was closed still lands on +/// a real position. +double chatRestoreOffset({ + required double? savedOffset, + required double maxScrollExtent, +}) { + if (savedOffset == null) return maxScrollExtent; + return savedOffset.clamp(0.0, maxScrollExtent).toDouble(); +} + +/// 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); + + /// Records a deliberate position away from the end. + void write(String sessionId, double offset); + + /// Forgets the position once the operator is following the end again. + void clear(String sessionId); +} + +/// In-memory storage for the app's chat destination and for tests. +/// +/// A surfaced position survives the conversation view being disposed and +/// reopened with the chat destination, but not a process restart. This native +/// client keeps no transcript position on disk and does not import the web's +/// storage keys. +class MemoryChatScrollStore implements ChatScrollStore { + final Map _offsets = {}; + + /// A snapshot of the stored offsets, so a test can tell a cleared + /// conversation from one that was never moved. + Map get entries => Map.unmodifiable(_offsets); + + @override + double? read(String sessionId) => _offsets[sessionId]; + + @override + void write(String sessionId, double offset) { + if (!offset.isFinite || offset < 0) return; + _offsets[sessionId] = offset; + } + + @override + void clear(String sessionId) => _offsets.remove(sessionId); +} diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index ce85ad5b..1e77f5d6 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; import '../../../core/api_gateway.dart'; import '../domain/chat_activity_detail.dart'; @@ -16,6 +17,7 @@ import 'chat_draft_store.dart'; import 'chat_model_control.dart'; import 'chat_models.dart'; import 'chat_row_keys.dart'; +import 'chat_scroll.dart'; import 'chat_thread_controller.dart'; import 'chat_transcript_card.dart'; @@ -41,6 +43,7 @@ class ChatThreadView extends StatefulWidget { this.syncToken = 0, this.drafts, this.newOperationId, + this.scrollPositions, }); final ApiGateway gateway; @@ -68,6 +71,11 @@ class ChatThreadView extends StatefulWidget { /// Test/fixture seam for deterministic operation ids. final String Function()? newOperationId; + /// The destination's per-conversation scroll store. The screen supplies one + /// that outlives this view, so a conversation opened again returns to where + /// the operator left it. Null keeps the view stateless across visits. + final ChatScrollStore? scrollPositions; + @override State createState() => _ChatThreadViewState(); } @@ -99,6 +107,45 @@ class _ChatThreadViewState extends State { /// A sent turn shown before history or a live frame echoes it. final List _optimistic = []; + final ScrollController _scroll = ScrollController(); + + /// True while the transcript's end is in view. The operator's own upward + /// scroll releases it; only returning to the end (or the jump control) arms + /// it again. + bool _following = true; + + /// The measured distance from the transcript's end, or null before layout. + /// Not every scrolled pixel rebuilds the view; the jump control only needs to + /// know whether the end is beyond the follow threshold. + double? _distanceFromBottom; + + /// The conversation's saved position, read when this view is attached and + /// consumed by the first placement after the history arrives. + double? _savedOffset; + bool _placed = false; + bool _pinScheduled = false; + + /// A saved position is being re-applied while the lazy transcript's measured + /// extent is still settling. Until it stops growing, an apparent "bottom" + /// would be a stale estimate and would silently turn a restored read into a + /// follow. + double? _restoreOffset; + bool _restoring = false; + double _restoreMeasuredExtent = 0; + + /// True during a pointer/touch/wheel scroll. Programmatic placement and + /// follow jumps never set it, so they cannot release the follow intent. + bool _userScrolling = false; + + /// The last measured offset. Kept separately because the scrollable can + /// detach before this state is disposed; disposal still has to save where the + /// operator was. + double _lastOffset = 0; + + /// The newest message id when the operator left the end. Later messages are + /// counted against it for the jump control's arrival count. + String? _newestAtRelease; + ChatThreadController _attach() => ChatThreadController(widget.gateway, widget.sessionId)..load(); @@ -183,11 +230,19 @@ class _ChatThreadViewState extends State { return native.isNotEmpty && native == message['native_message_id']; } + @override + void initState() { + super.initState(); + _savedOffset = widget.scrollPositions?.read(widget.sessionId); + } + @override void didUpdateWidget(covariant ChatThreadView oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.gateway != widget.gateway || oldWidget.sessionId != widget.sessionId) { + // The conversation being left keeps the position the operator chose. + _persistPosition(oldWidget.sessionId); _controller.dispose(); _composer.dispose(); _controller = _attach(); @@ -198,6 +253,16 @@ class _ChatThreadViewState extends State { _preGapMessages = null; _syncGeneration++; _optimistic.clear(); + _savedOffset = widget.scrollPositions?.read(widget.sessionId); + _placed = false; + _following = true; + _distanceFromBottom = null; + _newestAtRelease = null; + _userScrolling = false; + _restoring = false; + _restoreOffset = null; + _restoreMeasuredExtent = 0; + _lastOffset = 0; } else if (oldWidget.syncToken != widget.syncToken) { // The socket was replaced: conditions recorded before the gap are stale, // so no earlier dismissal survives and nothing recorded before the gap is @@ -230,11 +295,228 @@ class _ChatThreadViewState extends State { @override void dispose() { + _persistPosition(); + _scroll.dispose(); _composer.dispose(); _controller.dispose(); super.dispose(); } + /// The ids of the transcript's messages in view order. Cards are conversation + /// state, not messages, so a pending approval does not count as an arrival. + List _messageIds() => [ + for (final message in _visibleMessages()) + if ('${message['id'] ?? ''}'.trim().isNotEmpty) '${message['id']}'.trim(), + ]; + + String? _newestMessageId() { + final ids = _messageIds(); + return ids.isEmpty ? null : ids.last; + } + + /// Writes the operator's position for the conversation being left: a + /// deliberate position is remembered, following the end is not. Called on a + /// scroll's end, a conversation switch and disposal. + void _persistPosition([String? sessionId]) { + final store = widget.scrollPositions; + final id = sessionId ?? widget.sessionId; + if (store == null || !_placed || _restoring) return; + if (_following) { + store.clear(id); + return; + } + if (_scroll.hasClients) { + store.write(id, _scroll.position.pixels); + } else { + store.write(id, _lastOffset); + } + } + + /// Measured distance from the end for the current content. + double? _distanceFor(ScrollMetrics metrics, int itemCount) => + chatBottomDistance( + maxScrollExtent: metrics.maxScrollExtent, + pixels: metrics.pixels, + itemCount: itemCount, + ); + + /// Adopts a measured position as the follow intent. Crossing out of the + /// bottom records the newest message then, so only later arrivals are counted. + void _updateFollow(ScrollMetrics metrics) { + final ids = _messageIds(); + final distance = _distanceFor(metrics, ids.length); + final following = chatFollowsAt(distance, itemCount: ids.length); + _distanceFromBottom = distance; + _lastOffset = metrics.pixels; + if (following == _following) return; + setState(() { + _following = following; + _newestAtRelease = following ? null : _newestMessageId(); + }); + } + + /// Puts the transcript at its end without animation, the way the web's + /// `scrollTop = scrollHeight` does. Used both for following and the control. + void _jumpToBottom() { + if (!_scroll.hasClients) return; + final end = _scroll.position.maxScrollExtent; + if (_scroll.position.pixels != end) _scroll.jumpTo(end); + _lastOffset = end; + _distanceFromBottom = 0; + _following = true; + _newestAtRelease = null; + } + + /// The first placement after the held history arrives: the saved position when + /// the operator left one, otherwise the newest message. + void _placeFromStore() { + if (!_scroll.hasClients) return; + _placed = true; + final saved = _savedOffset; + _savedOffset = null; + if (saved != null) { + _restoreOffset = saved; + _restoring = true; + _following = false; + _newestAtRelease = null; + // The control must appear as soon as a saved position exists, even while + // the lazy extent is still settling; this runs after layout, so a rebuild + // is safe. + setState(() {}); + _applyRestore(); + _scheduleFollow(); + return; + } + _jumpToBottom(); + _persistPosition(); + } + + /// Puts the viewport at the saved position within the currently measured + /// extent. Re-applied while the extent settles, so a growing lazy list cannot + /// turn the restored read into an accidental follow. + void _applyRestore() { + if (!_scroll.hasClients) return; + final end = _scroll.position.maxScrollExtent; + final target = chatRestoreOffset( + savedOffset: _restoreOffset, + maxScrollExtent: end, + ); + if (_scroll.position.pixels != target) _scroll.jumpTo(target); + _lastOffset = target; + _restoreMeasuredExtent = _scroll.position.maxScrollExtent; + _distanceFromBottom = chatBottomDistance( + maxScrollExtent: _restoreMeasuredExtent, + pixels: _scroll.position.pixels, + itemCount: _messageIds().length, + ); + } + + /// Places the first loaded transcript and keeps a following view at the end + /// after every rebuild. Runs after layout so the newest extent is known; a pin + /// is never scheduled while the operator is scrolling. + void _scheduleFollow() { + if (_pinScheduled) return; + _pinScheduled = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + _pinScheduled = false; + if (!mounted || !_scroll.hasClients || !_controller.loaded) return; + if (!_placed) { + _placeFromStore(); + return; + } + if (_restoring) { + final measuredBefore = _restoreMeasuredExtent; + _applyRestore(); + if (_scroll.position.maxScrollExtent == measuredBefore) { + // The measured extent stopped changing: the restored offset is the + // operator's real position again, so follow intent can be judged. + _restoring = false; + _restoreOffset = null; + _updateFollow(_scroll.position); + // The settled distance decides whether the control is offered; the + // frames that settled it ran without a follow-intent change. + setState(() {}); + _persistPosition(); + } else { + _scheduleFollow(); + } + return; + } + if (_following && !_userScrolling) _jumpToBottom(); + }); + } + + /// Follows a list whose measured extent grew without a scroll, as a lazily + /// built transcript does while its newest turn wraps onto more lines. The jump + /// itself happens after layout, when the new extent is the settled one. + bool _onScrollMetrics(ScrollMetricsNotification notification) { + if (notification.depth != 0 || + notification.metrics.axis != Axis.vertical || + !_placed) { + return false; + } + if (_restoring) { + // The lazy extent is still growing; re-place the saved offset once the + // next layout has measured the new content. + _scheduleFollow(); + return false; + } + if (!_following || _userScrolling || !_scroll.hasClients) return false; + if (_scroll.position.pixels < _scroll.position.maxScrollExtent) { + _scheduleFollow(); + } + return false; + } + + /// Follows only the transcript's own vertical scroll. A code fence's or + /// table's horizontal scroll bubbles through this listener too and must not + /// release the conversation's follow intent. + bool _onScrollNotification(ScrollNotification notification) { + if (notification.depth != 0 || + notification.metrics.axis != Axis.vertical) { + return false; + } + if (notification is UserScrollNotification) { + _userScrolling = notification.direction != ScrollDirection.idle; + if (_userScrolling) _abandonRestore(); + } else if (notification is ScrollStartNotification) { + if (notification.dragDetails != null) { + _userScrolling = true; + _abandonRestore(); + } + } else if (notification is ScrollUpdateNotification) { + if (_userScrolling) _updateFollow(notification.metrics); + } else if (notification is ScrollEndNotification) { + if (_userScrolling) { + _updateFollow(notification.metrics); + _persistPosition(); + // Releasing a scroll within the threshold returns to the end, exactly + // like a follow check at the bottom of the web's wheel handler. + if (_following) _jumpToBottom(); + } + _userScrolling = false; + } + return false; + } + + void _followLatest() { + setState(() { + _following = true; + _newestAtRelease = null; + _distanceFromBottom = 0; + }); + _abandonRestore(); + _jumpToBottom(); + _persistPosition(); + } + + /// The operator took over while a saved position was still being re-applied; + /// their own scroll is authoritative from that point. + void _abandonRestore() { + _restoring = false; + _restoreOffset = null; + } + @override Widget build(BuildContext context) => AnimatedBuilder( animation: _controller, @@ -288,160 +570,193 @@ class _ChatThreadViewState extends State { ChatNoticeKind.connectionRefused, ); final liveNotice = _noticeOf(notices, ChatNoticeKind.liveFailure); + final messageIds = _messageIds(); + final newMessages = chatNewMessageCount(messageIds, _newestAtRelease); + final showJump = chatShowsJumpToLatest( + following: _following, + distanceFromBottom: _distanceFromBottom, + itemCount: messageIds.length, + ); + // Place the first loaded transcript and keep a following view at the end. + // Scheduling after the build means the new extent is already laid out. + _scheduleFollow(); return Column( children: [ Expanded( - child: ListView( - key: ValueKey('chat-thread-${widget.sessionId}'), - padding: const EdgeInsets.symmetric(vertical: 8), - children: [ - Padding( - key: const Key('chat-thread-header'), - padding: const EdgeInsetsDirectional.fromSTEB(4, 0, 4, 4), - child: LayoutBuilder( - builder: (context, constraints) { - final title = widget.title.trim(); - final session = widget.session; - final hasModel = - session != null && - supportsChatModels('${session['backend'] ?? ''}'); - // One compact row, as on the web: back, the conversation's - // name, its model and the information action. The title - // takes the remaining width and ellipsises; the model keeps - // a bounded share so neither control is pushed off a narrow - // 2x phone and the header never wraps onto a second line. - return Row( - children: [ - _backButton(cupertino), - Expanded( - child: Padding( - padding: const EdgeInsetsDirectional.only( - start: 4, - ), - child: title.isEmpty - ? const SizedBox.shrink() - : Text( - title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: cupertino - ? CupertinoTheme.of( - context, - ).textTheme.navTitleTextStyle - : Theme.of( - context, - ).textTheme.titleLarge, + child: NotificationListener( + onNotification: _onScrollMetrics, + child: NotificationListener( + onNotification: _onScrollNotification, + child: Stack( + children: [ + ListView( + key: ValueKey('chat-thread-${widget.sessionId}'), + controller: _scroll, + padding: const EdgeInsets.symmetric(vertical: 8), + children: [ + Padding( + key: const Key('chat-thread-header'), + padding: const EdgeInsetsDirectional.fromSTEB(4, 0, 4, 4), + child: LayoutBuilder( + builder: (context, constraints) { + final title = widget.title.trim(); + final session = widget.session; + final hasModel = + session != null && + supportsChatModels('${session['backend'] ?? ''}'); + // One compact row, as on the web: back, the conversation's + // name, its model and the information action. The title + // takes the remaining width and ellipsises; the model keeps + // a bounded share so neither control is pushed off a narrow + // 2x phone and the header never wraps onto a second line. + return Row( + children: [ + _backButton(cupertino), + Expanded( + child: Padding( + padding: const EdgeInsetsDirectional.only( + start: 4, + ), + child: title.isEmpty + ? const SizedBox.shrink() + : Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: cupertino + ? CupertinoTheme.of( + context, + ).textTheme.navTitleTextStyle + : Theme.of( + context, + ).textTheme.titleLarge, + ), + ), + ), + if (hasModel) + ConstrainedBox( + constraints: BoxConstraints( + maxWidth: constraints.maxWidth * 0.4, + ), + child: ChatModelControl( + key: ValueKey( + 'chat-model-${widget.sessionId}', + ), + gateway: widget.gateway, + sessionId: widget.sessionId, + session: session, + onChanged: widget.onModelChanged, + ), + ), + ChatBarAction( + key: const Key('chat-info'), + label: 'Chat information', + onPressed: _openInfo, + materialIcon: Icons.info_outline, + cupertinoIcon: CupertinoIcons.info, + ), + ], + ); + }, + ), + ), + if (initialLoad) + Padding( + key: const Key('chat-thread-loading'), + padding: const EdgeInsets.all(16), + child: Center( + child: cupertino + ? const CupertinoActivityIndicator() + : const CircularProgressIndicator(), + ), + ), + if (_controller.hasMore) + Padding( + key: const Key('chat-load-older'), + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Align( + alignment: AlignmentDirectional.centerStart, + child: cupertino + ? CupertinoButton( + padding: EdgeInsets.zero, + onPressed: _controller.loading + ? null + : _controller.loadOlder, + child: const Text('Load older'), + ) + : TextButton( + onPressed: _controller.loading + ? null + : _controller.loadOlder, + child: const Text('Load older'), ), ), ), - if (hasModel) - ConstrainedBox( - constraints: BoxConstraints( - maxWidth: constraints.maxWidth * 0.4, - ), - child: ChatModelControl( - key: ValueKey( - 'chat-model-${widget.sessionId}', - ), - gateway: widget.gateway, - sessionId: widget.sessionId, - session: session, - onChanged: widget.onModelChanged, - ), - ), - ChatBarAction( - key: const Key('chat-info'), - label: 'Chat information', - onPressed: _openInfo, - materialIcon: Icons.info_outline, - cupertinoIcon: CupertinoIcons.info, + if (historyNotice != null) + _ChatNoticeLine( + key: const Key('chat-history-error'), + notice: historyNotice, + onDismiss: _dismiss, + onRetry: _controller.load, ), - ], - ); - }, - ), - ), - if (initialLoad) - Padding( - key: const Key('chat-thread-loading'), - padding: const EdgeInsets.all(16), - child: Center( - child: cupertino - ? const CupertinoActivityIndicator() - : const CircularProgressIndicator(), - ), - ), - if (_controller.hasMore) - Padding( - key: const Key('chat-load-older'), - padding: const EdgeInsets.symmetric(horizontal: 16), - child: Align( - alignment: AlignmentDirectional.centerStart, - child: cupertino - ? CupertinoButton( - padding: EdgeInsets.zero, - onPressed: _controller.loading - ? null - : _controller.loadOlder, - child: const Text('Load older'), - ) - : TextButton( - onPressed: _controller.loading - ? null - : _controller.loadOlder, - child: const Text('Load older'), + if (liveNotice != null) + _ChatNoticeLine( + key: const Key('chat-live-error'), + notice: liveNotice, + onDismiss: _dismiss, + onRetry: _controller.resync, + ), + if (_controller.loaded && + allRows.isEmpty && + allNotices.isEmpty && + _controller.error == null) + const Padding( + key: Key('chat-thread-empty'), + padding: EdgeInsets.all(16), + child: Text('No messages in this chat yet.'), + ), + for (var index = 0; index < rows.length; index++) + Padding( + key: ValueKey(keys[index]), + padding: const EdgeInsets.symmetric(horizontal: 16), + child: _transcriptRow( + rows[index], + onDismissCompaction: + compactionNotice != null && + chatNoticeActivityCondition(rows[index]) == + compactionNotice.condition + ? () => _dismiss(compactionNotice) + : null, ), + ), + if (_controller.running && !awaiting) + Padding( + key: const Key('chat-running'), + padding: const EdgeInsets.all(16), + child: Semantics( + liveRegion: true, + child: const Text('Assistant is responding…'), + ), + ), + ], ), - ), - if (historyNotice != null) - _ChatNoticeLine( - key: const Key('chat-history-error'), - notice: historyNotice, - onDismiss: _dismiss, - onRetry: _controller.load, - ), - if (liveNotice != null) - _ChatNoticeLine( - key: const Key('chat-live-error'), - notice: liveNotice, - onDismiss: _dismiss, - onRetry: _controller.resync, - ), - if (_controller.loaded && - allRows.isEmpty && - allNotices.isEmpty && - _controller.error == null) - const Padding( - key: Key('chat-thread-empty'), - padding: EdgeInsets.all(16), - child: Text('No messages in this chat yet.'), - ), - for (var index = 0; index < rows.length; index++) - Padding( - key: ValueKey(keys[index]), - padding: const EdgeInsets.symmetric(horizontal: 16), - child: _transcriptRow( - rows[index], - onDismissCompaction: - compactionNotice != null && - chatNoticeActivityCondition(rows[index]) == - compactionNotice.condition - ? () => _dismiss(compactionNotice) - : null, + if (showJump) + PositionedDirectional( + end: 16, + bottom: 16, + child: _ChatJumpToLatest( + key: const Key('chat-jump-to-latest'), + label: chatJumpToLatestLabel(newMessages), + cupertino: cupertino, + onPressed: _followLatest, + ), ), - ), - if (_controller.running && !awaiting) - Padding( - key: const Key('chat-running'), - padding: const EdgeInsets.all(16), - child: Semantics( - liveRegion: true, - child: const Text('Assistant is responding…'), - ), - ), - ], + ], + ), + ), ), ), + ChatComposerBar( key: ValueKey('chat-composer-${widget.sessionId}'), composer: _composer, @@ -865,6 +1180,55 @@ class _ChatInfoRow extends StatelessWidget { } } +/// The transcript's follow control: a standard filled button that returns to the +/// end and says how many messages arrived while the operator was reading above +/// it. The count is part of the visible label and therefore its accessible name. +class _ChatJumpToLatest extends StatelessWidget { + const _ChatJumpToLatest({ + super.key, + required this.label, + required this.cupertino, + required this.onPressed, + }); + + final String label; + final bool cupertino; + final VoidCallback onPressed; + + @override + Widget build(BuildContext context) { + final button = cupertino + ? CupertinoButton.filled( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + onPressed: onPressed, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + CupertinoIcons.arrow_down, + color: CupertinoTheme.of(context).primaryContrastingColor, + ), + const SizedBox(width: 8), + Flexible(child: Text(label, textAlign: TextAlign.center)), + ], + ), + ) + : FilledButton.tonalIcon( + onPressed: onPressed, + icon: const Icon(Icons.arrow_downward), + label: Text(label, textAlign: TextAlign.center), + ); + // A long count at a large text scale wraps inside the pane instead of + // pushing the control past the transcript's edge. + return ConstrainedBox( + constraints: BoxConstraints( + maxWidth: MediaQuery.sizeOf(context).width - 32, + ), + child: button, + ); + } +} + /// One recorded activity line for a turn. /// /// The line is a summary of the recorded sequence. Its wording and state come diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index d34de564..202f3ef2 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import '../../core/api_gateway.dart'; import 'conversation/chat_models.dart'; +import 'conversation/chat_scroll.dart'; import 'conversation/chat_thread_view.dart'; import 'ui/sessions/chat_sessions_screen.dart'; @@ -48,6 +49,10 @@ class _ChatScreenState extends State { /// for the rest of this visit, including when the same chat is reopened. final Map _acceptedModels = {}; + /// Transcript positions for this visit. It lives with the destination, not a + /// conversation view, so Back and a reopened chat return to the same place. + final ChatScrollStore _scrollPositions = MemoryChatScrollStore(); + String? _standaloneSelection; String? get _selected { @@ -133,6 +138,7 @@ class _ChatScreenState extends State { title: '${row?['title'] ?? ''}'.trim(), session: row, syncToken: widget.syncToken, + scrollPositions: _scrollPositions, onBack: _back, onModelChanged: (applied) => _modelChanged(selected, applied), ), diff --git a/app/test/features/chat/conversation/chat_scroll_test.dart b/app/test/features/chat/conversation/chat_scroll_test.dart new file mode 100644 index 00000000..ba7205f0 --- /dev/null +++ b/app/test/features/chat/conversation/chat_scroll_test.dart @@ -0,0 +1,142 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_scroll.dart'; + +void main() { + group('follow geometry', () { + test('a transcript with no content has no distance or follow state', () { + expect( + chatBottomDistance(maxScrollExtent: 0, pixels: 0, itemCount: 0), + isNull, + ); + expect(chatFollowsAt(null, itemCount: 0), isFalse); + }); + + test('the distance never goes negative past the end', () { + expect( + chatBottomDistance(maxScrollExtent: 800, pixels: 300, itemCount: 3), + 500, + ); + expect( + chatBottomDistance(maxScrollExtent: 800, pixels: 900, itemCount: 3), + 0, + ); + }); + + test('the follow threshold includes its boundary and needs an item', () { + expect(chatFollowsAt(0, itemCount: 3), isTrue); + expect(chatFollowsAt(32, itemCount: 3), isTrue); + expect(chatFollowsAt(33, itemCount: 3), isFalse); + expect(chatFollowsAt(null, itemCount: 3), isFalse); + expect(chatFollowsAt(0, itemCount: 0), isFalse); + }); + }); + + group('jump control', () { + test('is offered only when not following with content below the fold', () { + expect( + chatShowsJumpToLatest( + following: false, + distanceFromBottom: 400, + itemCount: 5, + ), + isTrue, + ); + expect( + chatShowsJumpToLatest( + following: true, + distanceFromBottom: 400, + itemCount: 5, + ), + isFalse, + ); + // The end is in view, so there is nothing to return to. + expect( + chatShowsJumpToLatest( + following: false, + distanceFromBottom: 0, + itemCount: 5, + ), + isFalse, + ); + expect( + chatShowsJumpToLatest( + following: false, + distanceFromBottom: 400, + itemCount: 0, + ), + isFalse, + ); + }); + }); + + group('arrival count', () { + test('counts only messages after the release point', () { + expect( + chatNewMessageCount(['m1', 'm2', 'm3'], 'm2'), + 1, + ); + expect( + chatNewMessageCount(['older', 'm1', 'm2', 'live', 'newer'], 'm2'), + 2, + ); + // A growing delta keeps the same id and is not a new message. + expect(chatNewMessageCount(['m1', 'm2'], 'm2'), 0); + }); + + test('reports nothing without a release point or a surviving message', () { + expect(chatNewMessageCount(['m1'], null), 0); + expect(chatNewMessageCount(['m1'], 'replaced'), 0); + expect(chatNewMessageCount(const [], 'm1'), 0); + }); + + test('the label keeps the action and states the singular/plural count', () { + expect(chatJumpToLatestLabel(0), 'Jump to latest'); + expect(chatJumpToLatestLabel(1), 'Jump to latest · 1 new message'); + expect(chatJumpToLatestLabel(2), 'Jump to latest · 2 new messages'); + }); + }); + + group('restore', () { + test('no saved position lands on the newest end', () { + expect( + chatRestoreOffset(savedOffset: null, maxScrollExtent: 640), + 640, + ); + }); + + test('a saved position is kept within the current extent', () { + expect( + chatRestoreOffset(savedOffset: 120, maxScrollExtent: 640), + 120, + ); + expect(chatRestoreOffset(savedOffset: 0, maxScrollExtent: 640), 0); + expect( + chatRestoreOffset(savedOffset: 900, maxScrollExtent: 640), + 640, + ); + }); + }); + + group('store', () { + test('remembers one conversation without touching another', () { + final store = MemoryChatScrollStore(); + store.write('a', 120); + store.write('b', 30); + expect(store.read('a'), 120); + expect(store.read('b'), 30); + expect(store.read('c'), isNull); + + store.clear('a'); + expect(store.read('a'), isNull); + expect(store.entries, {'b': 30.0}); + }); + + test('ignores an unusable offset instead of inventing a position', () { + final store = MemoryChatScrollStore(); + store.write('a', double.nan); + store.write('a', double.infinity); + store.write('a', -5); + expect(store.read('a'), isNull); + }); + }); +} diff --git a/app/test/features/chat/conversation/chat_thread_scroll_test.dart b/app/test/features/chat/conversation/chat_thread_scroll_test.dart new file mode 100644 index 00000000..69b5a467 --- /dev/null +++ b/app/test/features/chat/conversation/chat_thread_scroll_test.dart @@ -0,0 +1,284 @@ +import 'package:flutter/cupertino.dart'; +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/chat/conversation/chat_scroll.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; + +import 'chat_thread_fixtures.dart'; + +Widget host(Widget child) => MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: Scaffold(body: child), +); + +Widget cupertinoHost(Widget child) => CupertinoApp( + theme: const CupertinoThemeData(brightness: Brightness.dark), + home: CupertinoPageScaffold(child: child), +); + +/// A history tall enough that the transcript overflows the test viewport. +JsonMap tallPage() => chatPage([ + for (var index = 0; index < 14; index++) + chatMessage( + 'm$index', + index.isEven ? 'user' : 'assistant', + parts: [ + { + 'type': 'text', + 'text': + 'Message $index. ' + '${List.filled(16, 'A sentence that wraps across the transcript width.').join(' ')}', + }, + ], + ), +]); + +ScrollController transcriptScroll(WidgetTester tester) => + tester + .widget(find.byKey(const Key('chat-thread-s'))) + .controller!; + +void main() { + testWidgets('a streaming transcript stays pinned to its newest end', ( + tester, + ) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => tallPage(); + + await tester.pumpWidget( + host(ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {})), + ); + await tester.pumpAndSettle(); + + final scroll = transcriptScroll(tester); + expect(scroll.position.maxScrollExtent, greaterThan(0)); + expect( + scroll.position.pixels, + closeTo(scroll.position.maxScrollExtent, 0.5), + ); + final heldExtent = scroll.position.maxScrollExtent; + + // A new message and further deltas grow the turn; every frame keeps the + // newest end visible without an animation the operator has to chase. + gateway.emitEvent(chatTextFrame('One streamed paragraph. ', messageId: 'live')); + await tester.pump(); + await tester.pump(); + gateway.emitEvent(chatTextFrame('And another delta. ', messageId: 'live')); + await tester.pump(); + await tester.pump(); + + expect(scroll.position.maxScrollExtent, greaterThan(heldExtent)); + expect( + scroll.position.pixels, + closeTo(scroll.position.maxScrollExtent, 0.5), + ); + expect(find.byKey(const Key('chat-jump-to-latest')), findsNothing); + }); + + for (final cupertino in [false, true]) { + testWidgets( + 'an upward scroll releases follow and the control counts arrivals ' + '(${cupertino ? 'cupertino' : 'material'})', + (tester) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => tallPage(); + + await tester.pumpWidget( + (cupertino ? cupertinoHost : host)( + ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + ), + ); + await tester.pumpAndSettle(); + + final scroll = transcriptScroll(tester); + await tester.drag( + find.byKey(const Key('chat-thread-s')), + const Offset(0, 360), + ); + await tester.pumpAndSettle(); + + final releasedAt = scroll.position.pixels; + expect( + releasedAt, + lessThan(scroll.position.maxScrollExtent - chatFollowThresholdPx), + ); + expect(find.byKey(const Key('chat-jump-to-latest')), findsOneWidget); + expect(find.text('Jump to latest'), findsOneWidget); + + gateway.emitEvent(chatTextFrame('A new answer. ', messageId: 'live-1')); + await tester.pump(); + await tester.pump(); + + // The operator's position is not moved by an arrival; only the + // control's count changes. + expect(scroll.position.pixels, closeTo(releasedAt, 0.5)); + expect( + find.text('Jump to latest · 1 new message'), + findsOneWidget, + ); + + gateway.emitEvent(chatTextFrame('A second answer. ', messageId: 'live-2')); + await tester.pump(); + await tester.pump(); + expect(scroll.position.pixels, closeTo(releasedAt, 0.5)); + expect( + find.text('Jump to latest · 2 new messages'), + findsOneWidget, + ); + + if (cupertino) { + // The affordance is a standard Cupertino control; no Material + // ancestor is introduced into the bare Cupertino host. + expect(find.byType(Material), findsNothing); + } + + await tester.tap(find.byKey(const Key('chat-jump-to-latest'))); + await tester.pumpAndSettle(); + + expect( + scroll.position.pixels, + closeTo(scroll.position.maxScrollExtent, 0.5), + ); + expect(find.byKey(const Key('chat-jump-to-latest')), findsNothing); + + // Returning to the end re-arms following for later frames. + gateway.emitEvent(chatTextFrame('Pinned again. ', messageId: 'live-3')); + await tester.pump(); + await tester.pump(); + expect( + scroll.position.pixels, + closeTo(scroll.position.maxScrollExtent, 0.5), + ); + expect(find.byKey(const Key('chat-jump-to-latest')), findsNothing); + }, + ); + } + + testWidgets('a reopened conversation restores the position it was left at', ( + tester, + ) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => tallPage(); + final positions = MemoryChatScrollStore(); + + await tester.pumpWidget( + host( + ChatThreadView( + gateway: gateway, + sessionId: 's', + scrollPositions: positions, + onBack: () {}, + ), + ), + ); + await tester.pumpAndSettle(); + + final scroll = transcriptScroll(tester); + await tester.drag( + find.byKey(const Key('chat-thread-s')), + const Offset(0, 360), + ); + await tester.pumpAndSettle(); + final saved = scroll.position.pixels; + expect(saved, greaterThan(0)); + expect(positions.read('s'), closeTo(saved, 0.5)); + + // Leaving the conversation disposes its view but not the destination's + // store. + await tester.pumpWidget(host(const SizedBox())); + await tester.pumpAndSettle(); + expect(positions.read('s'), closeTo(saved, 0.5)); + + await tester.pumpWidget( + host( + ChatThreadView( + gateway: gateway, + sessionId: 's', + scrollPositions: positions, + onBack: () {}, + ), + ), + ); + await tester.pumpAndSettle(); + + final reopened = transcriptScroll(tester); + expect(reopened.position.pixels, closeTo(saved, 1)); + expect( + reopened.position.pixels, + lessThan(reopened.position.maxScrollExtent - chatFollowThresholdPx), + ); + // The operator left a position, so the control offers the way back. + expect(find.byKey(const Key('chat-jump-to-latest')), findsOneWidget); + }); + + testWidgets('a conversation that fits its viewport offers no control', ( + tester, + ) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => chatPage([ + chatMessage( + 'm1', + 'user', + parts: [ + {'type': 'text', 'text': 'Short.'}, + ], + ), + ]); + + await tester.pumpWidget( + host(ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {})), + ); + await tester.pumpAndSettle(); + + final scroll = transcriptScroll(tester); + expect(scroll.position.maxScrollExtent, 0); + expect(find.byKey(const Key('chat-jump-to-latest')), findsNothing); + }); + + testWidgets('the control fits a 320px Cupertino viewport at 2x text', ( + tester, + ) async { + tester.view.physicalSize = const Size(640, 1200); + tester.view.devicePixelRatio = 2; + tester.platformDispatcher.textScaleFactorTestValue = 2; + tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue); + + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => tallPage(); + + await tester.pumpWidget( + cupertinoHost( + ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + ), + ); + await tester.pumpAndSettle(); + + await tester.drag( + find.byKey(const Key('chat-thread-s')), + const Offset(0, 360), + ); + await tester.pumpAndSettle(); + gateway.emitEvent(chatTextFrame('Arrival. ', messageId: 'live')); + await tester.pump(); + await tester.pump(); + + expect(tester.takeException(), isNull); + final control = find.byKey(const Key('chat-jump-to-latest')); + expect(control, findsOneWidget); + expect(find.text('Jump to latest · 1 new message'), findsOneWidget); + final rect = tester.getRect(control); + expect(rect.left, greaterThanOrEqualTo(0)); + expect(rect.right, lessThanOrEqualTo(320)); + expect(find.byType(Material), findsNothing); + }); +}