merge(app): land native chat composer after retained-run recovery
This commit is contained in:
@@ -0,0 +1,267 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../ui/sessions/chat_adaptive.dart';
|
||||
import 'chat_composer_controller.dart';
|
||||
|
||||
/// The composer's multiline placeholder, verbatim from the web client.
|
||||
const String chatComposerPlaceholder = 'Message the agent… or / for commands';
|
||||
|
||||
/// The single primary control's words while a turn is and is not running.
|
||||
const String chatSendLabel = 'Send';
|
||||
const String chatStopLabel = 'Stop';
|
||||
|
||||
/// Shown while the reply says this prompt waits behind the running turn.
|
||||
const String chatQueuedNotice =
|
||||
'Queued — it will send when the current turn finishes.';
|
||||
|
||||
/// The foot of one conversation: a native multiline field and one primary
|
||||
/// Send/Stop control, driven by the landed [ChatComposerController].
|
||||
///
|
||||
/// The field owns only its [TextEditingController] and focus; the durable draft
|
||||
/// text lives in the composer controller, so a live transcript rebuild never
|
||||
/// replaces the operator's caret. Enter inserts a newline and Ctrl/Cmd+Enter
|
||||
/// sends the plain message. Attachments and the slash palette are not part of
|
||||
/// this slice.
|
||||
class ChatComposerBar extends StatefulWidget {
|
||||
const ChatComposerBar({
|
||||
super.key,
|
||||
required this.composer,
|
||||
required this.running,
|
||||
});
|
||||
|
||||
final ChatComposerController composer;
|
||||
|
||||
/// The thread controller's running bit; it alone decides Send versus Stop.
|
||||
final bool running;
|
||||
|
||||
@override
|
||||
State<ChatComposerBar> createState() => _ChatComposerBarState();
|
||||
}
|
||||
|
||||
class _ChatComposerBarState extends State<ChatComposerBar> {
|
||||
late final TextEditingController _text = TextEditingController(
|
||||
text: widget.composer.draft,
|
||||
);
|
||||
final FocusNode _focus = FocusNode(debugLabel: 'chat-composer');
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
widget.composer.addListener(_syncDraft);
|
||||
unawaited(widget.composer.loadDraft());
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant ChatComposerBar oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.composer != widget.composer) {
|
||||
oldWidget.composer.removeListener(_syncDraft);
|
||||
widget.composer.addListener(_syncDraft);
|
||||
_syncDraft();
|
||||
}
|
||||
}
|
||||
|
||||
/// External draft changes (saved-draft load, send clear, refusal restore)
|
||||
/// replace the field's text but never the focus node, so the caret survives
|
||||
/// live transcript rebuilds.
|
||||
void _syncDraft() {
|
||||
if (!mounted) return;
|
||||
final draft = widget.composer.draft;
|
||||
if (_text.text == draft) return;
|
||||
_text.value = TextEditingValue(
|
||||
text: draft,
|
||||
selection: TextSelection.collapsed(offset: draft.length),
|
||||
);
|
||||
}
|
||||
|
||||
KeyEventResult _onKey(FocusNode node, KeyEvent event) {
|
||||
if (event.logicalKey != LogicalKeyboardKey.enter &&
|
||||
event.logicalKey != LogicalKeyboardKey.numpadEnter) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
final keyboard = HardwareKeyboard.instance;
|
||||
if (!keyboard.isControlPressed && !keyboard.isMetaPressed) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
// A held key must not post a second prompt.
|
||||
if (event is! KeyDownEvent) return KeyEventResult.handled;
|
||||
_send();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
void _send() {
|
||||
final composer = widget.composer;
|
||||
if (composer.sending || composer.draft.trim().isEmpty) return;
|
||||
unawaited(composer.send());
|
||||
_focus.requestFocus();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
widget.composer.removeListener(_syncDraft);
|
||||
_text.dispose();
|
||||
_focus.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
return ListenableBuilder(
|
||||
listenable: widget.composer,
|
||||
builder: (context, _) {
|
||||
final composer = widget.composer;
|
||||
final error = composer.error ?? composer.draftError;
|
||||
return SafeArea(
|
||||
top: false,
|
||||
child: Padding(
|
||||
key: const Key('chat-composer'),
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 8),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (composer.queued)
|
||||
_notice(
|
||||
context,
|
||||
cupertino,
|
||||
key: const Key('chat-composer-queued'),
|
||||
text: chatQueuedNotice,
|
||||
),
|
||||
if (error != null)
|
||||
_notice(
|
||||
context,
|
||||
cupertino,
|
||||
key: const Key('chat-composer-error'),
|
||||
text: error,
|
||||
failed: true,
|
||||
),
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Focus(
|
||||
canRequestFocus: false,
|
||||
includeSemantics: false,
|
||||
onKeyEvent: _onKey,
|
||||
child: _field(cupertino),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
_primary(context, cupertino),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _field(bool cupertino) {
|
||||
final composer = widget.composer;
|
||||
void changed(String value) => unawaited(composer.setDraft(value));
|
||||
if (cupertino) {
|
||||
return CupertinoTextField(
|
||||
key: const Key('chat-composer-field'),
|
||||
controller: _text,
|
||||
focusNode: _focus,
|
||||
placeholder: chatComposerPlaceholder,
|
||||
minLines: 1,
|
||||
maxLines: 6,
|
||||
keyboardType: TextInputType.multiline,
|
||||
textInputAction: TextInputAction.newline,
|
||||
onChanged: changed,
|
||||
);
|
||||
}
|
||||
return TextField(
|
||||
key: const Key('chat-composer-field'),
|
||||
controller: _text,
|
||||
focusNode: _focus,
|
||||
minLines: 1,
|
||||
maxLines: 6,
|
||||
keyboardType: TextInputType.multiline,
|
||||
textInputAction: TextInputAction.newline,
|
||||
onChanged: changed,
|
||||
decoration: const InputDecoration(
|
||||
hintText: chatComposerPlaceholder,
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _primary(BuildContext context, bool cupertino) {
|
||||
final composer = widget.composer;
|
||||
final stop = widget.running;
|
||||
final enabled = stop
|
||||
? !composer.stopping
|
||||
: !composer.sending && composer.draft.trim().isNotEmpty;
|
||||
void press() {
|
||||
if (stop) {
|
||||
unawaited(composer.stop());
|
||||
} else {
|
||||
_send();
|
||||
}
|
||||
}
|
||||
|
||||
final label = Text(stop ? chatStopLabel : chatSendLabel);
|
||||
if (cupertino) {
|
||||
return CupertinoButton(
|
||||
key: const Key('chat-composer-primary'),
|
||||
color: stop ? CupertinoColors.systemRed.resolveFrom(context) : null,
|
||||
onPressed: enabled ? press : null,
|
||||
child: label,
|
||||
);
|
||||
}
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
return FilledButton(
|
||||
key: const Key('chat-composer-primary'),
|
||||
style: stop
|
||||
? FilledButton.styleFrom(
|
||||
backgroundColor: scheme.error,
|
||||
foregroundColor: scheme.onError,
|
||||
)
|
||||
: null,
|
||||
onPressed: enabled ? press : null,
|
||||
child: label,
|
||||
);
|
||||
}
|
||||
|
||||
/// A polite, secondary line for queued/refused state. The error uses the
|
||||
/// host's own semantic error tint, never a bespoke palette.
|
||||
Widget _notice(
|
||||
BuildContext context,
|
||||
bool cupertino, {
|
||||
required Key key,
|
||||
required String text,
|
||||
bool failed = false,
|
||||
}) {
|
||||
final theme = Theme.of(context);
|
||||
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);
|
||||
return Semantics(
|
||||
liveRegion: true,
|
||||
child: Padding(
|
||||
key: key,
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Text(text, style: style),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,9 @@ import '../../../core/api_gateway.dart';
|
||||
import '../domain/chat_transcript.dart';
|
||||
import '../ui/sessions/chat_adaptive.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';
|
||||
|
||||
@@ -24,6 +27,8 @@ class ChatThreadView extends StatefulWidget {
|
||||
required this.onBack,
|
||||
this.title = '',
|
||||
this.syncToken = 0,
|
||||
this.drafts,
|
||||
this.newOperationId,
|
||||
});
|
||||
|
||||
final ApiGateway gateway;
|
||||
@@ -36,25 +41,91 @@ class ChatThreadView extends StatefulWidget {
|
||||
/// 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<ChatThreadView> createState() => _ChatThreadViewState();
|
||||
}
|
||||
|
||||
class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
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<JsonMap> _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<JsonMap> _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());
|
||||
}
|
||||
@@ -62,6 +133,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_composer.dispose();
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
@@ -72,7 +144,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
builder: (context, _) {
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
final rows = transcriptRows(_controller.messages);
|
||||
final rows = transcriptRows(_visibleMessages());
|
||||
// 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
|
||||
@@ -80,95 +152,110 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
// across paging and streaming.
|
||||
final keys = _rowKeys.forRows(rows);
|
||||
final initialLoad = !_controller.loaded && _controller.loading;
|
||||
return ListView(
|
||||
key: ValueKey<String>('chat-thread-${widget.sessionId}'),
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
return Column(
|
||||
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,
|
||||
Expanded(
|
||||
child: ListView(
|
||||
key: ValueKey<String>('chat-thread-${widget.sessionId}'),
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
children: [
|
||||
_backButton(cupertino),
|
||||
if (widget.title.trim().isNotEmpty)
|
||||
Text(
|
||||
widget.title.trim(),
|
||||
style: cupertino
|
||||
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
|
||||
: Theme.of(context).textTheme.titleLarge,
|
||||
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<String>(keys[index]),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: ChatMessageView(row: rows[index]),
|
||||
),
|
||||
if (_controller.running)
|
||||
Padding(
|
||||
key: const Key('chat-running'),
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Semantics(
|
||||
liveRegion: true,
|
||||
child: const Text('Assistant is responding…'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
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<String>(keys[index]),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: ChatMessageView(row: rows[index]),
|
||||
),
|
||||
if (_controller.running)
|
||||
Padding(
|
||||
key: const Key('chat-running'),
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Semantics(
|
||||
liveRegion: true,
|
||||
child: const Text('Assistant is responding…'),
|
||||
),
|
||||
),
|
||||
ChatComposerBar(
|
||||
key: ValueKey<String>('chat-composer-${widget.sessionId}'),
|
||||
composer: _composer,
|
||||
running: _controller.running,
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user