import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import '../domain/chat_transcript.dart'; import '../ui/sessions/chat_adaptive.dart'; import '../ui/transcript/chat_markdown_view.dart'; import '../ui/transcript/chat_message_view.dart'; import 'chat_composer_bar.dart'; import 'chat_composer_controller.dart'; import 'chat_draft_store.dart'; import 'chat_row_keys.dart'; import 'chat_thread_controller.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.syncToken = 0, this.drafts, this.newOperationId, }); final ApiGateway gateway; final String sessionId; final VoidCallback onBack; /// The list row's title when this visit knows it; a deep link may not. final String title; /// 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; @override State createState() => _ChatThreadViewState(); } class _ChatThreadViewState extends State { late ChatThreadController _controller = _attach(); late ChatComposerController _composer = _attachComposer(); late ChatRowKeys _rowKeys = ChatRowKeys(); /// A sent turn shown before history or a live frame echoes it. final List _optimistic = []; ChatThreadController _attach() => ChatThreadController(widget.gateway, widget.sessionId)..load(); ChatComposerController _attachComposer() => ChatComposerController( widget.gateway, widget.sessionId, drafts: widget.drafts, newOperationId: widget.newOperationId, onOptimistic: _onOptimistic, onRejected: _onRejected, ); void _onOptimistic(ChatComposerSend send) { if (!mounted) return; setState(() { _optimistic.add({ 'id': send.optimisticId, 'session_id': send.sessionId, 'role': 'user', 'operation_id': send.operationId, 'native_message_id': send.nativeMessageId, 'parts': [ {'type': 'text', 'text': send.text}, ], }); }); } void _onRejected(ChatComposerSend send, String error) { if (!mounted) return; setState(() { _optimistic.removeWhere((row) => row['operation_id'] == send.operationId); }); } /// Local turns whose authoritative copy is not in the held transcript yet. /// A live user frame or a history page that carries the same operation, /// native id or message id hides the local copy instead of drawing it twice. List _visibleMessages() { final messages = _controller.messages; return [ ...messages, for (final pending in _optimistic) if (!messages.any((message) => _isEcho(pending, message))) pending, ]; } bool _isEcho(JsonMap pending, JsonMap message) { if (message['role'] != 'user') return false; if (pending['id'] == message['id']) return true; final operation = pending['operation_id']; if (operation != null && operation == message['operation_id']) return true; final native = '${pending['native_message_id'] ?? ''}'; return native.isNotEmpty && native == message['native_message_id']; } @override void didUpdateWidget(covariant ChatThreadView oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.gateway != widget.gateway || oldWidget.sessionId != widget.sessionId) { _controller.dispose(); _composer.dispose(); _controller = _attach(); _composer = _attachComposer(); _rowKeys = ChatRowKeys(); _optimistic.clear(); } else if (oldWidget.syncToken != widget.syncToken) { unawaited(_controller.resync()); } } @override void dispose() { _composer.dispose(); _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) => AnimatedBuilder( animation: _controller, builder: (context, _) { final cupertino = chatControlsStyleOf(context) == ChatControlsStyle.cupertino; final cards = chatCardRows( permissions: _controller.permissionFrames, forms: _controller.questionForms, answerFor: _controller.permissionAnswerFor, permissionErrorFor: _controller.permissionErrorFor, formErrorFor: _controller.questionErrorFor, ); // A pending approval/question means the turn is waiting on the operator, // not generating, so the transcript indicator and its live region stand // down; the composer's Stop control still follows `running`. final awaiting = cards.any(chatCardAwaitingOperator); final rows = transcriptRows(_visibleMessages(), trailing: cards); // 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 initialLoad = !_controller.loaded && _controller.loading; 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(8, 0, 16, 4), child: Wrap( spacing: 8, runSpacing: 4, crossAxisAlignment: WrapCrossAlignment.center, children: [ _backButton(cupertino), if (widget.title.trim().isNotEmpty) Text( widget.title.trim(), style: cupertino ? CupertinoTheme.of( context, ).textTheme.navTitleTextStyle : Theme.of(context).textTheme.titleLarge, ), ], ), ), 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 (_controller.error != null) ChatErrorNotice( key: const Key('chat-history-error'), message: 'Chat history unavailable\n${_controller.error}', onRetry: _controller.load, ), if (_controller.subscriptionError != null) ChatErrorNotice( key: const Key('chat-live-error'), message: 'Live updates unavailable\n${_controller.subscriptionError}', onRetry: _controller.resync, ), if (_controller.loaded && rows.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: rows[index]['kind'] == 'permission' || rows[index]['kind'] == 'question' ? ChatTranscriptCard( row: rows[index], onPermissionDecision: _controller.replyPermission, onQuestionAnswer: _controller.answerQuestion, ) : ChatMessageView( row: rows[index], textBuilder: chatMarkdownText, ), ), 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, running: _controller.running, ), ], ); }, ); Widget _backButton(bool cupertino) => cupertino ? CupertinoButton( padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 8, 0), onPressed: widget.onBack, child: const Row( mainAxisSize: MainAxisSize.min, children: [ Icon(CupertinoIcons.back), SizedBox(width: 4), Text('Back'), ], ), ) : TextButton.icon( onPressed: widget.onBack, icon: const Icon(Icons.arrow_back), label: const Text('Back to chats'), ); }