d02d5ea11d
Root causes found in release web captures (1280x800 and 560x900): - Follow mode undid small wheel/trackpad ticks at the end: each tick is its own scroll, re-judged as following within 32 px and jumped back. A user scroll toward older rows now releases the end however small; the jump control appears once streamed content moves the end beyond the threshold. - The end-of-scroll jump ran inside the position's activity switch, so a touch or scrollbar drag released near the end recursed without end (stack overflow during the gesture). The jump now runs after the notification. - Horizontally scrolling code blocks and tables claimed diagonal trackpad gestures whole. HorizontalScrollView gives mostly vertical gestures to the enclosing list; sideways and Shift + wheel still scroll the block. - The wheel over the floating chat bar, composer and jump control moved nothing. VerticalWheelForwarder scrolls the transcript from them unless something under the pointer claims the event. Adds widget tests per content kind and scroll mode, follow/touch/Load older tests, a capture-kit check (tool/capture/examples/chat-wheel-scroll.json) with eval/expect steps, wheel dx/repeat, --params and eval: targets, a transcript scroll probe and fixture options, and fixes the kit ignoring a script's size. Notes in notes/chat-wheel-scroll.md.
1914 lines
72 KiB
Dart
1914 lines
72 KiB
Dart
import 'dart:async';
|
|
|
|
import 'package:flutter/cupertino.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter/rendering.dart';
|
|
|
|
import '../../../core/api_gateway.dart';
|
|
import '../../../shell/shell_bar.dart';
|
|
import '../data/chat_attachment_images.dart';
|
|
import '../data/chat_repository.dart';
|
|
import '../domain/chat_activity_detail.dart';
|
|
import '../domain/chat_notice.dart';
|
|
import '../domain/chat_attachment_picker.dart';
|
|
import '../domain/chat_transcript.dart';
|
|
import '../ui/sessions/chat_adaptive.dart';
|
|
import '../ui/sessions/session_actions.dart';
|
|
import '../ui/transcript/chat_markdown_view.dart';
|
|
import '../ui/transcript/chat_message_view.dart';
|
|
import '../ui/transcript/chat_injected_rows.dart';
|
|
import 'chat_account_usage_section.dart';
|
|
import 'chat_background_tasks.dart';
|
|
import 'chat_command_actions.dart';
|
|
import 'chat_composer_bar.dart';
|
|
import 'chat_composer_controller.dart';
|
|
import 'chat_delivery_indicator.dart';
|
|
import 'chat_draft_store.dart';
|
|
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';
|
|
import '../../../ui/adaptive/floating_bar_layout.dart';
|
|
import '../../../ui/adaptive/segmented_bar_overlay.dart';
|
|
import '../../../ui/layout/app_sheet_header.dart';
|
|
import '../../../ui/layout/wheel_scroll_forwarding.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';
|
|
|
|
/// One read-only conversation: the controller's transcript in the order the
|
|
/// server reports it, rendered by the existing [ChatMessageView].
|
|
///
|
|
/// Assistant text goes through [ChatMarkdownView]'s builder, so stored and live
|
|
/// prose share the supported markdown subset. User text keeps the server's exact
|
|
/// characters, and reasoning/tool disclosures stay plain text.
|
|
///
|
|
/// History and live-subscription failures are separate notices: readable stored
|
|
/// history must never hide a refused live watch. The shell owns the navigation
|
|
/// bar, so this view adds only its own Back control and content.
|
|
class ChatThreadView extends StatefulWidget {
|
|
const ChatThreadView({
|
|
super.key,
|
|
required this.gateway,
|
|
required this.sessionId,
|
|
required this.onBack,
|
|
this.title = '',
|
|
this.session,
|
|
this.onModelChanged,
|
|
this.onModeChanged,
|
|
this.syncToken = 0,
|
|
this.drafts,
|
|
this.newOperationId,
|
|
this.attachmentPicker,
|
|
this.scrollPositions,
|
|
this.transcripts,
|
|
this.initialNotice,
|
|
this.onCreatedSession,
|
|
this.onSessionRenamed,
|
|
this.onSessionClosed,
|
|
});
|
|
|
|
final ApiGateway gateway;
|
|
final String sessionId;
|
|
final VoidCallback onBack;
|
|
|
|
/// The local line this conversation opens on: the destination hands over
|
|
/// the `/new` notice for a session it just created and opened.
|
|
final String? initialNotice;
|
|
|
|
/// `/new` created this row; the destination lists it, opens it with the
|
|
/// notice and refreshes the list. Without a destination the notice shows
|
|
/// here instead, since the session already exists on the server.
|
|
final ChatCreatedSessionCallback? onCreatedSession;
|
|
|
|
/// `/rename` was accepted with this title, so the header can follow it.
|
|
final ValueChanged<String>? onSessionRenamed;
|
|
|
|
/// `/close` was accepted: the conversation is finished here as on the web.
|
|
final VoidCallback? onSessionClosed;
|
|
|
|
/// The list row's title when this visit knows it; a deep link may not.
|
|
final String title;
|
|
|
|
/// The opened row's recorded facts when this visit knows them. The model
|
|
/// control reads its current model from this row; the destination supplies
|
|
/// it from the tapped row or from the list's loaded rows for a routed id.
|
|
final JsonMap? session;
|
|
|
|
/// The server's echo after an accepted model switch, so the destination can
|
|
/// keep the row it opened current for the next visit.
|
|
final ValueChanged<ChatModelSelection>? onModelChanged;
|
|
|
|
/// The accepted permission mode's id and name.
|
|
final void Function(String mode, String name)? onModeChanged;
|
|
|
|
/// Advances when the shared socket is replaced, keeping this selection.
|
|
final int syncToken;
|
|
|
|
/// Draft persistence for tests and previews; production uses the app store.
|
|
final ChatDraftStore? drafts;
|
|
|
|
/// Test/fixture seam for deterministic operation ids.
|
|
final String Function()? newOperationId;
|
|
|
|
/// Host picker seam for the thread's composer.
|
|
final ChatAttachmentPicker? attachmentPicker;
|
|
|
|
/// 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;
|
|
|
|
/// The destination's recently left transcripts. A conversation found here
|
|
/// opens on that transcript instead of a loading state while its newest page
|
|
/// is read; leaving writes back the transcript the last successful read
|
|
/// produced. Null opens every visit from the server alone.
|
|
final ChatTranscriptCache? transcripts;
|
|
|
|
@override
|
|
State<ChatThreadView> createState() => _ChatThreadViewState();
|
|
}
|
|
|
|
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);
|
|
|
|
/// Local notices the operator hid; cleared when the conversation or socket
|
|
/// changes so a reconnect never keeps a stale dismissal.
|
|
ChatNoticeDismissals _dismissals = ChatNoticeDismissals();
|
|
|
|
/// True while a reconnect repair is in flight: notices recorded before the
|
|
/// gap are stale, so none is drawn until the repair reports fresh state.
|
|
bool _reconnecting = false;
|
|
int _syncGeneration = 0;
|
|
|
|
/// The transcript held when the socket was replaced. A running state recorded
|
|
/// before the gap cannot be trusted again until a fresh read or frame
|
|
/// replaces that transcript.
|
|
List<JsonMap>? _preGapMessages;
|
|
|
|
/// The chain that repairs the newest socket gap. A second gap waits for an
|
|
/// in-flight repair instead of treating the controller's immediate return as
|
|
/// completion, which would expose stale notices mid-repair.
|
|
Future<void>? _repair;
|
|
|
|
/// The lines this conversation's slash commands produced, in order. They are
|
|
/// this conversation's own: a session switch starts over from the
|
|
/// destination's handoff, and a dismissal removes one.
|
|
final List<ChatNotice> _commandNotices = [];
|
|
int _commandNoticeSeq = 0;
|
|
|
|
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.
|
|
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;
|
|
|
|
/// 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;
|
|
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.
|
|
bool _userScrolling = false;
|
|
|
|
/// The way the operator's current scroll last moved. A wheel tick or a
|
|
/// drag toward older rows is a deliberate release of the end, however small.
|
|
ScrollDirection _userDirection = ScrollDirection.idle;
|
|
|
|
/// 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() {
|
|
final controller = ChatThreadController(
|
|
widget.gateway,
|
|
widget.sessionId,
|
|
cached: widget.transcripts?.read(widget.sessionId),
|
|
);
|
|
// The listener names this controller: load() can notify before _attach
|
|
// returns, while reading _controller would build another one, and so on.
|
|
controller.transcriptChanges.addListener(
|
|
() => _reconcileUnsent(controller),
|
|
);
|
|
// Delivery states follow the server's queue reports. Read the composer
|
|
// when the report arrives: it is not built yet while this one is.
|
|
controller.onQueue = (queue) {
|
|
if (mounted && identical(controller, _controller)) {
|
|
_composer.applyServerQueue(queue);
|
|
}
|
|
};
|
|
unawaited(controller.load());
|
|
return controller;
|
|
}
|
|
|
|
/// Settles stored unsent messages once the transcript is an authoritative
|
|
/// read: a message the server recorded was sent after all.
|
|
void _reconcileUnsent(ChatThreadController controller) {
|
|
if (!mounted ||
|
|
!controller.loaded ||
|
|
controller.loading ||
|
|
controller.error != null ||
|
|
controller.showingCached) {
|
|
return;
|
|
}
|
|
_composer.reconcile(controller.messages);
|
|
}
|
|
|
|
/// `/close` finished this conversation; its transcript is not kept.
|
|
bool _closed = false;
|
|
|
|
/// A cached transcript is from before this visit's subscription, like one
|
|
/// held across a socket gap: no running turn or compaction is drawn from it
|
|
/// until a read or frame replaces it.
|
|
void _adoptCachedTranscript() {
|
|
_preGapMessages = _controller.showingCached ? _controller.messages : null;
|
|
}
|
|
|
|
/// Keeps the transcript being left for the next visit. Only one backed by a
|
|
/// successful read on the current connection is written; otherwise the
|
|
/// earlier entry stays, and every visit re-reads anyway.
|
|
void _saveTranscript(ChatTranscriptCache? cache, String sessionId) {
|
|
if (cache == null) return;
|
|
if (_closed) {
|
|
cache.remove(sessionId);
|
|
return;
|
|
}
|
|
final snapshot = _controller.snapshot;
|
|
if (snapshot != null) cache.write(sessionId, snapshot);
|
|
}
|
|
|
|
void _sessionClosed() {
|
|
_closed = true;
|
|
widget.transcripts?.remove(widget.sessionId);
|
|
widget.onSessionClosed?.call();
|
|
}
|
|
|
|
ChatComposerController _attachComposer() {
|
|
final composer = ChatComposerController(
|
|
widget.gateway,
|
|
widget.sessionId,
|
|
drafts: widget.drafts,
|
|
newOperationId: widget.newOperationId,
|
|
onOptimistic: _onOptimistic,
|
|
onRejected: _onRejected,
|
|
onAccepted: (send, queued) =>
|
|
_controller.promptAccepted(send.operationId, queued: queued),
|
|
);
|
|
// A message a previous visit sent but never saw accepted comes back as
|
|
// "Not sent" unless the history read shows the server has it.
|
|
unawaited(
|
|
composer.loadUnsent().then((_) {
|
|
if (mounted && identical(composer, _composer)) {
|
|
_reconcileUnsent(_controller);
|
|
}
|
|
}),
|
|
);
|
|
return composer;
|
|
}
|
|
|
|
/// Draws a sent (or retried) message where it was sent: a retry moves the
|
|
/// message to the end, since that is when it is sent.
|
|
void _onOptimistic(ChatComposerSend send) {
|
|
if (!mounted) return;
|
|
_controller.removeLocal(send.operationId);
|
|
_controller.insertLocal(send.toMessage());
|
|
}
|
|
|
|
/// A refused message leaves the transcript; it is drawn after it as "Not
|
|
/// sent" from the composer's deliveries instead.
|
|
void _onRejected(ChatComposerSend send, String error) {
|
|
if (!mounted) return;
|
|
_controller.removeLocal(send.operationId);
|
|
}
|
|
|
|
/// Reports the harness's recorded usage. The standard sheet is dismissed the
|
|
/// platform's way (drag/barrier/Back, or a popup tap) and closes explicitly.
|
|
Future<void> _openInfo() async {
|
|
final cupertino =
|
|
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
|
if (cupertino) {
|
|
await showCupertinoModalPopup<void>(
|
|
context: context,
|
|
builder: (sheetContext) => Align(
|
|
alignment: Alignment.bottomCenter,
|
|
child: SafeArea(
|
|
child: CupertinoPopupSurface(
|
|
child: _ChatInfoSheet(controller: _controller),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
await showModalBottomSheet<void>(
|
|
context: context,
|
|
showDragHandle: true,
|
|
isScrollControlled: true,
|
|
useSafeArea: true,
|
|
builder: (sheetContext) => _ChatInfoSheet(controller: _controller),
|
|
);
|
|
}
|
|
|
|
/// The transcript in recorded order; a sent turn is part of it from the
|
|
/// moment it is sent (ChatThreadController.insertLocal).
|
|
List<JsonMap> _visibleMessages() => _controller.messages;
|
|
|
|
void _seedCommandNotice() {
|
|
final notice = widget.initialNotice;
|
|
if (notice == null || notice.isEmpty) return;
|
|
_commandNotices.add(
|
|
chatCommandNotice(notice, sequence: ++_commandNoticeSeq),
|
|
);
|
|
}
|
|
|
|
void _showCommandNotice(String text, {bool failed = false}) {
|
|
if (!mounted) return;
|
|
setState(() {
|
|
_commandNotices.add(
|
|
chatCommandNotice(text, sequence: ++_commandNoticeSeq, failed: failed),
|
|
);
|
|
});
|
|
}
|
|
|
|
/// The runner for this session's `/new`, `/close` and `/rename`, rebuilt per
|
|
/// build so an adopted row's directory and title are the current ones.
|
|
ChatCommandActions _commandActions() {
|
|
final session =
|
|
widget.session ?? {'id': widget.sessionId, 'title': widget.title};
|
|
final onCreated = widget.onCreatedSession;
|
|
return ChatCommandActions(
|
|
repository: ChatRepository(widget.gateway),
|
|
sessionId: widget.sessionId,
|
|
directory: '${session['directory'] ?? ''}'.trim(),
|
|
showNotice: _showCommandNotice,
|
|
confirmClose: () => confirmCloseChat(context, session),
|
|
openCreatedSession:
|
|
onCreated ?? (created, notice) => _showCommandNotice(notice),
|
|
onRenamed: widget.onSessionRenamed,
|
|
onClosed: _sessionClosed,
|
|
newOperationId: widget.newOperationId,
|
|
);
|
|
}
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
_savedPosition = widget.scrollPositions?.read(widget.sessionId);
|
|
_adoptCachedTranscript();
|
|
_seedCommandNotice();
|
|
}
|
|
|
|
@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);
|
|
// A transcript from another server is not this one's to keep.
|
|
if (oldWidget.gateway == widget.gateway) {
|
|
_saveTranscript(oldWidget.transcripts, oldWidget.sessionId);
|
|
} else {
|
|
_images = ChatAttachmentImages(widget.gateway);
|
|
}
|
|
_controller.dispose();
|
|
_composer.dispose();
|
|
_closed = false;
|
|
_controller = _attach();
|
|
_composer = _attachComposer();
|
|
_rowKeys = ChatRowKeys();
|
|
_rowWidgets.clear();
|
|
_chrome.clear();
|
|
_dismissals = ChatNoticeDismissals();
|
|
_reconnecting = false;
|
|
_adoptCachedTranscript();
|
|
_syncGeneration++;
|
|
_commandNotices.clear();
|
|
_seedCommandNotice();
|
|
_savedPosition = widget.scrollPositions?.read(widget.sessionId);
|
|
_anchor = null;
|
|
_anchorChosen = false;
|
|
_placed = false;
|
|
_following = true;
|
|
_distanceFromBottom = null;
|
|
_newestAtRelease = null;
|
|
_userScrolling = false;
|
|
_userDirection = ScrollDirection.idle;
|
|
_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,
|
|
// so no earlier dismissal survives and nothing recorded before the gap is
|
|
// painted while the repair runs.
|
|
_dismissals.clear();
|
|
_preGapMessages = _controller.messages;
|
|
_reconnecting = true;
|
|
final generation = ++_syncGeneration;
|
|
final previous = _repair;
|
|
final repair = (previous ?? Future<void>.value())
|
|
.then((_) async {
|
|
// A newer gap owns the repair; its own step in this chain runs next.
|
|
if (!mounted || generation != _syncGeneration) return;
|
|
await _controller.resync();
|
|
})
|
|
.whenComplete(() {
|
|
if (!mounted || generation != _syncGeneration) return;
|
|
setState(() {
|
|
_reconnecting = false;
|
|
// A successful repair replaced the transcript with fresh state.
|
|
if (!identical(_controller.messages, _preGapMessages)) {
|
|
_preGapMessages = null;
|
|
}
|
|
});
|
|
});
|
|
_repair = repair;
|
|
unawaited(repair);
|
|
}
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_persistPosition();
|
|
_saveTranscript(widget.transcripts, widget.sessionId);
|
|
_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<String> _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;
|
|
}
|
|
final offset = _scroll.hasClients ? _scroll.position.pixels : _lastOffset;
|
|
store.write(id, (offset: offset, anchor: _anchor));
|
|
}
|
|
|
|
/// 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, {bool towardOlder = false}) {
|
|
final ids = _messageIds();
|
|
final distance = _distanceFor(metrics, ids.length);
|
|
final following = chatFollowsAfterScroll(
|
|
distance,
|
|
itemCount: ids.length,
|
|
towardOlder: towardOlder,
|
|
);
|
|
_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;
|
|
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;
|
|
_savedPosition = null;
|
|
if (saved != null) {
|
|
_restoreOffset = saved.offset;
|
|
_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,
|
|
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,
|
|
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;
|
|
final startBefore = _restoreMeasuredStart;
|
|
_applyRestore();
|
|
// 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;
|
|
_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) _trackDistance(notification.metrics);
|
|
if (!_following || _userScrolling || !_scroll.hasClients) return false;
|
|
if (_scroll.position.pixels < _scroll.position.maxScrollExtent) {
|
|
_scheduleFollow();
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/// Keeps the measured distance current while the operator reads above the
|
|
/// end and content grows below them, so the jump control appears once the
|
|
/// end moves beyond the threshold (a release can start within it).
|
|
void _trackDistance(ScrollMetrics metrics) {
|
|
final ids = _messageIds();
|
|
final distance = _distanceFor(metrics, ids.length);
|
|
bool shows(double? distance) => chatShowsJumpToLatest(
|
|
following: false,
|
|
distanceFromBottom: distance,
|
|
itemCount: ids.length,
|
|
);
|
|
final changed = shows(distance) != shows(_distanceFromBottom);
|
|
_distanceFromBottom = distance;
|
|
if (changed) setState(() {});
|
|
}
|
|
|
|
/// 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) {
|
|
_userDirection = notification.direction;
|
|
_abandonRestore();
|
|
}
|
|
} else if (notification is ScrollStartNotification) {
|
|
if (notification.dragDetails != null) {
|
|
_userScrolling = true;
|
|
_abandonRestore();
|
|
}
|
|
} else if (notification is ScrollUpdateNotification) {
|
|
if (_userScrolling) {
|
|
_updateFollow(notification.metrics, towardOlder: _towardOlder);
|
|
}
|
|
} else if (notification is ScrollEndNotification) {
|
|
final user = _userScrolling;
|
|
final towardOlder = _towardOlder;
|
|
_userScrolling = false;
|
|
_userDirection = ScrollDirection.idle;
|
|
if (user) {
|
|
_updateFollow(notification.metrics, towardOlder: towardOlder);
|
|
_persistPosition();
|
|
// Releasing a scroll toward the end within the threshold returns to
|
|
// the end. A scroll toward older rows has already released it: every
|
|
// wheel or trackpad tick ends its own scroll, so snapping back here
|
|
// would undo each small tick and pin the view to the end.
|
|
//
|
|
// The jump waits for this notification to finish: a drag's or
|
|
// fling's end is reported while the position is still switching
|
|
// activities, and jumping inside it re-entered this handler without
|
|
// end (a stack overflow that left the gesture broken).
|
|
if (_following) {
|
|
scheduleMicrotask(() {
|
|
if (mounted && _following && !_userScrolling) _jumpToBottom();
|
|
});
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
bool get _towardOlder => _userDirection == ScrollDirection.forward;
|
|
|
|
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;
|
|
}
|
|
|
|
/// 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([
|
|
_controller.transcriptChanges,
|
|
_composer.deliveries,
|
|
]),
|
|
builder: (context, _) {
|
|
final cupertino =
|
|
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
|
final messages = _visibleMessages();
|
|
final cards = chatCardRows(
|
|
permissions: _controller.permissionFrames,
|
|
forms: _controller.questionForms,
|
|
answerFor: _controller.permissionAnswerFor,
|
|
permissionErrorFor: _controller.permissionErrorFor,
|
|
formErrorFor: _controller.questionErrorFor,
|
|
);
|
|
// Answered approvals fold into their turn's chips, like tool calls.
|
|
final allRows = groupSettledPermissions(
|
|
transcriptRows(
|
|
messages,
|
|
trailing: cards,
|
|
running:
|
|
_controller.running &&
|
|
!_reconnecting &&
|
|
!_staleTranscript &&
|
|
!cards.any(chatCardAwaitingOperator),
|
|
awaitingResponse:
|
|
_controller.awaitingResponse &&
|
|
!_reconnecting &&
|
|
!_staleTranscript &&
|
|
!cards.any(chatCardAwaitingOperator),
|
|
liveMessageId: _controller.liveAssistantMessageId,
|
|
),
|
|
);
|
|
// A transcript held from before a socket gap may still say a compaction is
|
|
// running even when the repair's read is refused. That running state is
|
|
// stale, so no compaction notice is derived from it until a fresh read or
|
|
// frame replaces the transcript. Fresh failure notices still report.
|
|
//
|
|
// Notices report recorded conditions only: a refused read/watch and a
|
|
// running compaction. A dismissal keeps one hidden until its condition
|
|
// changes. A running compaction's own activity line is that notice, so it
|
|
// is not drawn twice; hiding it when dismissed is the whole dismissal.
|
|
final allNotices = _reconnecting
|
|
? const <ChatNotice>[]
|
|
: chatNotices(
|
|
historyError: _controller.error,
|
|
liveError: _controller.subscriptionError,
|
|
messages: _staleTranscript ? const [] : _controller.messages,
|
|
);
|
|
final notices = _dismissals.visible(allNotices);
|
|
final compactionNotice = _noticeOf(notices, ChatNoticeKind.compaction);
|
|
final rows = [
|
|
for (final row in allRows)
|
|
if (!_hiddenRunningCompaction(row)) row,
|
|
];
|
|
// Older pages prepend messages and a live frame can append one, so a
|
|
// folded assistant turn's first message id is not a stable identity.
|
|
// ChatRowKeys carries a turn's key forward while it still holds any of
|
|
// 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,
|
|
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();
|
|
// Under the app shell the conversation takes over the app's bar (title,
|
|
// Back, model, information) instead of drawing a second bar below it.
|
|
final inShellBar = ShellBar.available(context);
|
|
// 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.
|
|
// 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,
|
|
commands: _commandActions(),
|
|
picker: widget.attachmentPicker,
|
|
images: _images,
|
|
placeholder: chatComposerPlaceholderFor(
|
|
'${widget.session?['directory'] ?? ''}',
|
|
),
|
|
backgroundTasks: ChatBackgroundTasks(
|
|
key: ValueKey('chat-background-tasks-${widget.sessionId}'),
|
|
gateway: widget.gateway,
|
|
sessionId: widget.sessionId,
|
|
syncToken: widget.syncToken,
|
|
),
|
|
),
|
|
);
|
|
final page = FloatingBarOverlay(
|
|
bar: composerBar,
|
|
child: SegmentedBarOverlay(
|
|
bar: _header(context, inShellBar),
|
|
child: NotificationListener<ScrollMetricsNotification>(
|
|
onNotification: _onScrollMetrics,
|
|
child: NotificationListener<ScrollNotification>(
|
|
onNotification: _onScrollNotification,
|
|
child: LayoutBuilder(
|
|
builder: (context, constraints) {
|
|
// Rows keep to the centred reading column on a wide
|
|
// 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
|
|
// and the last one ends above the floating composer.
|
|
// 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,
|
|
side,
|
|
media.bottom + 8,
|
|
),
|
|
children: [
|
|
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 (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 &&
|
|
_commandNotices.isEmpty &&
|
|
_controller.error == null)
|
|
const Padding(
|
|
key: Key('chat-thread-empty'),
|
|
padding: EdgeInsets.all(16),
|
|
child: Text('No messages in this chat yet.'),
|
|
),
|
|
...transcript,
|
|
// Messages the server holds queued (one sent before
|
|
// a reload, or from another device) follow the
|
|
// transcript: none has reached the harness yet.
|
|
for (final prompt
|
|
in _controller.queuedOutsideTranscript)
|
|
Padding(
|
|
key: ValueKey<String>(
|
|
'chat-queued-${prompt['operation_id']}',
|
|
),
|
|
padding: const EdgeInsets.symmetric(
|
|
horizontal: 16,
|
|
),
|
|
child: _queuedRow(prompt, cupertino),
|
|
),
|
|
// Messages the server has not accepted follow the
|
|
// transcript until they are retried or edited.
|
|
for (final send in _composer.deliveries.unsent)
|
|
Padding(
|
|
key: ValueKey<String>(
|
|
'chat-unsent-${send.operationId}',
|
|
),
|
|
padding: const EdgeInsets.symmetric(
|
|
horizontal: 16,
|
|
),
|
|
child: _unsentRow(send, cupertino),
|
|
),
|
|
// The conversation's own command lines sit after the
|
|
// turns, as on the web; they are never bubbles.
|
|
for (final notice in _commandNotices)
|
|
_ChatNoticeLine(
|
|
key: ValueKey<String>(
|
|
'chat-command-notice-${notice.condition}',
|
|
),
|
|
notice: notice,
|
|
onDismiss: _dismiss,
|
|
),
|
|
],
|
|
),
|
|
if (showJump)
|
|
PositionedDirectional(
|
|
end: side + 16,
|
|
bottom: media.bottom + 16,
|
|
child: _ChatJumpToLatest(
|
|
key: const Key('chat-jump-to-latest'),
|
|
label: chatJumpToLatestLabel(newMessages),
|
|
cupertino: cupertino,
|
|
onPressed: _followLatest,
|
|
),
|
|
),
|
|
],
|
|
);
|
|
},
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
// The bar, the composer and the jump control float over the transcript;
|
|
// the wheel over them scrolls it, as a page scrolls under fixed bars.
|
|
final column = VerticalWheelForwarder(controller: _scroll, child: page);
|
|
if (!inShellBar) return column;
|
|
// The conversation draws its own floating bar; the page shows none.
|
|
final title = widget.title.trim();
|
|
return ShellBar(
|
|
barless: true,
|
|
title: title.isEmpty ? null : title,
|
|
child: column,
|
|
);
|
|
},
|
|
);
|
|
|
|
/// The floating bar: Back where this page can go back (a pushed phone page,
|
|
/// or a standalone screen), the title pill that opens the information, and
|
|
/// 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 directory = '${session?['directory'] ?? ''}'.trim();
|
|
final folder = directory
|
|
.split(RegExp(r'[/\\]'))
|
|
.lastWhere((part) => part.isNotEmpty, orElse: () => '');
|
|
return ChatThreadHeader(
|
|
key: const Key('chat-thread-header'),
|
|
title: widget.title.trim(),
|
|
folder: folder,
|
|
onInfo: _openInfo,
|
|
showBack: canGoBack,
|
|
// A pushed page keeps the platform's stock Back (pop this route); a
|
|
// standalone conversation calls its owner.
|
|
onBack: inShellBar ? null : widget.onBack,
|
|
// Natural width while the bar has room; past the title's share both
|
|
// controls ellipsise. A session without a mode draws no mode control,
|
|
// so no empty pill is ever drawn.
|
|
controls: [
|
|
if (hasModel || hasMode)
|
|
LayoutBuilder(
|
|
builder: (context, constraints) => Row(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
if (hasModel)
|
|
Flexible(
|
|
child: ChatModelControl(
|
|
key: ValueKey<String>('chat-model-${widget.sessionId}'),
|
|
gateway: widget.gateway,
|
|
sessionId: widget.sessionId,
|
|
session: session,
|
|
onChanged: widget.onModelChanged,
|
|
answeredBy: answeredBy,
|
|
),
|
|
),
|
|
if (hasMode)
|
|
// The mode keeps its whole name until it would take more
|
|
// than half the pill; the model takes the rest.
|
|
ConstrainedBox(
|
|
constraints: BoxConstraints(
|
|
maxWidth: hasModel
|
|
? constraints.maxWidth / 2
|
|
: constraints.maxWidth,
|
|
),
|
|
child: _modeControl(),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
],
|
|
);
|
|
}
|
|
|
|
/// The session's permission mode, keyed per session so another chat
|
|
/// re-reads its own modes.
|
|
Widget _modeControl() => ChatModeControl(
|
|
key: ValueKey<String>('chat-mode-${widget.sessionId}'),
|
|
gateway: widget.gateway,
|
|
sessionId: widget.sessionId,
|
|
mode: '${widget.session?['mode'] ?? ''}'.trim(),
|
|
modeName: '${widget.session?['mode_name'] ?? ''}'.trim(),
|
|
onChanged: widget.onModeChanged,
|
|
);
|
|
|
|
ChatNotice? _noticeOf(List<ChatNotice> notices, ChatNoticeKind kind) {
|
|
for (final notice in notices) {
|
|
if (notice.kind == kind) return notice;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// Whether a running compaction's activity line must stay off screen.
|
|
///
|
|
/// That line is the compaction notice, so it follows the same conditions: it
|
|
/// is hidden while the repair runs, while the held transcript is still the
|
|
/// pre-gap one, and when the operator dismissed this exact compaction. A
|
|
/// different running compaction in the transcript keeps its own line.
|
|
bool _hiddenRunningCompaction(JsonMap row) {
|
|
final condition = chatNoticeActivityCondition(row);
|
|
if (condition == null) return false;
|
|
return _reconnecting ||
|
|
_staleTranscript ||
|
|
_dismissals.isDismissed(condition);
|
|
}
|
|
|
|
/// Whether the held transcript is still the one recorded before the gap.
|
|
bool get _staleTranscript =>
|
|
_preGapMessages != null &&
|
|
identical(_controller.messages, _preGapMessages);
|
|
|
|
void _dismiss(ChatNotice notice) {
|
|
setState(() {
|
|
if (notice.kind == ChatNoticeKind.command) {
|
|
// A command line is this conversation's own record, not a recorded
|
|
// condition that could recur: dismissing it removes it.
|
|
_commandNotices.remove(notice);
|
|
} else {
|
|
_dismissals.dismiss(notice);
|
|
}
|
|
});
|
|
}
|
|
|
|
Widget _transcriptRow(
|
|
JsonMap row,
|
|
String key, {
|
|
VoidCallback? onDismissCompaction,
|
|
}) {
|
|
final kind = '${row['kind'] ?? ''}';
|
|
if (kind == 'activity') {
|
|
return _ChatActivityLine(row: row, onDismiss: onDismissCompaction);
|
|
}
|
|
if (kind == 'agent_report') {
|
|
return ChatAgentReportCard(row: row, textBuilder: chatMarkdownText);
|
|
}
|
|
if (kind == 'system_notice') return ChatSystemNoticeLine(row: row);
|
|
if (kind == 'permission' || kind == 'question') {
|
|
return ChatTranscriptCard(
|
|
row: row,
|
|
onPermissionDecision: _controller.replyPermission,
|
|
onQuestionAnswer: _controller.answerQuestion,
|
|
);
|
|
}
|
|
final permissions = row['permissions'];
|
|
final chips = [
|
|
if (permissions is List<ChatPermissionCardData> && permissions.isNotEmpty)
|
|
ChatPermissionsChip(permissions: permissions),
|
|
];
|
|
if (kind == 'permissions') {
|
|
return Align(
|
|
alignment: AlignmentDirectional.centerStart,
|
|
child: chips.firstOrNull ?? const SizedBox.shrink(),
|
|
);
|
|
}
|
|
final message = kind == 'user' && row['message'] is Map
|
|
? Map<String, dynamic>.from(row['message'] as Map)
|
|
: null;
|
|
final delivery = message != null
|
|
? _composer.deliveries.stateFor(message)
|
|
: null;
|
|
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,
|
|
),
|
|
);
|
|
}
|
|
|
|
/// Remove for a message the server still holds queued, or null.
|
|
VoidCallback? _removeAction(String operationId) {
|
|
if (operationId.isEmpty || !_controller.isQueued(operationId)) return null;
|
|
final controller = _controller;
|
|
return () =>
|
|
unawaited(_composer.unqueue(() => controller.unqueue(operationId)));
|
|
}
|
|
|
|
/// One prompt the server holds queued that the transcript does not show,
|
|
/// as the sender's bubble with "Queued" and its Remove.
|
|
Widget _queuedRow(JsonMap prompt, bool cupertino) {
|
|
final message = ChatServerQueue.message(prompt);
|
|
return ChatMessageView(
|
|
row: {'kind': 'user', 'key': message['id'], 'message': message},
|
|
textBuilder: chatMarkdownText,
|
|
images: _images,
|
|
footer: [
|
|
ChatDeliveryIndicator(
|
|
state: ChatDelivery.queued,
|
|
cupertino: cupertino,
|
|
onRemove: _removeAction('${prompt['operation_id'] ?? ''}'),
|
|
),
|
|
],
|
|
);
|
|
}
|
|
|
|
/// One message the server has not accepted, as the operator's bubble with
|
|
/// "Not sent" and its Retry and Edit.
|
|
Widget _unsentRow(ChatComposerSend send, bool cupertino) {
|
|
final composer = _composer;
|
|
return ChatMessageView(
|
|
row: {
|
|
'kind': 'user',
|
|
'key': send.optimisticId,
|
|
'message': send.toMessage(),
|
|
},
|
|
textBuilder: chatMarkdownText,
|
|
images: _images,
|
|
footer: [
|
|
ChatDeliveryIndicator(
|
|
state: ChatDelivery.failed,
|
|
cupertino: cupertino,
|
|
onRetry: send.canRetry && !composer.sending
|
|
? () => unawaited(composer.retry(send.operationId))
|
|
: null,
|
|
// Attachment bytes cannot go back into the composer's chips, so an
|
|
// intent with files is discarded rather than silently trimmed.
|
|
// Its text already back in the composer needs no Edit.
|
|
editLabel: send.attachments.isEmpty ? 'Edit' : 'Discard',
|
|
onEdit: composer.isInComposer(send.operationId)
|
|
? null
|
|
: send.attachments.isEmpty
|
|
? () => unawaited(composer.edit(send.operationId))
|
|
: () => composer.discard(send.operationId),
|
|
),
|
|
],
|
|
);
|
|
}
|
|
}
|
|
|
|
/// The native dismiss control shared by a local notice and a running
|
|
/// compaction's activity line. Material uses a tooltip; Cupertino carries the
|
|
/// same accessible name on the wrapping node, since its button has none.
|
|
Widget _noticeDismissControl({
|
|
required bool cupertino,
|
|
required String label,
|
|
required Key key,
|
|
required VoidCallback onPressed,
|
|
}) {
|
|
final icon = Icon(cupertino ? CupertinoIcons.xmark_circle_fill : Icons.close);
|
|
if (!cupertino) {
|
|
return IconButton(
|
|
key: key,
|
|
tooltip: label,
|
|
onPressed: onPressed,
|
|
icon: icon,
|
|
);
|
|
}
|
|
return Semantics(
|
|
container: true,
|
|
button: true,
|
|
label: label,
|
|
onTap: onPressed,
|
|
child: ExcludeSemantics(
|
|
child: CupertinoButton(
|
|
key: key,
|
|
padding: EdgeInsets.zero,
|
|
onPressed: onPressed,
|
|
child: icon,
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
/// One local notice beside the conversation: a recorded failure or a slash
|
|
/// command's outcome.
|
|
///
|
|
/// It is never a message bubble and never sent to the agent. The line carries
|
|
/// the kind's own words plus the recorded reason, keeps its native Retry and
|
|
/// adds a native dismiss control. Colour only repeats the failed state, so the
|
|
/// words remain readable without it. A running compaction is a recorded activity
|
|
/// line and is dismissed there instead.
|
|
class _ChatNoticeLine extends StatelessWidget {
|
|
const _ChatNoticeLine({
|
|
super.key,
|
|
required this.notice,
|
|
required this.onDismiss,
|
|
this.onRetry,
|
|
});
|
|
|
|
final ChatNotice notice;
|
|
final ValueChanged<ChatNotice> onDismiss;
|
|
final VoidCallback? onRetry;
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final cupertino =
|
|
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
|
final theme = Theme.of(context);
|
|
final failed = notice.failed;
|
|
final color = failed
|
|
? (cupertino
|
|
? CupertinoColors.systemRed.resolveFrom(context)
|
|
: theme.colorScheme.error)
|
|
: (cupertino
|
|
? CupertinoColors.secondaryLabel.resolveFrom(context)
|
|
: theme.colorScheme.onSurfaceVariant);
|
|
final style =
|
|
(cupertino
|
|
? CupertinoTheme.of(context).textTheme.textStyle
|
|
: theme.textTheme.bodyMedium)
|
|
?.copyWith(color: color);
|
|
final icon = failed
|
|
? (cupertino
|
|
? CupertinoIcons.exclamationmark_circle
|
|
: Icons.error_outline)
|
|
: (cupertino ? CupertinoIcons.info_circle : Icons.info_outline);
|
|
return Padding(
|
|
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 8, 4),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
Row(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Padding(
|
|
padding: const EdgeInsetsDirectional.only(top: 8),
|
|
child: Icon(icon, color: color),
|
|
),
|
|
const SizedBox(width: 8),
|
|
Expanded(
|
|
child: Padding(
|
|
padding: const EdgeInsets.symmetric(vertical: 8),
|
|
child: Semantics(
|
|
liveRegion: true,
|
|
child: Text(notice.text, style: style),
|
|
),
|
|
),
|
|
),
|
|
_dismissControl(cupertino),
|
|
],
|
|
),
|
|
if (onRetry != null)
|
|
Align(
|
|
alignment: AlignmentDirectional.centerStart,
|
|
child: cupertino
|
|
? CupertinoButton(
|
|
padding: EdgeInsets.zero,
|
|
onPressed: onRetry,
|
|
child: const Text('Retry'),
|
|
)
|
|
: TextButton(onPressed: onRetry, child: const Text('Retry')),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _dismissControl(bool cupertino) {
|
|
return _noticeDismissControl(
|
|
cupertino: cupertino,
|
|
label: chatNoticeDismissLabel(notice.kind),
|
|
key: ValueKey<String>('chat-notice-dismiss-${notice.kind.name}'),
|
|
onPressed: () => onDismiss(notice),
|
|
);
|
|
}
|
|
}
|
|
|
|
/// One reported usage metric: its web label, whether the harness reported it,
|
|
/// and the displayed value. Unavailable is a word, never a zero.
|
|
typedef _ChatInfoMetric = ({
|
|
String key,
|
|
String label,
|
|
bool available,
|
|
String value,
|
|
});
|
|
|
|
const _chatInfoUnavailable = 'Unavailable';
|
|
|
|
/// The four chat usage facts in the web order and wording.
|
|
///
|
|
/// Values come only from [ChatThreadController.usage]; a missing count, amount
|
|
/// or window is "Unavailable". A reported zero stays a reported zero, and the
|
|
/// context row keeps the web's partial forms when only one side was reported.
|
|
List<_ChatInfoMetric> _chatInfoMetrics(JsonMap? usage) {
|
|
final scope = '${usage?['scope'] ?? ''}';
|
|
final basis = '${usage?['rate_basis'] ?? ''}';
|
|
final rate = _chatInfoAmount(usage?['output_tokens_per_second']);
|
|
final total = _chatInfoCount(usage?['total_tokens']);
|
|
final used = _chatInfoCount(usage?['context_tokens']);
|
|
final reportedWindow = _chatInfoCount(usage?['context_window']);
|
|
// The web treats a zero context window as no reported limit.
|
|
final limit = reportedWindow != null && reportedWindow > 0
|
|
? reportedWindow
|
|
: null;
|
|
final cost = _chatInfoAmount(usage?['cost_usd']);
|
|
final context = used != null && limit != null
|
|
? '${_chatInfoInteger(used)} / ${_chatInfoInteger(limit)}'
|
|
: limit != null
|
|
? '${_chatInfoInteger(limit)} limit'
|
|
: used != null
|
|
? '${_chatInfoInteger(used)} used'
|
|
: _chatInfoUnavailable;
|
|
return [
|
|
(
|
|
key: 'rate',
|
|
label: basis == 'turn' ? 'Avg output rate' : 'Output rate',
|
|
available: rate != null,
|
|
value: rate == null ? _chatInfoUnavailable : _chatInfoRate(rate),
|
|
),
|
|
(
|
|
key: 'tokens',
|
|
label: scope == 'turn' ? 'Turn tokens' : 'Total tokens',
|
|
available: total != null,
|
|
value: total == null ? _chatInfoUnavailable : _chatInfoInteger(total),
|
|
),
|
|
(
|
|
key: 'context',
|
|
label: 'Context',
|
|
available: used != null || limit != null,
|
|
value: context,
|
|
),
|
|
(
|
|
key: 'cost',
|
|
label: 'Reported cost',
|
|
available: cost != null,
|
|
value: cost == null ? _chatInfoUnavailable : _chatInfoDollars(cost),
|
|
),
|
|
];
|
|
}
|
|
|
|
int? _chatInfoCount(Object? value) => value is int && value >= 0 ? value : null;
|
|
|
|
num? _chatInfoAmount(Object? value) =>
|
|
value is num && value.isFinite && value >= 0 ? value : null;
|
|
|
|
String _chatInfoInteger(int value) {
|
|
final digits = value.toString();
|
|
final grouped = StringBuffer();
|
|
for (var index = 0; index < digits.length; index++) {
|
|
if (index > 0 && (digits.length - index) % 3 == 0) grouped.write(',');
|
|
grouped.write(digits[index]);
|
|
}
|
|
return grouped.toString();
|
|
}
|
|
|
|
String _chatInfoRate(num value) {
|
|
final atMostOneDecimal = value.toStringAsFixed(1);
|
|
final number = atMostOneDecimal.endsWith('.0')
|
|
? atMostOneDecimal.substring(0, atMostOneDecimal.length - 2)
|
|
: atMostOneDecimal;
|
|
return value > 0 && value < 0.1 ? '<0.1 tok/s' : '$number tok/s';
|
|
}
|
|
|
|
String _chatInfoDollars(num value) {
|
|
if (value > 0 && value < 0.000001) return '<\$0.000001';
|
|
final fixed = value.toStringAsFixed(6);
|
|
final point = fixed.indexOf('.');
|
|
var decimals = fixed.substring(point + 1);
|
|
while (decimals.length > 4 && decimals.endsWith('0')) {
|
|
decimals = decimals.substring(0, decimals.length - 1);
|
|
}
|
|
final whole = int.parse(fixed.substring(0, point));
|
|
return '\$${_chatInfoInteger(whole)}.$decimals';
|
|
}
|
|
|
|
/// The "Chat information" panel. It rebuilds from the controller, so metrics
|
|
/// that arrive while it is open replace the displayed snapshot.
|
|
class _ChatInfoSheet extends StatelessWidget {
|
|
const _ChatInfoSheet({required this.controller});
|
|
|
|
final ChatThreadController controller;
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final cupertino =
|
|
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
|
return AnimatedBuilder(
|
|
animation: controller,
|
|
builder: (context, _) {
|
|
final content = Column(
|
|
key: const Key('chat-info-sheet'),
|
|
mainAxisSize: MainAxisSize.min,
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
AppSheetHeader(
|
|
title: 'Chat information',
|
|
cupertino: cupertino,
|
|
doneKey: const Key('chat-info-close'),
|
|
),
|
|
for (final metric in _chatInfoMetrics(controller.usage))
|
|
_ChatInfoRow(metric: metric, cupertino: cupertino),
|
|
ChatAccountUsageSection(
|
|
usage: controller.accountUsage,
|
|
cupertino: cupertino,
|
|
),
|
|
Padding(
|
|
padding: const EdgeInsetsDirectional.fromSTEB(24, 8, 24, 16),
|
|
child: Text(
|
|
'Last reported by the harness. '
|
|
'Unavailable values are not estimated.',
|
|
style:
|
|
(cupertino
|
|
? CupertinoTheme.of(context).textTheme.textStyle
|
|
: Theme.of(context).textTheme.bodySmall)
|
|
?.copyWith(
|
|
color: cupertino
|
|
? CupertinoColors.secondaryLabel.resolveFrom(
|
|
context,
|
|
)
|
|
: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
),
|
|
),
|
|
),
|
|
],
|
|
);
|
|
if (!cupertino) return SingleChildScrollView(child: content);
|
|
// A tall text scale must scroll inside the popup rather than push its
|
|
// heading off-screen. The height follows the viewport, not a fixed size.
|
|
return ConstrainedBox(
|
|
constraints: BoxConstraints(
|
|
maxHeight: MediaQuery.sizeOf(context).height * 0.8,
|
|
),
|
|
child: SingleChildScrollView(child: content),
|
|
);
|
|
},
|
|
);
|
|
}
|
|
}
|
|
|
|
class _ChatInfoRow extends StatelessWidget {
|
|
const _ChatInfoRow({required this.metric, required this.cupertino});
|
|
|
|
final _ChatInfoMetric metric;
|
|
final bool cupertino;
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final secondary = cupertino
|
|
? CupertinoColors.secondaryLabel.resolveFrom(context)
|
|
: Theme.of(context).colorScheme.onSurfaceVariant;
|
|
final labelStyle =
|
|
(cupertino
|
|
? CupertinoTheme.of(context).textTheme.textStyle
|
|
: Theme.of(context).textTheme.bodySmall)
|
|
?.copyWith(color: secondary);
|
|
final valueStyle = cupertino
|
|
? CupertinoTheme.of(context).textTheme.textStyle
|
|
: Theme.of(context).textTheme.bodyLarge;
|
|
return Padding(
|
|
key: Key('chat-info-metric-${metric.key}'),
|
|
padding: const EdgeInsetsDirectional.fromSTEB(24, 6, 24, 6),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(metric.label, style: labelStyle),
|
|
Text(
|
|
metric.value,
|
|
key: Key('chat-info-value-${metric.key}'),
|
|
style: metric.available
|
|
? valueStyle
|
|
: valueStyle?.copyWith(color: secondary),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
/// 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
|
|
/// from the recorded row, and the icon only repeats that state with theme roles,
|
|
/// so an unknown kind or state is still readable without colour. The trailing
|
|
/// control expands the same line into the recorded lifecycle and any recorded
|
|
/// input, output, error, duration and edit diff; collapsing restores the single
|
|
/// line without touching the turn.
|
|
class _ChatActivityLine extends StatefulWidget {
|
|
const _ChatActivityLine({required this.row, this.onDismiss});
|
|
|
|
final JsonMap row;
|
|
|
|
/// Set only for a running compaction, whose line is the local notice the
|
|
/// operator can hide until that compaction's condition changes.
|
|
final VoidCallback? onDismiss;
|
|
|
|
@override
|
|
State<_ChatActivityLine> createState() => _ChatActivityLineState();
|
|
}
|
|
|
|
class _ChatActivityLineState extends State<_ChatActivityLine> {
|
|
bool _expanded = false;
|
|
|
|
void _toggle() => setState(() => _expanded = !_expanded);
|
|
|
|
/// The latest recorded update, which is also the line's label/state. With no
|
|
/// records (a caller-built row) the row itself carries the same fields.
|
|
JsonMap _record() {
|
|
final records = widget.row['records'];
|
|
if (records is List) {
|
|
for (final record in records.reversed) {
|
|
if (record is Map) return JsonMap.from(record);
|
|
}
|
|
}
|
|
return widget.row;
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final cupertino =
|
|
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
|
final state = '${widget.row['state'] ?? ''}'.trim().toLowerCase();
|
|
final failed = state == 'failed' || state == 'error';
|
|
final running = state == 'running';
|
|
final completed =
|
|
state == 'completed' || state == 'ended' || state == 'succeeded';
|
|
final secondary = _secondary(context, cupertino);
|
|
final color = failed
|
|
? (cupertino
|
|
? CupertinoColors.systemRed.resolveFrom(context)
|
|
: Theme.of(context).colorScheme.error)
|
|
: secondary;
|
|
final style =
|
|
(cupertino
|
|
? CupertinoTheme.of(context).textTheme.textStyle
|
|
: Theme.of(context).textTheme.bodySmall)
|
|
?.copyWith(color: color);
|
|
final icon = failed
|
|
? (cupertino
|
|
? CupertinoIcons.exclamationmark_circle
|
|
: Icons.error_outline)
|
|
: running
|
|
? (cupertino ? CupertinoIcons.arrow_2_circlepath : Icons.sync)
|
|
: completed
|
|
? (cupertino
|
|
? CupertinoIcons.check_mark_circled
|
|
: Icons.check_circle_outline)
|
|
: (cupertino ? CupertinoIcons.circle : Icons.circle_outlined);
|
|
final label = '${widget.row['label'] ?? ''}'.trim();
|
|
return Padding(
|
|
padding: const EdgeInsets.symmetric(vertical: 6),
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
Row(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Expanded(
|
|
child: Semantics(
|
|
container: true,
|
|
label: label,
|
|
value: state,
|
|
child: ExcludeSemantics(
|
|
child: Row(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Icon(icon, color: color),
|
|
const SizedBox(width: 8),
|
|
Expanded(child: Text(label, style: style)),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
),
|
|
_toggleControl(cupertino),
|
|
if (widget.onDismiss != null)
|
|
_noticeDismissControl(
|
|
cupertino: cupertino,
|
|
label: chatNoticeDismissLabel(ChatNoticeKind.compaction),
|
|
key: const ValueKey<String>('chat-notice-dismiss-compaction'),
|
|
onPressed: widget.onDismiss!,
|
|
),
|
|
],
|
|
),
|
|
if (_expanded) _detail(context, cupertino, secondary),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
/// The host's own disclosure control, with an action label that states what a
|
|
/// tap does. Cupertino's button has no built-in label, so the wrapping node
|
|
/// carries it and the button keeps the pointer handling.
|
|
Widget _toggleControl(bool cupertino) {
|
|
const key = ValueKey<String>('chat-activity-toggle');
|
|
final label = _expanded ? 'Collapse activity' : 'Expand activity';
|
|
final icon = Icon(
|
|
_expanded
|
|
? (cupertino ? CupertinoIcons.chevron_up : Icons.expand_less)
|
|
: (cupertino ? CupertinoIcons.chevron_down : Icons.expand_more),
|
|
);
|
|
if (!cupertino) {
|
|
return IconButton(
|
|
key: key,
|
|
tooltip: label,
|
|
onPressed: _toggle,
|
|
icon: icon,
|
|
);
|
|
}
|
|
return Semantics(
|
|
container: true,
|
|
button: true,
|
|
label: label,
|
|
onTap: _toggle,
|
|
child: ExcludeSemantics(
|
|
child: CupertinoButton(
|
|
key: key,
|
|
padding: EdgeInsets.zero,
|
|
onPressed: _toggle,
|
|
child: icon,
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
/// The expanded section: every recorded field, with the exact absence sentence
|
|
/// for one the record did not carry. Only [ChatActivityDetail] reads the
|
|
/// record, so the line and its details cannot disagree about a field.
|
|
Widget _detail(BuildContext context, bool cupertino, Color secondary) {
|
|
final detail = chatActivityDetail(_record());
|
|
final baseStyle = cupertino
|
|
? CupertinoTheme.of(context).textTheme.textStyle
|
|
: Theme.of(context).textTheme.bodyMedium;
|
|
final labelStyle = TextStyle(color: secondary, fontWeight: FontWeight.w600);
|
|
Widget field(String label, String value) {
|
|
final absent =
|
|
value == chatActivityLifecycleAbsent ||
|
|
value == chatActivityInputAbsent ||
|
|
value == chatActivityOutputAbsent ||
|
|
value == chatActivityErrorAbsent ||
|
|
value == chatActivityDurationAbsent ||
|
|
value == chatActivityDiffAbsent;
|
|
return Padding(
|
|
padding: const EdgeInsetsDirectional.only(top: 8),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(label, style: labelStyle),
|
|
DefaultTextStyle.merge(
|
|
style: absent ? TextStyle(color: secondary) : const TextStyle(),
|
|
child: SelectableText(value),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
return DefaultTextStyle.merge(
|
|
style: baseStyle,
|
|
child: Padding(
|
|
key: const ValueKey<String>('chat-activity-details'),
|
|
padding: const EdgeInsetsDirectional.only(bottom: 2),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
field('Lifecycle', detail.lifecycle),
|
|
field('Input', detail.input),
|
|
field('Output', detail.output),
|
|
field('Error', detail.error),
|
|
field('Duration', detail.duration),
|
|
field('Edit diff', detail.diff),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
Color _secondary(BuildContext context, bool cupertino) => cupertino
|
|
? CupertinoColors.secondaryLabel.resolveFrom(context)
|
|
: Theme.of(context).colorScheme.onSurfaceVariant;
|
|
}
|