merge(app): land paged live chat thread controller

This commit is contained in:
2026-10-21 20:07:14 +01:00
5 changed files with 683 additions and 0 deletions
@@ -0,0 +1,230 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../data/chat_repository.dart';
import '../domain/chat_transcript.dart';
/// One open conversation's transcript and live turn state.
///
/// The controller attaches to exactly one session: it subscribes that session
/// with `chat_subscribe`, then reads the newest history page. Pushed frames for
/// any other session are ignored, a superseded or disposed read never lands, and
/// a reconnect/resync replaces the held turn with the newest authoritative page
/// instead of merging stale state. The server detaches subscriptions when the
/// socket closes, so disposal only cancels the local stream (there is no
/// `chat_unsubscribe`).
class ChatThreadController extends ChangeNotifier {
ChatThreadController(this.gateway, this.sessionId) {
_subscription = gateway.frames.listen(_onFrame);
}
final ApiGateway gateway;
final String sessionId;
late final ChatRepository _repository = ChatRepository(gateway);
StreamSubscription<JsonMap>? _subscription;
List<JsonMap> _messages = const [];
bool _running = false;
bool _loaded = false;
bool _loading = false;
bool _hasMore = false;
String _cursor = '';
String _nativeTurnId = '';
String? _error;
bool _subscribed = false;
bool _disposed = false;
int _generation = 0;
bool _resyncing = false;
bool _resyncAgain = false;
List<JsonMap> get messages => _messages;
bool get running => _running;
bool get loaded => _loaded;
bool get loading => _loading;
bool get hasMore => _hasMore;
/// The server's opaque older-page cursor. Never interpreted, only passed back.
String get cursor => _cursor;
String? get error => _error;
/// Subscribes this session, then loads its newest history page.
Future<void> load() async {
if (_disposed) return;
final token = ++_generation;
_loading = true;
_error = null;
_notify();
await _attach();
if (!_owned(token)) return;
await _readNewest(token, replaceHeldTurn: false);
}
/// Reads the next older page. Only offered while the server says `has_more`;
/// the cursor is the server's own `next_cursor`, passed back verbatim.
Future<void> loadOlder() async {
if (_disposed || _loading || !_hasMore) return;
final token = ++_generation;
_loading = true;
_error = null;
_notify();
try {
final page = await _repository.history(
sessionId,
cursor: _cursor,
limit: 200,
);
if (!_owned(token)) return;
final merged = mergeChatHistory(
{'messages': _messages},
page,
older: true,
);
_applyPage(merged);
} catch (error) {
if (!_owned(token)) return;
_loading = false;
_error = '$error';
}
_notify();
}
/// The reconnect/resync repair: settle the held turn, re-attach the session,
/// then replace the conversation with the newest authoritative page. Activity
/// replayed while re-attaching (a running step, a form) is fresh native state
/// and survives the replacement. A resync frame also lands here.
Future<void> resync() async {
if (_disposed) return;
if (_resyncing) {
_resyncAgain = true;
return;
}
_resyncing = true;
do {
_resyncAgain = false;
await _resyncOnce();
} while (_resyncAgain && !_disposed);
_resyncing = false;
}
Future<void> _resyncOnce() async {
final token = ++_generation;
// A socket drop removed the frames feeding the turn, so no held turn may
// keep claiming to run until the re-subscribe proves otherwise.
_running = false;
_nativeTurnId = '';
_notify();
await _attach(force: true);
if (!_owned(token)) return;
await _readNewest(token, replaceHeldTurn: true);
}
Future<void> _readNewest(int token, {required bool replaceHeldTurn}) async {
try {
final page = await _repository.history(sessionId, limit: 200);
if (!_owned(token)) return;
if (replaceHeldTurn) {
_messages = (page['messages'] as List? ?? const [])
.whereType<Map>()
.map((message) => Map<String, dynamic>.from(message))
.toList();
_cursor = '${page['nextCursor'] ?? ''}';
_hasMore = page['hasMore'] == true;
} else {
// A live frame may have arrived while the page was loading; merge it
// over the held transcript instead of replacing it.
_applyPage(mergeChatHistory({'messages': _messages}, page));
}
_loaded = true;
_loading = false;
_error = null;
} catch (error) {
if (!_owned(token)) return;
// A refused read is not an empty successful history: the reason stays
// visible and the held transcript is kept.
_loaded = true;
_loading = false;
_error = '$error';
}
_notify();
}
/// Attaches the session stream once per connection. 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;
try {
await _repository.subscribe(sessionId);
if (_disposed) return;
_subscribed = true;
} catch (_) {
// The history path remains usable; resync re-attempts the subscribe.
if (_disposed) return;
_subscribed = false;
}
}
void _onFrame(JsonMap envelope) {
if (_disposed) return;
final body = _eventBody(envelope);
if (body == null || body['session_id'] != sessionId) return;
if (body['kind'] == 'resync') {
unawaited(resync());
return;
}
final current = _thread;
final next = applyChatEvent(current, body);
if (identical(next, current)) return;
_messages = (next['messages'] as List? ?? const [])
.whereType<Map>()
.map((message) => Map<String, dynamic>.from(message))
.toList();
_running = next['running'] == true;
_nativeTurnId = '${next['nativeTurnId'] ?? ''}';
_notify();
}
/// The pushed envelope body, or null for another message type. The server
/// wraps `chat_event` in the typed envelope; domain code never sees the
/// transport fields.
JsonMap? _eventBody(JsonMap envelope) {
if (envelope['type'] != 'chat_event') return null;
final body = envelope['chat_event'];
if (body is! Map) return null;
return Map<String, dynamic>.from(body);
}
JsonMap get _thread => {
'sessionId': sessionId,
'messages': _messages,
'running': _running,
'nativeTurnId': _nativeTurnId,
};
void _applyPage(JsonMap page) {
_messages = (page['messages'] as List? ?? const [])
.whereType<Map>()
.map((message) => Map<String, dynamic>.from(message))
.toList();
_cursor = '${page['nextCursor'] ?? ''}';
_hasMore = page['hasMore'] == true;
_loaded = true;
_loading = false;
}
bool _owned(int token) => !_disposed && token == _generation;
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
_generation++;
unawaited(_subscription?.cancel());
super.dispose();
}
}
+38
View File
@@ -0,0 +1,38 @@
# C2 — Chat thread controller
`lib/features/chat/conversation/chat_thread_controller.dart` owns one open
conversation without any UI. It is constructed with the shared `ApiGateway` and
one `sessionId`, reuses `ChatRepository` for the wire and
`domain/chat_transcript.dart` for the fold, and exposes `messages`, `running`,
`loaded`, `loading`, `hasMore`, `cursor` and `error` through
`ChangeNotifier`.
Behaviour:
- `load()` calls `chat_subscribe` with the exact session body, then reads the
newest `chat_messages` page with `limit: 200` and an empty cursor. A refused
subscribe leaves history usable.
- `loadOlder()` is explicit only, requires `hasMore`, passes the server's opaque
`next_cursor` back verbatim, and prepends the older page by id.
- Only `chat_event` envelopes for this session are folded; replayed/live
text, reasoning, tool, step and user frames use the existing domain fold, so
unknown message and part fields survive.
- `resync()` settles the held turn, re-subscribes, then replaces the transcript,
cursor and `hasMore` with the newest authoritative page. Activity replayed
while re-attaching (for example a running step) survives the replacement. A
pushed `resync` event invokes the same path.
- History failures set `error` and keep the held transcript; they are never
reported as an empty success. Superseded reads and replies after disposal are
ignored.
- Disposal cancels only the local stream subscription. There is no
`chat_unsubscribe` request.
Checks (run from `app/`):
- `flutter test test/features/chat/conversation` — 10 tests passed.
- `flutter test test/features/chat` — 43 tests passed.
- `flutter analyze lib/features/chat test/features/chat` — no issues.
Not done: the controller is not yet wired to a screen, so there is no rendered
or browser change to capture; mobile builds and device verification were not
performed. No shared domain, shell, main, pubspec or server files changed.
@@ -0,0 +1,154 @@
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';
void main() {
late FakeChatGateway gateway;
late ChatThreadController controller;
setUp(() {
gateway = FakeChatGateway();
controller = ChatThreadController(gateway, 's');
});
tearDown(() {
controller.dispose();
gateway.close();
});
test(
'subscribes the exact session, then reads newest history with all data',
() async {
final unknown = chatMessage(
'a',
'assistant',
parts: [
{
'type': 'future_part',
'id': 'p1',
'payload': {'nested': true},
'unknown_field': 7,
},
],
)..['future_message_field'] = 'keep';
gateway.history = (_) async =>
chatPage([unknown], cursor: 'opaque/next?x=1', hasMore: true);
await controller.load();
expect(gateway.calls.map((call) => call.type), [
'chat_subscribe',
'chat_messages',
]);
expect(gateway.calls.first.fields, {
'chat_subscribe': {'session_id': 's'},
});
expect(gateway.calls.last.fields['chat_query'], {
'session_id': 's',
'limit': 200,
'cursor': '',
});
expect(controller.loaded, isTrue);
expect(controller.loading, isFalse);
expect(controller.error, isNull);
expect(controller.running, isFalse);
expect(controller.hasMore, isTrue);
expect(controller.cursor, 'opaque/next?x=1');
expect(controller.messages.single, unknown);
expect(controller.messages.single['future_message_field'], 'keep');
},
);
test(
'loadOlder passes the opaque cursor back and prepends the page',
() async {
gateway.history = (_) async => chatPage(
[chatMessage('b', 'user')],
cursor: 'older-1',
hasMore: true,
);
await controller.load();
final olderReply = Completer<JsonMap>();
gateway.history = (_) => olderReply.future;
final loadingStates = <bool>[];
controller.addListener(() => loadingStates.add(controller.loading));
final older = controller.loadOlder();
expect(gateway.calls.last.fields['chat_query'], {
'session_id': 's',
'limit': 200,
'cursor': 'older-1',
});
expect(controller.loading, isTrue);
expect(loadingStates, [true]);
olderReply.complete(
chatPage(
[chatMessage('a', 'assistant')],
cursor: 'last',
hasMore: false,
),
);
await older;
expect(controller.messages.map((item) => item['id']), ['a', 'b']);
expect(controller.cursor, 'last');
expect(controller.hasMore, isFalse);
expect(controller.loading, isFalse);
},
);
test(
'a superseded history reply never replaces the newer transcript',
() async {
final first = Completer<JsonMap>();
final second = Completer<JsonMap>();
var request = 0;
gateway.history = (_) => request++ == 0 ? first.future : second.future;
final stale = controller.load();
await pumpEventQueue();
final current = controller.load();
await pumpEventQueue();
second.complete(chatPage([chatMessage('new', 'user')]));
await current;
expect(controller.messages.single['id'], 'new');
first.complete(chatPage([chatMessage('old', 'user')]));
await stale;
expect(controller.messages.single['id'], 'new');
expect(controller.loaded, isTrue);
expect(controller.loading, isFalse);
},
);
test(
'a failed history read reports the error, never an empty success',
() async {
gateway.history = (_) => Future.error(StateError('history unavailable'));
await controller.load();
expect(controller.error, contains('history unavailable'));
expect(controller.error, isNot(''));
expect(controller.messages, isEmpty);
expect(controller.loading, isFalse);
expect(controller.loaded, isTrue);
},
);
test('a refused subscribe leaves history usable', () async {
gateway.subscribe = () => Future.error(StateError('not live'));
gateway.history = (_) async => chatPage([chatMessage('a', 'user')]);
await controller.load();
expect(controller.messages.single['id'], 'a');
expect(controller.error, isNull);
expect(controller.loaded, isTrue);
});
}
@@ -0,0 +1,73 @@
import 'dart:async';
import 'package:pipelines_app/core/api_gateway.dart';
/// A fake gateway whose subscribe/history replies the test controls.
class FakeChatGateway implements ApiGateway {
final calls = <({String type, JsonMap fields})>[];
final historyRequests = <Completer<JsonMap>>[];
final _frames = StreamController<JsonMap>.broadcast();
Future<JsonMap> Function(JsonMap fields)? history;
Future<JsonMap> Function()? subscribe;
void Function()? onSubscribe;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add((type: type, fields: fields));
switch (type) {
case 'chat_subscribe':
onSubscribe?.call();
return subscribe == null ? <String, dynamic>{} : subscribe!();
case 'chat_messages':
final completer = Completer<JsonMap>();
historyRequests.add(completer);
if (history != null) return history!(fields);
return completer.future;
}
return <String, dynamic>{};
}
@override
Stream<JsonMap> get frames => _frames.stream;
void emitEvent(JsonMap body) {
_frames.add({'type': 'chat_event', 'chat_event': body});
}
void emitRaw(JsonMap envelope) => _frames.add(envelope);
void close() => _frames.close();
}
JsonMap chatPage(
List<JsonMap> messages, {
String cursor = '',
bool hasMore = false,
}) => {
'chat_history': {
'messages': messages,
'next_cursor': cursor,
'has_more': hasMore,
},
};
JsonMap chatMessage(String id, String role, {List<JsonMap> parts = const []}) =>
{'id': id, 'role': role, 'parts': parts};
JsonMap chatTextFrame(
String text, {
String session = 's',
String messageId = 'a',
}) => {
'session_id': session,
'message_id': messageId,
'kind': 'text',
'part': {'id': 'p', 'type': 'text'},
'delta': text,
};
JsonMap chatStepFrame(String status, {String session = 's'}) => {
'session_id': session,
'kind': 'step',
'step': {'status': status, 'turn_id': 'turn', 'intermediate': false},
};
@@ -0,0 +1,188 @@
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';
void main() {
late FakeChatGateway gateway;
late ChatThreadController controller;
setUp(() {
gateway = FakeChatGateway();
controller = ChatThreadController(gateway, 's');
});
tearDown(() {
controller.dispose();
gateway.close();
});
test('folds own session frames only and keeps live turn activity', () async {
gateway.history = (_) async => chatPage([
chatMessage(
'a',
'assistant',
parts: [
{'type': 'reasoning', 'id': 'r', 'text': 'held'},
],
),
]);
await controller.load();
var notifications = 0;
controller.addListener(() => notifications++);
gateway.emitEvent(chatTextFrame('foreign', session: 'other'));
gateway.emitEvent(chatTextFrame('nodata')..remove('session_id'));
gateway.emitRaw({'type': 'run_event', 'session_id': 's'});
await pumpEventQueue();
expect(notifications, 0);
expect(controller.messages.single['parts'], [
{'type': 'reasoning', 'id': 'r', 'text': 'held'},
]);
expect(controller.running, isFalse);
gateway.emitEvent(chatTextFrame('one'));
gateway.emitEvent(chatTextFrame(' two'));
await pumpEventQueue();
expect(controller.running, isTrue);
expect(controller.messages.single['parts'], [
{'type': 'reasoning', 'id': 'r', 'text': 'held'},
{'type': 'text', 'id': 'p', 'text': 'one two'},
]);
gateway.emitEvent(chatStepFrame('ended'));
await pumpEventQueue();
expect(controller.running, isFalse);
expect(notifications, greaterThan(0));
});
test(
'resync re-subscribes, settles the held turn, and replaces it with the page',
() async {
gateway.history = (_) async => chatPage(
[
chatMessage('stale-user', 'user'),
chatMessage('stale-assistant', 'assistant'),
],
cursor: 'stale-cursor',
hasMore: true,
);
await controller.load();
gateway.emitEvent(chatTextFrame('still running'));
await pumpEventQueue();
expect(controller.running, isTrue);
gateway.onSubscribe = () {
// Settled before the re-attach, then replay proves the fresh turn.
expect(controller.running, isFalse);
gateway.emitEvent(chatStepFrame('started'));
};
gateway.history = (_) async => chatPage(
[
chatMessage('fresh-user', 'user'),
chatMessage('fresh-assistant', 'assistant'),
],
cursor: 'fresh-cursor',
hasMore: false,
);
await controller.resync();
await pumpEventQueue();
expect(
gateway.calls.where((call) => call.type == 'chat_subscribe').length,
2,
);
expect(
gateway.calls.where((call) => call.type == 'chat_messages').length,
2,
);
expect(gateway.calls.last.fields['chat_query'], {
'session_id': 's',
'limit': 200,
'cursor': '',
});
expect(controller.messages.map((item) => item['id']), [
'fresh-user',
'fresh-assistant',
]);
expect(controller.cursor, 'fresh-cursor');
expect(controller.hasMore, isFalse);
expect(controller.running, isTrue);
expect(controller.error, isNull);
},
);
test(
'a failed resync keeps replayed activity and reports the error',
() async {
var attempt = 0;
gateway.history = (_) async {
attempt++;
if (attempt == 1) return chatPage([chatMessage('held', 'user')]);
throw StateError('resync unavailable');
};
await controller.load();
gateway.onSubscribe = () {
gateway.emitEvent(chatStepFrame('started'));
};
await controller.resync();
await pumpEventQueue();
expect(controller.messages.single['id'], 'held');
expect(controller.running, isTrue);
expect(controller.error, contains('resync unavailable'));
expect(controller.loading, isFalse);
},
);
test(
'a resync frame reattaches and replaces the new authoritative page',
() async {
var attempt = 0;
gateway.history = (_) async => attempt++ == 0
? chatPage([chatMessage('held', 'user')], hasMore: true)
: chatPage([chatMessage('fresh', 'assistant')]);
await controller.load();
gateway.emitEvent({'session_id': 's', 'kind': 'resync'});
await pumpEventQueue();
expect(
gateway.calls.where((call) => call.type == 'chat_subscribe').length,
2,
);
expect(controller.messages.single['id'], 'fresh');
expect(controller.hasMore, isFalse);
},
);
test(
'disposal ignores a late reply and never invents an unsubscribe',
() async {
final pending = Completer<JsonMap>();
gateway.history = (_) => pending.future;
var notifications = 0;
controller.addListener(() => notifications++);
final load = controller.load();
await pumpEventQueue();
final before = notifications;
controller.dispose();
pending.complete(chatPage([chatMessage('late', 'user')]));
await load;
expect(notifications, before);
expect(
gateway.calls.where((call) => call.type == 'chat_unsubscribe'),
isEmpty,
);
// Keep tearDown's dispose idempotent.
controller = ChatThreadController(gateway, 's');
},
);
}