merge(app): land reviewed native chat sessions

This commit is contained in:
2026-10-21 17:45:52 +01:00
28 changed files with 3692 additions and 0 deletions
@@ -0,0 +1,316 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/data/chat_repository.dart';
import 'package:pipelines_app/features/chat/domain/chat_sessions.dart';
import 'package:pipelines_app/features/chat/domain/chat_transcript.dart';
class RecordingGateway implements ApiGateway {
final calls = <({String type, JsonMap fields})>[];
JsonMap reply = {};
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add((type: type, fields: fields));
return reply;
}
@override
Stream<JsonMap> get frames => const Stream.empty();
}
void main() {
group('chat domain', () {
test(
'filters/groups in server order and keeps server usage unknowns unavailable',
() {
final sessions = [
{'id': 'a', 'directory': '/work', 'title': 'First'},
{'id': 'b', 'directory': '/else', 'title': 'Second'},
{'id': 'c', 'directory': '/work', 'title': 'Third'},
];
expect(filterChatSessions(sessions, 'ELSE').single['id'], 'b');
expect(groupChatSessions(sessions).map((g) => g.directory), [
'/work',
'/else',
]);
expect(chatSessionActivity(running: true, unseen: true), 'streaming');
expect(
chatUsageSnapshot({
'total_tokens': 3,
'context_window': 'unknown',
})!['context_window'],
isNull,
);
expect(chatUsageSnapshot({'legacy_tokens': 9}), isNull);
},
);
test(
'merges pages by id, retains idless events, replaces authority, and folds parts',
() {
final first = mergeChatHistory({}, {
'messages': [
{
'id': 'a',
'role': 'assistant',
'parts': [
{'type': 'reasoning', 'text': 'think'},
],
},
{
'role': 'assistant',
'parts': [
{'type': 'future_part', 'payload': 4},
],
},
{'id': 'u', 'role': 'user', 'text': 'hello', 'operation_id': 'op'},
],
'nextCursor': 'opaque/1',
'hasMore': true,
});
final older = mergeChatHistory(first, {
'messages': [
{
'id': 'a',
'role': 'assistant',
'parts': [
{'type': 'text', 'text': 'final'},
],
},
],
'nextCursor': '',
'hasMore': false,
}, older: true);
expect(older['nextCursor'], '');
final msgs = older['messages'] as List<JsonMap>;
expect(msgs.map((m) => m['id']), ['a', null, 'u']);
expect(
(transcriptRows(msgs).first['parts'] as List).map((p) => p['type']),
['text', 'future_part'],
);
expect(
reconcileChatUser(msgs, {
'id': 'remote',
'role': 'user',
'operation_id': 'op',
}).where((m) => m['operation_id'] == 'op').length,
1,
);
},
);
test(
'send queue is session-scoped and operation IDs deduplicate retries',
() {
final queue = ChatSendQueue();
final send = QueuedChatSend(
operationId: 'stable',
text: ' prompt ',
files: ['/tmp/a'],
);
expect(queue.enqueue('s1', send), isTrue);
expect(queue.enqueue('s1', send.retry()), isFalse);
expect(queue.enqueue('s2', send.retry()), isTrue);
expect(queue.takeNext('s1')!.operationId, 'stable');
expect(queue.takeNext('s1'), isNull);
expect(queue.forSession('s2').single.files, ['/tmp/a']);
},
);
test(
'live text/reasoning append, tool snapshots merge, and steps settle only activity',
() {
var thread = <String, dynamic>{
'sessionId': 's',
'messages': <JsonMap>[],
};
thread = applyChatEvent(thread, {
'kind': 'text',
'session_id': 's',
'message_id': 'a',
'part': {'id': 'p'},
'delta': 'one',
});
thread = applyChatEvent(thread, {
'kind': 'text',
'session_id': 's',
'message_id': 'a',
'part': {'id': 'p'},
'delta': ' two',
});
thread = applyChatEvent(thread, {
'kind': 'reasoning',
'session_id': 's',
'message_id': 'a',
'part': {'id': 'r'},
'delta': 'hidden',
});
thread = applyChatEvent(thread, {
'kind': 'tool',
'session_id': 's',
'message_id': 'a',
'part': {
'id': 't',
'type': 'tool',
'state': {'input': 'x'},
},
});
thread = applyChatEvent(thread, {
'kind': 'tool',
'session_id': 's',
'message_id': 'a',
'part': {
'id': 't',
'type': 'tool',
'state': {'status': 'completed'},
},
});
final parts =
((thread['messages'] as List).single as JsonMap)['parts']
as List<JsonMap>;
expect(parts[0]['text'], 'one two');
expect(parts[1]['text'], 'hidden');
expect(parts[2]['state'], {'input': 'x', 'status': 'completed'});
expect(thread['running'], true);
thread = applyChatEvent(thread, {
'kind': 'step',
'session_id': 's',
'step': {'status': 'ended', 'turn_id': 'turn'},
});
expect(thread['running'], false);
expect(
applyChatEvent(thread, {'kind': 'text', 'session_id': 'other'}),
same(thread),
);
},
);
});
group('chat wire adapter', () {
late RecordingGateway gateway;
late ChatRepository repo;
setUp(() {
gateway = RecordingGateway();
repo = ChatRepository(gateway);
});
test('uses web envelopes and opaque history cursor', () async {
gateway.reply = {
'chat_history': {
'messages': [
{'id': 'm', 'role': 'user'},
],
'next_cursor': 'opaque',
'has_more': true,
},
};
final page = await repo.history('s', cursor: 'before', limit: 17);
expect(page['nextCursor'], 'opaque');
expect(gateway.calls.last.type, 'chat_messages');
expect(gateway.calls.last.fields, {
'chat_query': {'session_id': 's', 'cursor': 'before', 'limit': 17},
});
await repo.subscribe('s');
expect(gateway.calls.last.fields, {
'chat_subscribe': {'session_id': 's'},
});
});
test(
'sends stable operation id, omits empty files, and builds action envelopes',
() async {
await repo.prompt('s', ' hi ', operationId: 'same');
expect(gateway.calls.last.fields, {
'chat_prompt': {
'session_id': 's',
'text': 'hi',
'operation_id': 'same',
'native_message_id': 'msg_same',
},
});
await repo.answerForm('s', 'f', {'choice': 'yes'}, action: 'submit');
expect(gateway.calls.last.fields, {
'chat_answer': {
'session_id': 's',
'form_id': 'f',
'answers': {'choice': 'yes'},
'action': 'submit',
},
});
await repo.replyPermission('s', 'r', 'once', message: ' approved ');
expect(gateway.calls.last.fields, {
'chat_reply': {
'session_id': 's',
'request_id': 'r',
'decision': 'once',
'client': 'Web',
'message': 'approved',
},
});
await repo.create(title: 'New', directory: '~', operationId: 'create');
expect(gateway.calls.last.fields, {
'chat_create': {
'title': 'New',
'directory': '~',
'operation_id': 'create',
},
});
await repo.selectModel('s', 'provider', 'model');
expect(gateway.calls.last.type, 'chat_model');
},
);
test('rejects invalid permissions and prompts before sending', () async {
expect(
() => repo.prompt(' ', 'hello', operationId: 'x'),
throwsArgumentError,
);
expect(
() => repo.prompt('s', ' ', operationId: 'x'),
throwsArgumentError,
);
expect(
() => repo.replyPermission('s', 'r', 'approve'),
throwsArgumentError,
);
expect(gateway.calls, isEmpty);
});
test(
'uses the server model catalog object and default history limit',
() async {
gateway.reply = {
'chat_models': {
'providers': {
'p': ['m'],
},
},
};
expect((await repo.models('s'))['providers'], {
'p': ['m'],
});
expect(gateway.calls.single.fields, {
'chat_query': {'session_id': 's'},
});
gateway.calls.clear();
await repo.history('s');
expect(gateway.calls.single.fields['chat_query']['limit'], 200);
},
);
test(
'reads exact directory/backend catalog envelopes without inventing fallback',
() async {
gateway.reply = {
'chat_directories': ['~', '/work'],
};
expect(await repo.directories(), ['~', '/work']);
expect(gateway.calls.last.type, 'chat_directories');
expect(gateway.calls.last.fields, isEmpty);
gateway.reply = {
'chat_backends': ['opencode', 'claude'],
};
expect(await repo.backends(), ['opencode', 'claude']);
expect(gateway.calls.last.type, 'chat_backends');
expect(gateway.calls.last.fields, isEmpty);
gateway.reply = {};
await expectLater(repo.directories(), throwsStateError);
await expectLater(repo.backends(), throwsStateError);
},
);
});
}
@@ -0,0 +1,217 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'chat_test_harness.dart';
import 'fake_chat_gateway.dart';
void main() {
testWidgets(
'material create dialog retains the draft through a delayed catalog failure and retry',
(tester) async {
final gateway = FakeChatGateway();
final directories = Completer<JsonMap>();
gateway.directoriesHandler = () => directories.future;
JsonMap? opened;
await pumpMaterialChat(
tester,
gateway,
onOpen: (session) => opened = session,
);
await tester.tap(find.byKey(const Key('chat-new-chat-fab')));
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
expect(find.text('Loading directories…'), findsOneWidget);
await tester.enterText(
find.byKey(const Key('chat-create-name')),
'Draft chat',
);
await tester.enterText(
find.byKey(const Key('chat-create-instructions')),
'Keep me',
);
directories.completeError(
StateError('Server did not return chat directories.'),
);
await tester.pump();
await tester.pump();
expect(
find.textContaining('Unable to load chat options'),
findsOneWidget,
);
expect(find.text('Draft chat'), findsOneWidget);
expect(find.text('Keep me'), findsOneWidget);
gateway.directoriesHandler = () async => {
'chat_directories': ['/work'],
};
await tester.tap(find.text('Retry'));
await tester.pumpAndSettle();
expect(find.textContaining('Unable to load chat options'), findsNothing);
expect(
find.byKey(const Key('chat-create-server-directory')),
findsOneWidget,
);
expect(
find.text('New chats use the server default model.'),
findsOneWidget,
);
await tester.enterText(find.byKey(const Key('chat-create-name')), '');
await tester.tap(find.text('Create'));
await tester.pump();
expect(find.text('Enter a name and server directory.'), findsOneWidget);
expect(gateway.count('chat_create'), 0);
await tester.enterText(
find.byKey(const Key('chat-create-name')),
'Draft chat',
);
await tester.tap(find.text('Create'));
await tester.pumpAndSettle();
final fields =
gateway.lastFields('chat_create')!['chat_create']! as JsonMap;
expect(fields['title'], 'Draft chat');
expect(fields['directory'], '/work');
expect(fields.containsKey('backend'), isFalse);
expect(fields['instructions'], 'Keep me');
expect(fields.containsKey('operation_id'), isTrue);
expect(opened?['id'], 'created');
},
);
testWidgets('Cupertino create dialog keeps the draft when catalogs fail', (
tester,
) async {
final gateway = FakeChatGateway();
gateway.directoriesHandler = () =>
Future.error(StateError('Server did not return chat directories.'));
await pumpCupertinoChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-new-chat')));
await tester.pumpAndSettle();
expect(find.textContaining('Unable to load chat options'), findsOneWidget);
await tester.enterText(
find.byKey(const Key('chat-create-name')),
'Cupertino draft',
);
await tester.enterText(
find.byKey(const Key('chat-create-instructions')),
'Keep me too',
);
expect(find.text('Cupertino draft'), findsOneWidget);
expect(find.text('Keep me too'), findsOneWidget);
gateway.directoriesHandler = () async => {
'chat_directories': ['/work'],
};
await tester.tap(find.text('Retry'));
await tester.pumpAndSettle();
expect(find.textContaining('Unable to load chat options'), findsNothing);
expect(find.text('Cupertino draft'), findsOneWidget);
expect(find.text('Keep me too'), findsOneWidget);
});
testWidgets('material create dialog reports an empty catalog', (
tester,
) async {
final gateway = FakeChatGateway();
gateway.directoriesHandler = () async => {'chat_directories': []};
await pumpMaterialChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-new-chat-fab')));
await tester.pumpAndSettle();
expect(
find.text('The server has no chat directories or backends available.'),
findsOneWidget,
);
});
testWidgets('Cupertino create dialog uses native selectors and fields', (
tester,
) async {
final gateway = FakeChatGateway();
JsonMap? opened;
await pumpCupertinoChat(
tester,
gateway,
onOpen: (session) => opened = session,
);
await tester.tap(find.byKey(const Key('chat-new-chat')));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
expect(find.text('Server directory: /work'), findsOneWidget);
expect(find.text('Backend: opencode'), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-create-backend')));
await tester.pumpAndSettle();
await tester.tap(find.text('codex'));
await tester.pumpAndSettle();
expect(find.text('Backend: codex'), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-create-server-directory')));
await tester.pumpAndSettle();
expect(find.text('/archive'), findsOneWidget);
await tester.tap(find.text('/archive'));
await tester.pumpAndSettle();
expect(find.text('Server directory: /archive'), findsOneWidget);
await tester.enterText(
find.byKey(const Key('chat-create-name')),
'Cupertino draft',
);
await tester.enterText(
find.byKey(const Key('chat-create-instructions')),
'Be careful',
);
await tester.tap(find.text('Create'));
await tester.pumpAndSettle();
final fields =
gateway.lastFields('chat_create')!['chat_create']! as JsonMap;
expect(fields['title'], 'Cupertino draft');
expect(fields['directory'], '/archive');
expect(fields['backend'], 'codex');
expect(fields['instructions'], 'Be careful');
expect(opened?['id'], 'created');
});
testWidgets('a created chat opens before the list refresh completes', (
tester,
) async {
final gateway = FakeChatGateway();
JsonMap? opened;
await pumpMaterialChat(
tester,
gateway,
onOpen: (session) => opened = session,
);
final refresh = Completer<JsonMap>();
gateway.pendingSessions.add(refresh);
await tester.tap(find.byKey(const Key('chat-new-chat-fab')));
await tester.pumpAndSettle();
await tester.tap(find.text('Create'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
expect(gateway.count('chat_create'), 1);
expect(gateway.count('chat_sessions'), 2);
expect(
opened?['id'],
'created',
reason: 'a slow listing must not hold up opening the new chat',
);
refresh.complete({'chat_sessions': []});
await tester.pumpAndSettle();
});
}
@@ -0,0 +1,91 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'chat_test_harness.dart';
import 'fake_chat_gateway.dart';
/// The message card is also mounted under a bare `MaterialApp` (the screen's
/// iOS/macOS path). Without its own style, `Text` inherits MaterialApp's
/// "missing Material" fallback: 48px, red, monospace with a double underline.
void main() {
testWidgets('Cupertino empty message under MaterialApp uses normal text', (
tester,
) async {
usePhoneSurface(tester);
await pumpIosMaterialChat(tester, FakeChatGateway());
expect(find.byType(CupertinoPageScaffold), findsOneWidget);
expect(find.byType(Scaffold), findsNothing);
const message = 'No chat sessions on this server yet.';
expect(find.text(message), findsOneWidget);
expectNormalTextStyle(tester, message);
});
testWidgets('Cupertino no-match message under MaterialApp wraps normally', (
tester,
) async {
usePhoneSurface(tester);
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpIosMaterialChat(tester, gateway);
await tester.enterText(
find.byType(CupertinoSearchTextField),
'zzz-no-match-with-a-long-query',
);
await tester.pumpAndSettle();
const message = 'No chats match "zzz-no-match-with-a-long-query".';
expect(find.text(message), findsOneWidget);
expectNormalTextStyle(tester, message);
expect(
tester.renderObject<RenderBox>(find.text(message)).size.height,
greaterThan(30),
reason: 'the query message must wrap instead of being cut to one line',
);
expect(
find.widgetWithText(CupertinoButton, 'Clear search'),
findsOneWidget,
);
});
testWidgets('Cupertino load error under MaterialApp uses normal text', (
tester,
) async {
usePhoneSurface(tester);
final gateway = FakeChatGateway()
..sessionsHandler = () => Future.error(
StateError(
'server unavailable while listing chat sessions for this operator',
),
);
await pumpIosMaterialChat(tester, gateway);
const message =
'Bad state: server unavailable while listing chat sessions '
'for this operator';
expect(find.text(message), findsOneWidget);
expectNormalTextStyle(tester, message);
expect(find.text('No chat sessions on this server yet.'), findsNothing);
expect(find.widgetWithText(CupertinoButton, 'Retry'), findsOneWidget);
});
}
/// Resolves the style actually painted for [message] and checks it is the
/// ordinary Cupertino body style rather than MaterialApp's fallback style.
void expectNormalTextStyle(WidgetTester tester, String message) {
final paragraph = tester.renderObject<RenderParagraph>(find.text(message));
final style = paragraph.text.style!;
expect(
style.fontSize,
const CupertinoThemeData().textTheme.textStyle.fontSize,
reason: 'message should not use MaterialApp\'s 48px fallback style',
);
expect(style.fontFamily, isNot('monospace'));
expect(style.fontWeight, isNot(FontWeight.w900));
expect(style.decoration, isNot(TextDecoration.underline));
expect(style.color, isNot(const Color(0xD0FF0000)));
}
@@ -0,0 +1,174 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'chat_test_harness.dart';
import 'fake_chat_gateway.dart';
void main() {
testWidgets('material row star, rename, close confirm and reopen', (
tester,
) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpMaterialChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-star-s2')));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_star'), {
'chat_query': {'session_id': 's2', 'starred': true},
});
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Rename…'));
await tester.pumpAndSettle();
await tester.enterText(
find.byKey(const Key('chat-rename-field')),
' Renamed chat ',
);
await tester.tap(find.text('Save'));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_rename'), {
'chat_rename': {'session_id': 's2', 'title': 'Renamed chat'},
});
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Close chat…'));
await tester.pumpAndSettle();
expect(find.text('Close chat?'), findsOneWidget);
await tester.tap(find.text('Cancel'));
await tester.pumpAndSettle();
expect(gateway.count('chat_close'), 0);
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Close chat…'));
await tester.pumpAndSettle();
await tester.tap(find.text('Close chat'));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_close'), {
'chat_query': {'session_id': 's2'},
});
await tester.ensureVisible(find.byKey(const Key('chat-actions-s4')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('chat-actions-s4')));
await tester.pumpAndSettle();
await tester.tap(find.text('Reopen'));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_reopen'), {
'chat_query': {'session_id': 's4'},
});
});
testWidgets('Cupertino close confirmation uses the action sheet flow', (
tester,
) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpCupertinoChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Close chat…'));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
expect(
find.textContaining('marks it closed on every device'),
findsOneWidget,
);
await tester.tap(find.text('Close chat'));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_close'), {
'chat_query': {'session_id': 's2'},
});
});
testWidgets('material rename disables Save while the name is blank', (
tester,
) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpMaterialChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Rename…'));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('chat-rename-field')), ' ');
await tester.pump();
final save = tester.widget<FilledButton>(
find.widgetWithText(FilledButton, 'Save'),
);
expect(save.onPressed, isNull);
expect(gateway.count('chat_rename'), 0);
});
testWidgets('Cupertino rename disables Save while the name is blank', (
tester,
) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpCupertinoChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Rename…'));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('chat-rename-field')), ' ');
await tester.pump();
final save = tester.widget<CupertinoDialogAction>(
find.widgetWithText(CupertinoDialogAction, 'Save'),
);
expect(save.onPressed, isNull);
expect(gateway.count('chat_rename'), 0);
});
testWidgets('material rename helper wraps instead of truncating at 2x', (
tester,
) async {
usePhoneSurface(tester);
tester.platformDispatcher.textScaleFactorTestValue = 2;
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpMaterialChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Rename…'));
await tester.pumpAndSettle();
const helper = 'This name is shared with every device.';
expect(find.text(helper), findsOneWidget);
expect(
tester.widget<Text>(find.text(helper)).maxLines,
2,
reason: 'helperMaxLines defaults to one, which truncates the sentence',
);
expect(tester.takeException(), isNull);
});
testWidgets('opening a row calls onOpen with the server session', (
tester,
) async {
JsonMap? opened;
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpMaterialChat(
tester,
gateway,
onOpen: (session) => opened = session,
);
await tester.tap(find.byKey(const Key('chat-row-s2')));
await tester.pumpAndSettle();
expect(opened?['id'], 's2');
});
}
@@ -0,0 +1,76 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart';
import 'fake_chat_gateway.dart';
void main() {
testWidgets('a stale refresh reply never replaces the latest listing', (
tester,
) async {
final gateway = FakeChatGateway();
final first = Completer<JsonMap>();
final second = Completer<JsonMap>();
gateway.pendingSessions.addAll([first, second]);
await tester.pumpWidget(
MaterialApp(
home: ChatSessionsScreen(gateway: gateway, onOpen: (_) {}),
),
);
await tester.pump();
await tester.tap(find.byKey(const Key('chat-refresh')));
await tester.pump();
expect(gateway.count('chat_sessions'), 2);
second.complete({
'chat_sessions': [
{'id': 'new', 'title': 'Newest chat'},
],
});
await tester.pump();
await tester.pump();
expect(find.text('Newest chat'), findsOneWidget);
first.complete({
'chat_sessions': [
{'id': 'old', 'title': 'Older chat'},
],
});
await tester.pump();
await tester.pump();
expect(find.text('Older chat'), findsNothing);
expect(find.text('Newest chat'), findsOneWidget);
});
testWidgets('a reply completing after dispose changes nothing', (
tester,
) async {
final gateway = FakeChatGateway();
final pending = Completer<JsonMap>();
gateway.pendingSessions.add(pending);
await tester.pumpWidget(
MaterialApp(
home: ChatSessionsScreen(gateway: gateway, onOpen: (_) {}),
),
);
await tester.pump();
await tester.pumpWidget(const MaterialApp(home: SizedBox()));
pending.complete({
'chat_sessions': [
{'id': 'late', 'title': 'Late chat'},
],
});
await tester.pump();
await tester.pump();
expect(tester.takeException(), isNull);
expect(find.text('Late chat'), findsNothing);
});
}
@@ -0,0 +1,213 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'chat_test_harness.dart';
import 'fake_chat_gateway.dart';
void main() {
testWidgets(
'material list keeps closed starred rows once and groups directories once',
(tester) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpMaterialChat(tester, gateway);
expect(find.text('Starred'), findsOneWidget);
expect(find.text('Chats'), findsNWidgets(2));
expect(find.text('Closed'), findsOneWidget);
expect(find.text('Starred chat'), findsOneWidget);
expect(find.text('Starred closed'), findsOneWidget);
expect(find.text('Open chat'), findsOneWidget);
expect(find.byIcon(Icons.folder_outlined), findsNWidgets(4));
expect(find.byType(Scaffold), findsOneWidget);
},
);
testWidgets('material search distinguishes no-match and clears back', (
tester,
) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpMaterialChat(tester, gateway);
await tester.enterText(find.byType(TextField), 'zzz');
await tester.pumpAndSettle();
expect(find.text('No chats match "zzz".'), findsOneWidget);
expect(find.text('Open chat'), findsNothing);
await tester.tap(find.text('Clear search'));
await tester.pumpAndSettle();
expect(find.text('Open chat'), findsOneWidget);
});
testWidgets('material empty server shows the distinct empty message', (
tester,
) async {
final gateway = FakeChatGateway();
await pumpMaterialChat(tester, gateway);
expect(find.text('No chat sessions on this server yet.'), findsOneWidget);
expect(find.textContaining('No chats match'), findsNothing);
});
testWidgets(
'Cupertino app renders standard controls, groups and renames without Material',
(tester) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpCupertinoChat(tester, gateway);
expect(find.byType(CupertinoPageScaffold), findsOneWidget);
expect(find.byType(CupertinoSearchTextField), findsOneWidget);
expect(find.byType(Scaffold), findsNothing);
expect(
tester.getTopLeft(find.byType(CupertinoSearchTextField)).dy,
greaterThanOrEqualTo(
tester.getBottomLeft(find.byType(CupertinoNavigationBar)).dy,
),
);
expect(find.text('Chats · /work'), findsOneWidget);
expect(find.text('Chats · /else'), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-star-s2')));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_star'), {
'chat_query': {'session_id': 's2', 'starred': true},
});
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
expect(find.text('Rename…'), findsOneWidget);
await tester.tap(find.text('Rename…'));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
await tester.enterText(
find.byKey(const Key('chat-rename-field')),
'Renamed on Cupertino',
);
await tester.tap(find.text('Save'));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_rename'), {
'chat_rename': {'session_id': 's2', 'title': 'Renamed on Cupertino'},
});
await tester.tap(find.byKey(const Key('chat-actions-s4')));
await tester.pumpAndSettle();
await tester.tap(find.text('Reopen'));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_reopen'), {
'chat_query': {'session_id': 's4'},
});
},
);
testWidgets(
'Cupertino no-match message wraps and Clear search is its own button',
(tester) async {
usePhoneSurface(tester);
final semantics = tester.ensureSemantics();
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpCupertinoChat(tester, gateway);
const query = 'zzz-no-match-with-a-long-query';
await tester.enterText(find.byType(CupertinoSearchTextField), query);
await tester.pumpAndSettle();
const message = 'No chats match "zzz-no-match-with-a-long-query".';
expect(find.text(message), findsOneWidget);
expect(find.text('Open chat'), findsNothing);
final messageBox = tester.renderObject<RenderBox>(find.text(message));
expect(
messageBox.size.height,
greaterThan(30),
reason: 'the query message must wrap instead of being cut to one line',
);
final clear = find.bySemanticsLabel('Clear search');
expect(clear, findsOneWidget);
expect(tester.getSemantics(clear).label, 'Clear search');
await tester.tap(find.text('Clear search'));
await tester.pumpAndSettle();
expect(find.text('Open chat'), findsOneWidget);
semantics.dispose();
},
);
testWidgets(
'Cupertino load failure wraps the reason and hides the empty message',
(tester) async {
usePhoneSurface(tester);
final gateway = FakeChatGateway()
..sessionsHandler = () => Future.error(
StateError(
'server unavailable while listing chat sessions for this operator',
),
);
await pumpCupertinoChat(tester, gateway);
const message =
'Bad state: server unavailable while listing chat sessions '
'for this operator';
expect(find.text(message), findsOneWidget);
expect(find.text('No chat sessions on this server yet.'), findsNothing);
final messageBox = tester.renderObject<RenderBox>(find.text(message));
expect(
messageBox.size.height,
greaterThan(30),
reason: 'the server reason must wrap instead of being cut to one line',
);
expect(find.widgetWithText(CupertinoButton, 'Retry'), findsOneWidget);
},
);
testWidgets('Cupertino no-match message survives 2x text scaling', (
tester,
) async {
usePhoneSurface(tester);
tester.platformDispatcher.textScaleFactorTestValue = 2;
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpCupertinoChat(tester, gateway);
await tester.enterText(
find.byType(CupertinoSearchTextField),
'zzz-no-match-with-a-long-query',
);
await tester.pumpAndSettle();
expect(
find.text('No chats match "zzz-no-match-with-a-long-query".'),
findsOneWidget,
);
expect(find.text('Clear search'), findsOneWidget);
expect(tester.takeException(), isNull);
});
testWidgets('duplicate Cupertino titles disambiguate the action labels', (
tester,
) async {
final semantics = tester.ensureSemantics();
final gateway = FakeChatGateway()
..sessionsReply = {
'chat_sessions': [
{'id': 'd1', 'title': 'New chat', 'directory': '/work'},
{'id': 'd2', 'title': 'New chat', 'directory': '/work'},
],
};
await pumpCupertinoChat(tester, gateway);
expect(
tester.getSemantics(find.byKey(const Key('chat-actions-d1'))).label,
'Chat actions for New chat (d1)',
);
expect(
tester.getSemantics(find.byKey(const Key('chat-actions-d2'))).label,
'Chat actions for New chat (d2)',
);
semantics.dispose();
});
}
@@ -0,0 +1,77 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart';
import 'fake_chat_gateway.dart';
List<JsonMap> sampleSessions() => [
{'id': 's1', 'title': 'Starred chat', 'directory': '/work', 'starred': true},
{'id': 's2', 'title': 'Open chat', 'directory': '/work'},
{'id': 's3', 'title': 'Elsewhere chat', 'directory': '/else'},
{
'id': 's4',
'title': 'Closed chat',
'directory': '/else',
'closed_at': '2026-01-01',
},
{
'id': 's5',
'title': 'Starred closed',
'directory': '/work',
'starred': true,
'closed_at': '2026-01-02',
},
];
Future<void> pumpMaterialChat(
WidgetTester tester,
FakeChatGateway gateway, {
ValueChanged<JsonMap>? onOpen,
}) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}),
),
);
await tester.pumpAndSettle();
}
Future<void> pumpCupertinoChat(
WidgetTester tester,
FakeChatGateway gateway, {
ValueChanged<JsonMap>? onOpen,
}) async {
await tester.pumpWidget(
CupertinoApp(
home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}),
),
);
await tester.pumpAndSettle();
}
/// The screen's iOS/macOS path: Cupertino controls under the app's ordinary
/// `MaterialApp` root, with no Material or CupertinoTheme ancestor.
Future<void> pumpIosMaterialChat(
WidgetTester tester,
FakeChatGateway gateway, {
ValueChanged<JsonMap>? onOpen,
}) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.iOS),
home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}),
),
);
await tester.pumpAndSettle();
}
/// Narrows the test surface to a phone so long messages must wrap.
void usePhoneSurface(WidgetTester tester) {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
}
@@ -0,0 +1,56 @@
import 'dart:async';
import 'dart:collection';
import 'package:pipelines_app/core/api_gateway.dart';
/// Scripted gateway for session-browser widget tests.
class FakeChatGateway implements ApiGateway {
final calls = <({String type, JsonMap fields})>[];
final pendingSessions = Queue<Completer<JsonMap>>();
JsonMap sessionsReply = const {'chat_sessions': []};
Future<JsonMap> Function()? sessionsHandler;
JsonMap createReply = const {
'chat_session': {'id': 'created', 'title': 'New chat'},
};
Future<JsonMap> Function()? directoriesHandler;
Future<JsonMap> Function()? backendsHandler;
@override
Stream<JsonMap> get frames => const Stream.empty();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
calls.add((type: type, fields: fields));
switch (type) {
case 'chat_sessions':
if (pendingSessions.isNotEmpty) {
return pendingSessions.removeFirst().future;
}
if (sessionsHandler != null) return sessionsHandler!();
return Future.value(sessionsReply);
case 'chat_directories':
return directoriesHandler?.call() ??
Future.value(const {
'chat_directories': ['/work', '/archive'],
});
case 'chat_backends':
return backendsHandler?.call() ??
Future.value(const {
'chat_backends': ['opencode', 'codex'],
});
case 'chat_create':
return Future.value(createReply);
default:
return Future.value(const {});
}
}
int count(String type) => calls.where((call) => call.type == type).length;
JsonMap? lastFields(String type) {
for (final call in calls.reversed) {
if (call.type == type) return call.fields;
}
return null;
}
}