merge(app): land chat turn order

This commit is contained in:
2026-10-23 15:35:49 +01:00
4 changed files with 95 additions and 45 deletions
@@ -304,6 +304,28 @@ class ChatThreadController extends ChangeNotifier {
bool _owned(int token) => !_disposed && token == _generation;
/// Puts a sent turn into the transcript where it was sent, as the web does:
/// after everything held so far and before any reply frame that follows. It
/// carries the id the harness will persist, so the live echo is ignored and
/// the history copy replaces it in place instead of moving it.
void insertLocal(JsonMap message) {
if (_disposed) return;
_messages = [..._messages, message];
_notify();
}
/// Removes a sent turn the server refused.
void removeLocal(String operationId) {
if (_disposed) return;
final next = [
for (final message in _messages)
if (message['operation_id'] != operationId) message,
];
if (next.length == _messages.length) return;
_messages = next;
_notify();
}
void _notify() {
if (!_disposed) notifyListeners();
}
@@ -132,9 +132,6 @@ class _ChatThreadViewState extends State<ChatThreadView> {
/// completion, which would expose stale notices mid-repair.
Future<void>? _repair;
/// A sent turn shown before history or a live frame echoes it.
final List<JsonMap> _optimistic = [];
/// 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.
@@ -194,32 +191,28 @@ class _ChatThreadViewState extends State<ChatThreadView> {
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},
for (final attachment in send.attachments)
{
'type': 'file',
'name': attachment['name'],
'uri': attachment['name'],
'mime': attachment['mime'],
},
],
});
_controller.insertLocal({
'id': send.optimisticId,
'session_id': send.sessionId,
'role': 'user',
'operation_id': send.operationId,
'native_message_id': send.nativeMessageId,
'parts': [
{'type': 'text', 'text': send.text},
for (final attachment in send.attachments)
{
'type': 'file',
'name': attachment['name'],
'uri': attachment['name'],
'mime': attachment['mime'],
},
],
});
}
void _onRejected(ChatComposerSend send, String error) {
if (!mounted) return;
setState(() {
_optimistic.removeWhere((row) => row['operation_id'] == send.operationId);
});
_controller.removeLocal(send.operationId);
}
/// Reports the harness's recorded usage. The standard sheet is dismissed the
@@ -250,26 +243,9 @@ class _ChatThreadViewState extends State<ChatThreadView> {
);
}
/// 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'];
}
/// 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;
@@ -331,7 +307,6 @@ class _ChatThreadViewState extends State<ChatThreadView> {
_reconnecting = false;
_preGapMessages = null;
_syncGeneration++;
_optimistic.clear();
_commandNotices.clear();
_seedCommandNotice();
_savedOffset = widget.scrollPositions?.read(widget.sessionId);
@@ -213,6 +213,7 @@ JsonMap applyChatEvent(JsonMap thread, JsonMap frame) {
messages.any(
(m) =>
m['id'] == id ||
m['native_message_id'] == id ||
(frame['operation_id'] != null &&
m['operation_id'] == frame['operation_id']),
)) {
@@ -0,0 +1,52 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'chat_composer_bar_fixtures.dart';
import 'chat_thread_fixtures.dart';
void main() {
testWidgets('each reply follows the message it answers, in its own box', (
tester,
) async {
tester.view.physicalSize = const Size(800, 2400);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
var operation = 0;
final gateway = ComposerBarGateway();
addTearDown(gateway.close);
await tester.pumpWidget(
composerThread(gateway, newOperationId: () => 'op-${++operation}'),
);
await tester.pumpAndSettle();
Future<void> send(String text) async {
await tester.enterText(
find.byKey(const Key('chat-composer-field')),
text,
);
await tester.pump();
await tester.tap(find.byKey(const Key('chat-composer-primary')));
await tester.pump();
}
double top(String text) => tester
.getTopLeft(find.textContaining(text, findRichText: true).first)
.dy;
// The reply streams in before the server echoes the operator's turn.
await send('first question');
gateway.emitEvent(chatTextFrame('first answer', messageId: 'a1'));
await tester.pump();
gateway.emitEvent(chatStepFrame('ended'));
await tester.pump();
await send('second question');
gateway.emitEvent(chatTextFrame('second answer', messageId: 'a2'));
await tester.pumpAndSettle();
expect(top('first question'), lessThan(top('first answer')));
expect(top('first answer'), lessThan(top('second question')));
expect(top('second question'), lessThan(top('second answer')));
});
}