App: open a chat with one round trip

The thread controller asks chat_subscribe to carry the newest history page
(history: true, limit 200) and applies it from the reply; a server that
leaves the page out is asked with chat_messages as before. Deltas arriving
before the reply are recorded from the start of the subscribe, and settle
against the page's live_seq exactly as for a separate read.

Also documents the subscribe history field and benchmarks the indexed page
at limits 20 and 100.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 15:09:02 +00:00
parent 686690f7b4
commit 608b6b8edb
7 changed files with 201 additions and 61 deletions
@@ -52,6 +52,9 @@ class ChatThreadController extends ChangeNotifier {
final ApiGateway gateway;
final String sessionId;
/// Messages asked for per history page (servers may serve fewer).
static const _pageLimit = 200;
late final ChatRepository _repository = ChatRepository(gateway);
late final ChatThreadCards _cards = ChatThreadCards(
repository: _repository,
@@ -212,9 +215,18 @@ class ChatThreadController extends ChangeNotifier {
_loading = true;
_error = null;
_notify();
await _attach();
if (!_owned(token)) return;
await _readNewest(token, replaceHeldTurn: false);
final frames = _live.beginRead();
final page = await _attach();
if (!_owned(token)) {
_live.abandon(frames);
return;
}
await _readNewest(
token,
replaceHeldTurn: false,
frames: frames,
page: page,
);
}
/// Reads the next older page. Only offered while the server says `has_more`;
@@ -229,7 +241,7 @@ class ChatThreadController extends ChangeNotifier {
final page = await _repository.history(
sessionId,
cursor: _cursor,
limit: 200,
limit: _pageLimit,
);
if (!_owned(token)) return;
turnDiffs.apply(page['turnDiffs'], sessionId);
@@ -276,17 +288,27 @@ class ChatThreadController extends ChangeNotifier {
_awaitingResponseOperation = null;
_authoritative = false;
_notify();
await _attach(force: true);
if (!_owned(token)) return;
await _readNewest(token, replaceHeldTurn: true);
final frames = _live.beginRead();
final page = await _attach(force: true);
if (!_owned(token)) {
_live.abandon(frames);
return;
}
await _readNewest(token, replaceHeldTurn: true, frames: frames, page: page);
}
Future<void> _readNewest(int token, {required bool replaceHeldTurn}) async {
// Deltas of a reply streaming during the read: the page holds the reply
// up to its own point, and those after it are folded back on top.
final frames = _live.beginRead();
/// Applies the newest history page: [page] when the subscribe reply carried
/// it, else one read now. [frames] records the deltas of a reply streaming
/// meanwhile: the page holds the reply up to its own point, and those after
/// it are folded back on top.
Future<void> _readNewest(
int token, {
required bool replaceHeldTurn,
required List<JsonMap> frames,
JsonMap? page,
}) async {
try {
final page = await _repository.history(sessionId, limit: 200);
page ??= await _repository.history(sessionId, limit: _pageLimit);
if (!_owned(token)) {
_live.abandon(frames);
return;
@@ -338,22 +360,29 @@ class ChatThreadController extends ChangeNotifier {
_notify();
}
/// Attaches the session stream once per connection. A refusal leaves history
/// Attaches the session stream once per connection, asking the reply to
/// carry the newest history page, which is returned (null when the server
/// left it out or the stream was already attached). A refusal leaves history
/// usable (the live stream is simply not attached) and is retried on resync.
Future<void> _attach({bool force = false}) async {
if (_disposed || (_subscribed && !force)) return;
Future<JsonMap?> _attach({bool force = false}) async {
if (_disposed || (_subscribed && !force)) return null;
try {
final reply = await _repository.subscribe(sessionId);
if (_disposed) return;
final reply = await _repository.subscribe(
sessionId,
historyLimit: _pageLimit,
);
if (_disposed) return null;
_subscribed = true;
_subscriptionError = null;
_applyQueue(reply['chat_queue']);
_applyShown(reply['chat_shown'], replace: true);
return ChatRepository.historyPageOf(reply);
} catch (error) {
// History stays usable, but the UI must report that live updates failed.
if (_disposed) return;
if (_disposed) return null;
_subscribed = false;
_subscriptionError = '$error';
return null;
}
}
+29 -19
View File
@@ -154,25 +154,29 @@ class ChatRepository {
final reply = await gateway.call('chat_messages', {
'chat_query': {'session_id': sessionId, 'limit': limit, 'cursor': cursor},
});
return historyPageOf(reply) ??
{
'messages': _maps(reply['chat_messages']),
'nextCursor': '',
'hasMore': false,
'turnDiffs': ?reply['chat_turn_diffs'],
};
}
/// The history page a `chat_messages` or `chat_subscribe` reply carries,
/// or null when it carries none.
static JsonMap? historyPageOf(JsonMap reply) {
final page = reply['chat_history'];
// The session's recorded per-turn changes ride with its history.
final turnDiffs = reply['chat_turn_diffs'];
if (page is Map) {
return {
'messages': _maps(page['messages']),
'nextCursor': '${page['next_cursor'] ?? ''}',
'hasMore': page['has_more'] == true,
'turnDiffs': ?turnDiffs,
// A streaming reply's text so far (see chat_live_frames.dart).
if (page['live_seq'] is int) 'liveSeq': page['live_seq'],
if (page['live_parts'] is List) 'liveParts': page['live_parts'],
};
}
if (page is! Map) return null;
return {
'messages': _maps(reply['chat_messages']),
'nextCursor': '',
'hasMore': false,
'turnDiffs': ?turnDiffs,
'messages': _maps(page['messages']),
'nextCursor': '${page['next_cursor'] ?? ''}',
'hasMore': page['has_more'] == true,
// The session's recorded per-turn changes ride with its history.
'turnDiffs': ?reply['chat_turn_diffs'],
// A streaming reply's text so far (see chat_live_frames.dart).
if (page['live_seq'] is int) 'liveSeq': page['live_seq'],
if (page['live_parts'] is List) 'liveParts': page['live_parts'],
};
}
@@ -189,9 +193,15 @@ class ChatRepository {
return Map<String, dynamic>.from(body);
}
Future<JsonMap> subscribe(String sessionId) =>
/// Attaches the session's live stream. With [historyLimit] the reply also
/// carries the newest history page (see [historyPageOf]) when the server
/// supports it, saving the separate `chat_messages` round trip.
Future<JsonMap> subscribe(String sessionId, {int? historyLimit}) =>
gateway.call('chat_subscribe', {
'chat_subscribe': {'session_id': sessionId},
'chat_subscribe': {
'session_id': sessionId,
if (historyLimit != null) ...{'history': true, 'limit': historyLimit},
},
});
Future<JsonMap> create({
required String title,
@@ -303,9 +303,9 @@ void main() {
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(
replaceSilentSocket: false,
channelFactory: (_) => channel,
);
replaceSilentSocket: false,
channelFactory: (_) => channel,
);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/chat/s1')),
);
@@ -331,6 +331,8 @@ void main() {
// The exact route names the session; the request carries the same id.
expect(requestOf(channel, 'chat_subscribe')!['chat_subscribe'], {
'session_id': 's1',
'history': true,
'limit': 200,
});
expect(requestOf(channel, 'chat_messages')!['chat_query'], {
'session_id': 's1',
@@ -461,6 +463,8 @@ void main() {
expect(requestOf(channel, 'chat_subscribe', index: 1)!['chat_subscribe'], {
'session_id': 'target',
'history': true,
'limit': 200,
});
expect(requestOf(channel, 'chat_messages', index: 1)!['chat_query'], {
'session_id': 'target',
@@ -499,9 +503,9 @@ void main() {
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(
replaceSilentSocket: false,
channelFactory: (_) => channel,
);
replaceSilentSocket: false,
channelFactory: (_) => channel,
);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/chat')),
);
@@ -712,9 +716,9 @@ void main() {
addTearDown(tester.view.reset);
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(
replaceSilentSocket: false,
channelFactory: (_) => channel,
);
replaceSilentSocket: false,
channelFactory: (_) => channel,
);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/chat')),
);
@@ -797,9 +801,9 @@ void main() {
addTearDown(tester.view.reset);
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(
replaceSilentSocket: false,
channelFactory: (_) => channel,
);
replaceSilentSocket: false,
channelFactory: (_) => channel,
);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/chat')),
);
@@ -855,9 +859,9 @@ void main() {
addTearDown(tester.view.reset);
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(
replaceSilentSocket: false,
channelFactory: (_) => channel,
);
replaceSilentSocket: false,
channelFactory: (_) => channel,
);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/chat')),
);
@@ -45,7 +45,7 @@ void main() {
'chat_messages',
]);
expect(gateway.calls.first.fields, {
'chat_subscribe': {'session_id': 's'},
'chat_subscribe': {'session_id': 's', 'history': true, 'limit': 200},
});
expect(gateway.calls.last.fields['chat_query'], {
'session_id': 's',
@@ -0,0 +1,87 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_controller.dart';
import 'chat_thread_fixtures.dart';
// Opening a chat used to take two round trips: chat_subscribe, then
// chat_messages. The subscribe now asks for the newest page in its reply; a
// server that leaves it out is asked with chat_messages as before.
void main() {
late FakeChatGateway gateway;
late ChatThreadController controller;
setUp(() {
gateway = FakeChatGateway();
controller = ChatThreadController(gateway, 's');
});
tearDown(() {
controller.dispose();
gateway.close();
});
List<String> types() => [for (final call in gateway.calls) call.type];
test('the subscribe reply carries the newest page', () async {
gateway.subscribe = () async => {
...chatPage([chatMessage('u', 'user'), chatMessage('a', 'assistant')]),
'chat_queue': {'session_id': 's', 'prompts': []},
};
await controller.load();
expect(gateway.calls.single.fields, {
'chat_subscribe': {'session_id': 's', 'history': true, 'limit': 200},
});
expect(types(), ['chat_subscribe']);
expect([for (final m in controller.messages) m['id']], ['u', 'a']);
expect(controller.loading, isFalse);
});
test(
'a subscribe reply without a page falls back to chat_messages',
() async {
gateway.history = (_) async => chatPage([chatMessage('u', 'user')]);
await controller.load();
expect(types(), ['chat_subscribe', 'chat_messages']);
expect([for (final m in controller.messages) m['id']], ['u']);
},
);
test('deltas before the reply settle against the page it carries', () async {
final reply = Completer<JsonMap>();
gateway.subscribe = () => reply.future;
final loading = controller.load();
await pumpEventQueue();
JsonMap delta(String text, int seq) => {
...chatTextFrame(text, messageId: 'a'),
'seq': seq,
};
gateway.emitEvent(delta('part. ', 11));
gateway.emitEvent(delta('And more.', 12));
await pumpEventQueue();
final page = chatPage([
chatMessage('u', 'user'),
chatMessage(
'a',
'assistant',
parts: [
{'type': 'text', 'id': 'p', 'text': 'The first part. '},
],
),
]);
(page['chat_history'] as JsonMap)
..['live_seq'] = 11
..['live_parts'] = ['p'];
reply.complete(page);
await loading;
expect(types(), ['chat_subscribe']);
final parts = controller.messages.last['parts'] as List;
expect(
[for (final part in parts) (part as Map)['text']],
['The first part. And more.'],
);
});
}
+6
View File
@@ -684,6 +684,12 @@ sessions pipeline runs create. The protocol types are:
`prompts`): the prompts the server still holds for the session, each with
`operation_id`, `message_id`, `native_message_id`, `text`, `client`,
`attachments` and `queued_at`, so a reloaded client draws them as queued.
A body with `history: true` (and `limit`) asks the reply to also carry the
newest history page — `chat_history`, `chat_messages` and `chat_turn_diffs`,
exactly as a `chat_messages` reply — read once the subscription is attached,
so opening a chat takes one round trip. A server that does not support it,
or whose read failed, leaves the page out and the client asks with
`chat_messages`.
- `chat_prompt` may come from any client. A prompt whose session already has a turn
in flight is handed to that turn at once when the harness accepts mid-turn input
(Claude Code reads it from stdin at its next step; Codex takes it with
+12 -8
View File
@@ -394,14 +394,18 @@ func BenchmarkTranscriptNewestPageWholeFile(b *testing.B) {
func BenchmarkTranscriptNewestPageIndexed(b *testing.B) {
path := benchmarkFile(b)
if _, ok, err := indexedTranscriptPage(path, "ses_bench", nil, 100, ""); !ok || err != nil {
b.Fatal("index not served")
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, ok, err := indexedTranscriptPage(path, "ses_bench", nil, 100, ""); !ok || err != nil {
b.Fatal("index not served")
}
for _, limit := range []int{20, 100} {
b.Run(fmt.Sprintf("limit%d", limit), func(b *testing.B) {
if _, ok, err := indexedTranscriptPage(path, "ses_bench", nil, limit, ""); !ok || err != nil {
b.Fatal("index not served")
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, ok, err := indexedTranscriptPage(path, "ses_bench", nil, limit, ""); !ok || err != nil {
b.Fatal("index not served")
}
}
})
}
}