merge(app): land chat-attach-send-ui micro-slice

This commit is contained in:
2026-10-22 12:30:43 +01:00
3 changed files with 416 additions and 23 deletions
@@ -4,8 +4,10 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../core/api_gateway.dart';
import '../domain/chat_attachment_draft.dart';
import '../domain/chat_attachment_picker.dart';
import '../domain/chat_attachment_wire.dart';
import '../ui/sessions/chat_adaptive.dart';
import 'chat_composer_controller.dart';
@@ -31,7 +33,9 @@ const String chatQueuedNotice =
/// replaces the operator's caret. Enter inserts a newline and Ctrl/Cmd+Enter
/// sends the plain message. Picked files are memory-only chips: their names are
/// shown with the host's own remove action and the bounded draft owns every
/// refusal. Sending does not yet carry attachments, and paste is not wired.
/// refusal. Send carries the chips as the landed wire parts, keeps them until
/// the prompt is accepted and leaves them in place on a refusal; paste is not
/// wired.
class ChatComposerBar extends StatefulWidget {
const ChatComposerBar({
super.key,
@@ -58,6 +62,10 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
);
final FocusNode _focus = FocusNode(debugLabel: 'chat-composer');
final ChatAttachmentDraft _attachments = ChatAttachmentDraft();
/// The picked bytes behind each chip, positionally aligned with the draft's
/// attachments so two picks of the same name stay distinct.
final List<Uint8List> _bytes = [];
String? _attachmentError;
ChatAttachmentPicker get _picker => widget.picker ?? hostChatAttachmentPicker;
@@ -103,15 +111,34 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
}
// A held key must not post a second prompt.
if (event is! KeyDownEvent) return KeyEventResult.handled;
_send();
unawaited(_send());
return KeyEventResult.handled;
}
void _send() {
/// Builds the chips' exact wire parts and hands them to the composer with the
/// draft's text and operation id. The chips stay while the prompt is in
/// flight so a refusal leaves the draft and its files together; only an
/// accepted prompt clears them.
Future<void> _send() async {
final composer = widget.composer;
if (composer.sending || composer.draft.trim().isEmpty) return;
unawaited(composer.send());
List<JsonMap> parts;
try {
parts = chatAttachmentParts(_attachments, read: _readAttachment);
} on ChatAttachmentWireException catch (error) {
setState(() => _attachmentError = error.message);
return;
}
// Keep the caret in the field while the prompt is in flight, as before.
_focus.requestFocus();
final accepted = await composer.send(attachments: parts);
if (!mounted) return;
if (accepted) {
setState(() {
_replaceAttachments(const [], const []);
_attachmentError = null;
});
}
}
/// Adds the operator's explicit selection through the host seam. A dismissed
@@ -132,19 +159,55 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
setState(() {
_attachmentError = null;
for (final file in picked) {
final refusal = _attachments.add(file.attachment);
if (refusal != null) _attachmentError = refusal.message;
final attachment = file.attachment;
final refusal = _attachments.add(attachment);
if (refusal != null) {
_attachmentError = refusal.message;
} else {
_bytes.add(file.bytes);
}
}
});
}
void _removeAttachment(ChatAttachment attachment) {
/// The picked bytes for the draft's own attachment instance. Identity is the
/// only reliable match when two picks share a name, type and size.
Uint8List? _readAttachment(ChatAttachment attachment) {
final attachments = _attachments.attachments;
for (var index = 0; index < attachments.length; index += 1) {
if (identical(attachments[index], attachment)) return _bytes[index];
}
return null;
}
void _removeAttachmentAt(int index) {
setState(() {
_attachments.remove(attachment);
final remaining = List<ChatAttachment>.from(_attachments.attachments)
..removeAt(index);
final remainingBytes = List<Uint8List>.from(_bytes)..removeAt(index);
_replaceAttachments(remaining, remainingBytes);
_attachmentError = null;
});
}
/// Rebuilds the draft and its aligned bytes in [attachments] order. The draft
/// owns the count and size bounds, and every kept attachment already passed
/// them, so re-adding never refuses.
void _replaceAttachments(
List<ChatAttachment> attachments,
List<Uint8List> bytes,
) {
for (final attachment in _attachments.attachments) {
_attachments.remove(attachment);
}
_bytes
..clear()
..addAll(bytes);
for (final attachment in attachments) {
_attachments.add(attachment);
}
}
@override
void dispose() {
widget.composer.removeListener(_syncDraft);
@@ -272,7 +335,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
Widget _materialChip(ChatAttachment attachment, int index) => Chip(
key: ValueKey<String>('chat-composer-attachment-$index'),
label: Text(attachment.name),
onDeleted: () => _removeAttachment(attachment),
onDeleted: () => _removeAttachmentAt(index),
deleteButtonTooltipMessage: 'Remove ${attachment.name}',
);
@@ -307,14 +370,14 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
container: true,
button: true,
label: 'Remove ${attachment.name}',
onTap: () => _removeAttachment(attachment),
onTap: () => _removeAttachmentAt(index),
child: ExcludeSemantics(
child: CupertinoButton(
key: ValueKey<String>(
'chat-composer-attachment-remove-$index',
),
padding: EdgeInsets.zero,
onPressed: () => _removeAttachment(attachment),
onPressed: () => _removeAttachmentAt(index),
child: Icon(
CupertinoIcons.xmark_circle_fill,
color: CupertinoColors.secondaryLabel.resolveFrom(
@@ -375,7 +438,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
if (stop) {
unawaited(composer.stop());
} else {
_send();
unawaited(_send());
}
}
@@ -14,6 +14,7 @@ class ChatComposerSend {
required this.text,
required this.operationId,
required this.nativeMessageId,
this.attachments = const [],
});
final String sessionId;
@@ -23,6 +24,10 @@ class ChatComposerSend {
final String operationId;
final String nativeMessageId;
/// The `{name, mime, data}` parts already built from the composer's chips,
/// in draft order. Empty for a text-only prompt.
final List<JsonMap> attachments;
/// Mirrors the web's `nativeChatMessageId(operationId) || local-<operationId>`.
String get optimisticId =>
nativeMessageId.isEmpty ? 'local-$operationId' : nativeMessageId;
@@ -120,17 +125,22 @@ class ChatComposerController extends ChangeNotifier {
return _persistDraft(text);
}
/// Sends the non-blank draft as one plain message. Only the wire text is
/// trimmed. A refused unchanged intent reuses its operation id; a refusal
/// restores the exact draft unless newer text is already present.
Future<void> send() async {
if (_disposed || _sending) return;
/// Sends the non-blank draft as one plain message, carrying [attachments] in
/// draft order. Only the wire text is trimmed. A refused unchanged intent
/// (same text and parts) reuses its operation id; a refusal restores the
/// exact draft unless newer text is already present. Returns whether the
/// server accepted this prompt, so the composer can clear its chips only
/// once the send is accepted.
Future<bool> send({List<JsonMap> attachments = const []}) async {
if (_disposed || _sending) return false;
final exact = _draft;
final text = exact.trim();
if (text.isEmpty) return;
if (text.isEmpty) return false;
final previous = _pending;
late final ChatComposerSend intent;
if (previous != null && previous.text == text) {
if (previous != null &&
previous.text == text &&
_sameAttachments(previous.attachments, attachments)) {
intent = previous;
} else {
final operationId = _nextOperationId();
@@ -139,6 +149,7 @@ class ChatComposerController extends ChangeNotifier {
text: text,
operationId: operationId,
nativeMessageId: nativeChatMessageId(operationId),
attachments: attachments,
);
}
_pending = intent;
@@ -148,22 +159,24 @@ class ChatComposerController extends ChangeNotifier {
_edited = true;
_notify();
await _persistDraft('');
if (_disposed) return;
if (_disposed) return false;
onOptimistic?.call(intent);
try {
final reply = await _repository.prompt(
sessionId,
text,
operationId: intent.operationId,
attachments: intent.attachments,
);
if (_disposed) return;
if (_disposed) return false;
_queued = reply['chat_queued'] == true;
_pending = null;
_sending = false;
_error = null;
_notify();
return true;
} catch (error) {
if (_disposed) return;
if (_disposed) return false;
final message = '$error';
_sending = false;
_error = message;
@@ -172,10 +185,11 @@ class ChatComposerController extends ChangeNotifier {
_edited = true;
_notify();
await _persistDraft(exact);
if (_disposed) return;
if (_disposed) return false;
}
onRejected?.call(intent, message);
_notify();
return false;
}
}
@@ -215,6 +229,23 @@ class ChatComposerController extends ChangeNotifier {
newOperationId?.call() ??
'native-chat-${DateTime.now().microsecondsSinceEpoch}-${_operationSeq++}';
/// Whether two prompts carry the same attachment parts, so a retry after a
/// refusal can keep the original operation id. Parts are the exact wire maps
/// this composer built, so a shallow key-by-key comparison is enough.
bool _sameAttachments(List<JsonMap> a, List<JsonMap> b) {
if (identical(a, b)) return true;
if (a.length != b.length) return false;
for (var index = 0; index < a.length; index += 1) {
final first = a[index];
final second = b[index];
if (first.length != second.length) return false;
for (final key in first.keys) {
if (!second.containsKey(key) || first[key] != second[key]) return false;
}
}
return true;
}
Future<void> _persistDraft(String text) {
final write = _writes.then((_) async {
var stored = false;