Show a reopened chat's last transcript while it refreshes
ChatScreen keeps a bounded in-memory cache of recently left transcripts (16 chats / 4000 messages, LRU). A reopened chat is seeded from it with no loading state, still re-subscribes and re-reads, and the newest page replaces the cached copy while live frames received during the read are kept. /close removes the entry; only transcripts backed by a successful read on the current connection are written. Adds tool/chat_reopen_probe.mjs and an optional history delay in the loopback fixture. Measurement shows a second cost the cache does not remove: opening at the end of the top-anchored transcript lays out every row (notes).
This commit is contained in:
@@ -0,0 +1,171 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/screen.dart';
|
||||
import 'package:pipelines_app/shell/adaptive_shell.dart';
|
||||
import 'package:pipelines_app/shell/destination.dart';
|
||||
|
||||
import '../../native_back.dart';
|
||||
import 'conversation/chat_thread_fixtures.dart';
|
||||
|
||||
class _Gateway extends FakeChatGateway {
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
|
||||
if (type == 'chat_sessions') {
|
||||
return Future.value({
|
||||
'chat_sessions': [
|
||||
{'id': 'a', 'title': 'First chat'},
|
||||
{'id': 'b', 'title': 'Second chat'},
|
||||
],
|
||||
});
|
||||
}
|
||||
if (type == 'chat_shells') return Future.value({'chat_shells': []});
|
||||
return super.call(type, fields);
|
||||
}
|
||||
|
||||
int get historyReads =>
|
||||
calls.where((call) => call.type == 'chat_messages').length;
|
||||
}
|
||||
|
||||
JsonMap _user(String id, String text) => chatMessage(
|
||||
id,
|
||||
'user',
|
||||
parts: [
|
||||
{'type': 'text', 'text': text},
|
||||
],
|
||||
);
|
||||
|
||||
/// A few frames, without settling: the phone pushes its page after a frame,
|
||||
/// and a pending read's indicator would never settle.
|
||||
Future<void> _frames(WidgetTester tester) async {
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
}
|
||||
|
||||
Finder _shows(String text) => find.textContaining(text, findRichText: true);
|
||||
|
||||
Future<_Gateway> _pumpShell(WidgetTester tester, Size size) async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
tester.view.physicalSize = size;
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
final gateway = _Gateway();
|
||||
addTearDown(gateway.close);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: AdaptiveShell(
|
||||
destination: AppDestination.chat,
|
||||
destinationBodies: {
|
||||
AppDestination.chat: (_) => ChatScreen(gateway: gateway),
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
return gateway;
|
||||
}
|
||||
|
||||
void main() {
|
||||
for (final (label, size) in [
|
||||
('phone page', const Size(390, 844)),
|
||||
('wide pane', const Size(1280, 800)),
|
||||
]) {
|
||||
testWidgets('a reopened chat shows its last transcript at once and '
|
||||
'refreshes it from the server ($label)', (tester) async {
|
||||
final gateway = await _pumpShell(tester, size);
|
||||
final phone = size.width < 600;
|
||||
|
||||
Future<void> leave() async {
|
||||
if (phone) {
|
||||
await tester.tap(findNativeBack());
|
||||
} else {
|
||||
gateway.history = (_) async => chatPage(const []);
|
||||
await tester.tap(_shows('Second chat').first);
|
||||
}
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const ValueKey('chat-thread-a')), findsNothing);
|
||||
gateway.history = null;
|
||||
}
|
||||
|
||||
// First visit: nothing is cached, so the read is awaited.
|
||||
await tester.tap(_shows('First chat').first);
|
||||
await _frames(tester);
|
||||
expect(find.byKey(const Key('chat-thread-loading')), findsOneWidget);
|
||||
gateway.historyRequests.last.complete(
|
||||
chatPage([_user('u1', 'Earlier question'), _user('gone', 'Removed')]),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(_shows('Earlier question'), findsOneWidget);
|
||||
await leave();
|
||||
|
||||
// Reopen: the cached transcript is drawn before the read replies, and
|
||||
// the conversation still re-subscribes and re-reads.
|
||||
final reads = gateway.historyReads;
|
||||
final subscribes = gateway.calls
|
||||
.where((call) => call.type == 'chat_subscribe')
|
||||
.length;
|
||||
await tester.tap(_shows('First chat').first);
|
||||
await _frames(tester);
|
||||
expect(find.byKey(const ValueKey('chat-thread-a')), findsOneWidget);
|
||||
expect(find.byKey(const Key('chat-thread-loading')), findsNothing);
|
||||
expect(_shows('Earlier question'), findsOneWidget);
|
||||
expect(_shows('Removed'), findsOneWidget);
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.historyReads, reads + 1);
|
||||
expect(
|
||||
gateway.calls.where((call) => call.type == 'chat_subscribe').length,
|
||||
subscribes + 1,
|
||||
);
|
||||
|
||||
// A live frame during the read is kept through the reply.
|
||||
gateway.emitEvent(
|
||||
chatTextFrame('Live reply while reopening', session: 'a'),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(_shows('Live reply while reopening'), findsOneWidget);
|
||||
|
||||
// The server's reply replaces the cached copy: a message it no longer
|
||||
// holds leaves, a new one arrives, the live frame stays.
|
||||
gateway.historyRequests.last.complete(
|
||||
chatPage([
|
||||
_user('u1', 'Earlier question'),
|
||||
_user('u2', 'Sent from another client'),
|
||||
]),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(_shows('Removed'), findsNothing);
|
||||
expect(_shows('Sent from another client'), findsOneWidget);
|
||||
expect(_shows('Live reply while reopening'), findsOneWidget);
|
||||
|
||||
// The refreshed transcript is what the next visit opens on.
|
||||
await leave();
|
||||
await tester.tap(_shows('First chat').first);
|
||||
await _frames(tester);
|
||||
expect(find.byKey(const Key('chat-thread-loading')), findsNothing);
|
||||
expect(_shows('Sent from another client'), findsOneWidget);
|
||||
expect(_shows('Removed'), findsNothing);
|
||||
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
});
|
||||
}
|
||||
|
||||
testWidgets('a chat whose read failed is not cached for the next visit', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = await _pumpShell(tester, const Size(390, 844));
|
||||
gateway.history = (_) async => throw StateError('refused');
|
||||
await tester.tap(_shows('First chat').first);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(findNativeBack());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
gateway.history = null;
|
||||
await tester.tap(_shows('First chat').first);
|
||||
await _frames(tester);
|
||||
expect(find.byKey(const Key('chat-thread-loading')), findsOneWidget);
|
||||
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
});
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/core/transport/connection_state.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_transcript_cache.dart';
|
||||
|
||||
import 'chat_composer_bar_fixtures.dart';
|
||||
|
||||
@@ -50,7 +51,11 @@ void main() {
|
||||
closed = 0;
|
||||
});
|
||||
|
||||
Future<void> pump(WidgetTester tester, {String directory = '/w'}) async {
|
||||
Future<void> pump(
|
||||
WidgetTester tester, {
|
||||
String directory = '/w',
|
||||
ChatTranscriptCache? transcripts,
|
||||
}) async {
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChatThreadView(
|
||||
@@ -60,6 +65,7 @@ void main() {
|
||||
session: {'id': 's', 'title': 'Old', 'directory': directory},
|
||||
onBack: () {},
|
||||
drafts: MemoryChatDraftStore(),
|
||||
transcripts: transcripts,
|
||||
newOperationId: () => 'op-1',
|
||||
onCreatedSession: (session, notice) {
|
||||
created = session;
|
||||
@@ -159,4 +165,22 @@ void main() {
|
||||
expect(closed, 1);
|
||||
expect(find.text('chat is locked'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('/close forgets the cached transcript, also after leaving', (
|
||||
tester,
|
||||
) async {
|
||||
final transcripts = ChatTranscriptCache()
|
||||
..write('s', ChatTranscriptSnapshot(messages: const []))
|
||||
..write('other', ChatTranscriptSnapshot(messages: const []));
|
||||
await pump(tester, transcripts: transcripts);
|
||||
await run(tester, '/close');
|
||||
await tester.tap(find.text('Close chat'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(closed, 1);
|
||||
expect(transcripts.sessionIds, ['other']);
|
||||
|
||||
// Leaving the closed conversation does not write it back.
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
expect(transcripts.sessionIds, ['other']);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_scroll.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_transcript_cache.dart';
|
||||
|
||||
import 'chat_thread_fixtures.dart';
|
||||
|
||||
@@ -211,6 +212,51 @@ void main() {
|
||||
expect(find.byKey(const Key('chat-jump-to-latest')), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a cached reopen restores the position before the read replies', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = FakeChatGateway();
|
||||
addTearDown(gateway.close);
|
||||
gateway.history = (_) async => tallPage();
|
||||
final positions = MemoryChatScrollStore();
|
||||
final transcripts = ChatTranscriptCache();
|
||||
Widget thread() => host(
|
||||
ChatThreadView(
|
||||
gateway: gateway,
|
||||
sessionId: 's',
|
||||
scrollPositions: positions,
|
||||
transcripts: transcripts,
|
||||
onBack: () {},
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pumpWidget(thread());
|
||||
await tester.pumpAndSettle();
|
||||
await tester.drag(
|
||||
find.byKey(const Key('chat-thread-s')),
|
||||
const Offset(0, 360),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final saved = transcriptScroll(tester).position.pixels;
|
||||
await tester.pumpWidget(host(const SizedBox()));
|
||||
expect(transcripts.sessionIds, ['s']);
|
||||
|
||||
// The reopened read stays pending: the position is restored on the
|
||||
// cached transcript alone.
|
||||
gateway.history = null;
|
||||
await tester.pumpWidget(thread());
|
||||
await tester.pumpAndSettle();
|
||||
final reopened = transcriptScroll(tester);
|
||||
expect(find.byKey(const Key('chat-thread-loading')), findsNothing);
|
||||
expect(reopened.position.pixels, closeTo(saved, 1));
|
||||
expect(find.byKey(const Key('chat-jump-to-latest')), findsOneWidget);
|
||||
|
||||
// The same transcript from the server keeps the operator's position.
|
||||
gateway.historyRequests.last.complete(tallPage());
|
||||
await tester.pumpAndSettle();
|
||||
expect(reopened.position.pixels, closeTo(saved, 1));
|
||||
});
|
||||
|
||||
testWidgets('a conversation that fits its viewport offers no control', (
|
||||
tester,
|
||||
) async {
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
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 'package:pipelines_app/features/chat/conversation/chat_transcript_cache.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_transcript.dart';
|
||||
|
||||
import 'chat_thread_fixtures.dart';
|
||||
|
||||
JsonMap _text(String id, String role, String text) => chatMessage(
|
||||
id,
|
||||
role,
|
||||
parts: [
|
||||
{'type': 'text', 'id': 'p-$id', 'text': text},
|
||||
],
|
||||
);
|
||||
|
||||
ChatTranscriptSnapshot _snapshot(int count, {String prefix = 'm'}) =>
|
||||
ChatTranscriptSnapshot(
|
||||
messages: [
|
||||
for (var i = 0; i < count; i++) chatMessage('$prefix$i', 'user'),
|
||||
],
|
||||
);
|
||||
|
||||
List<Object?> _ids(List<JsonMap> messages) => [
|
||||
for (final message in messages) message['id'],
|
||||
];
|
||||
|
||||
void main() {
|
||||
group('ChatTranscriptCache', () {
|
||||
test('keeps the most recently used sessions within the session bound', () {
|
||||
final cache = ChatTranscriptCache(maxSessions: 3, maxMessages: 100);
|
||||
for (final id in ['a', 'b', 'c']) {
|
||||
cache.write(id, _snapshot(1));
|
||||
}
|
||||
// Reading marks a conversation recently used, so it outlives b.
|
||||
expect(cache.read('a'), isNotNull);
|
||||
cache.write('d', _snapshot(1));
|
||||
|
||||
expect(cache.sessionIds, ['c', 'a', 'd']);
|
||||
expect(cache.read('b'), isNull);
|
||||
});
|
||||
|
||||
test('evicts the least recently used until the message bound holds', () {
|
||||
final cache = ChatTranscriptCache(maxSessions: 10, maxMessages: 10);
|
||||
cache.write('a', _snapshot(4));
|
||||
cache.write('b', _snapshot(4));
|
||||
cache.write('c', _snapshot(4));
|
||||
|
||||
expect(cache.sessionIds, ['b', 'c']);
|
||||
expect(cache.messageCount, 8);
|
||||
|
||||
// Rewriting one conversation replaces its count instead of adding to it.
|
||||
cache.write('b', _snapshot(2));
|
||||
expect(cache.messageCount, 6);
|
||||
expect(cache.sessionIds, ['c', 'b']);
|
||||
});
|
||||
|
||||
test('never keeps a transcript larger than the whole bound', () {
|
||||
final cache = ChatTranscriptCache(maxSessions: 10, maxMessages: 10);
|
||||
cache.write('a', _snapshot(3));
|
||||
cache.write('a', _snapshot(11));
|
||||
|
||||
expect(cache.read('a'), isNull);
|
||||
expect(cache.messageCount, 0);
|
||||
});
|
||||
|
||||
test('remove and clear forget transcripts and their counts', () {
|
||||
final cache = ChatTranscriptCache();
|
||||
cache.write('a', _snapshot(2));
|
||||
cache.write('b', _snapshot(3));
|
||||
cache.remove('a');
|
||||
expect(cache.sessionIds, ['b']);
|
||||
expect(cache.messageCount, 3);
|
||||
cache.clear();
|
||||
expect(cache.sessionIds, isEmpty);
|
||||
expect(cache.messageCount, 0);
|
||||
});
|
||||
});
|
||||
|
||||
test('refreshCachedChatHistory lets the page decide and keeps live '
|
||||
'arrivals', () {
|
||||
final held = [
|
||||
_text('gone', 'user', 'deleted on the server'),
|
||||
_text('u1', 'user', 'cached question'),
|
||||
_text('a1', 'assistant', 'cached stale answer'),
|
||||
_text('live', 'assistant', 'arrived after reopening'),
|
||||
];
|
||||
final page = {
|
||||
'messages': [
|
||||
_text('u1', 'user', 'cached question'),
|
||||
_text('a1', 'assistant', 'authoritative answer'),
|
||||
_text('u2', 'user', 'sent from another client'),
|
||||
],
|
||||
'nextCursor': 'next',
|
||||
'hasMore': true,
|
||||
};
|
||||
|
||||
final merged = refreshCachedChatHistory(held, page, {'gone', 'u1', 'a1'});
|
||||
|
||||
expect(_ids(merged['messages'] as List<JsonMap>), [
|
||||
'u1',
|
||||
'a1',
|
||||
'u2',
|
||||
'live',
|
||||
]);
|
||||
expect(
|
||||
((merged['messages'] as List<JsonMap>)[1]['parts'] as List)
|
||||
.single['text'],
|
||||
'authoritative answer',
|
||||
);
|
||||
expect(merged['nextCursor'], 'next');
|
||||
expect(merged['hasMore'], isTrue);
|
||||
});
|
||||
|
||||
group('a controller reopened on a cached transcript', () {
|
||||
late FakeChatGateway gateway;
|
||||
late ChatThreadController controller;
|
||||
final cached = ChatTranscriptSnapshot(
|
||||
messages: [
|
||||
_text('u1', 'user', 'question'),
|
||||
_text('a', 'assistant', 'cached answer'),
|
||||
],
|
||||
cursor: 'cached-cursor',
|
||||
hasMore: true,
|
||||
);
|
||||
|
||||
setUp(() {
|
||||
gateway = FakeChatGateway();
|
||||
controller = ChatThreadController(gateway, 's', cached: cached);
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
controller.dispose();
|
||||
gateway.close();
|
||||
});
|
||||
|
||||
test('shows the cached transcript before the read, then re-subscribes '
|
||||
'and lets the newest page replace it', () async {
|
||||
expect(controller.loaded, isTrue);
|
||||
expect(controller.showingCached, isTrue);
|
||||
expect(_ids(controller.messages), ['u1', 'a']);
|
||||
// A cached transcript is not backed by a read on this connection.
|
||||
expect(controller.snapshot, isNull);
|
||||
|
||||
final load = controller.load();
|
||||
await pumpEventQueue();
|
||||
expect(gateway.calls.map((call) => call.type), [
|
||||
'chat_subscribe',
|
||||
'chat_messages',
|
||||
]);
|
||||
expect(controller.loading, isTrue);
|
||||
expect(_ids(controller.messages), ['u1', 'a']);
|
||||
|
||||
gateway.historyRequests.single.complete(
|
||||
chatPage([
|
||||
_text('a', 'assistant', 'fresh answer'),
|
||||
_text('u2', 'user', 'newer question'),
|
||||
]),
|
||||
);
|
||||
await load;
|
||||
|
||||
expect(controller.showingCached, isFalse);
|
||||
expect(controller.loading, isFalse);
|
||||
expect(_ids(controller.messages), ['a', 'u2']);
|
||||
expect(
|
||||
(controller.messages.first['parts'] as List).single['text'],
|
||||
'fresh answer',
|
||||
);
|
||||
expect(controller.cursor, '');
|
||||
expect(controller.hasMore, isFalse);
|
||||
expect(_ids(controller.snapshot!.messages), ['a', 'u2']);
|
||||
});
|
||||
|
||||
test('keeps a live frame that arrives while the read is pending', () async {
|
||||
final load = controller.load();
|
||||
await pumpEventQueue();
|
||||
gateway.emitEvent(chatTextFrame('streamed reply', messageId: 'live'));
|
||||
await pumpEventQueue();
|
||||
expect(_ids(controller.messages), ['u1', 'a', 'live']);
|
||||
|
||||
gateway.historyRequests.single.complete(
|
||||
chatPage([
|
||||
_text('u1', 'user', 'question'),
|
||||
_text('a', 'assistant', 'cached answer'),
|
||||
]),
|
||||
);
|
||||
await load;
|
||||
|
||||
expect(_ids(controller.messages), ['u1', 'a', 'live']);
|
||||
expect(
|
||||
(controller.messages.last['parts'] as List).single['text'],
|
||||
'streamed reply',
|
||||
);
|
||||
expect(controller.running, isTrue);
|
||||
});
|
||||
|
||||
test('a refused read keeps the cached transcript with its error and '
|
||||
'offers nothing to cache', () async {
|
||||
gateway.history = (_) async => throw StateError('offline');
|
||||
await controller.load();
|
||||
|
||||
expect(controller.error, contains('offline'));
|
||||
expect(_ids(controller.messages), ['u1', 'a']);
|
||||
expect(controller.snapshot, isNull);
|
||||
});
|
||||
|
||||
test('a socket gap withdraws the snapshot until the repair read', () async {
|
||||
gateway.history = (_) async => chatPage([_text('a', 'assistant', 'x')]);
|
||||
await controller.load();
|
||||
expect(controller.snapshot, isNotNull);
|
||||
|
||||
final repaired = Completer<JsonMap>();
|
||||
gateway.history = (_) => repaired.future;
|
||||
final resync = controller.resync();
|
||||
await pumpEventQueue();
|
||||
expect(controller.snapshot, isNull);
|
||||
|
||||
repaired.complete(chatPage([_text('a', 'assistant', 'y')]));
|
||||
await resync;
|
||||
expect(controller.snapshot, isNotNull);
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user