Merge: search finds chats and opens them

This commit is contained in:
2026-11-03 13:02:16 +00:00
31 changed files with 1659 additions and 118 deletions
@@ -0,0 +1,131 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import 'package:pipelines_app/features/chat/screen.dart';
import 'package:pipelines_app/features/search/search_screen.dart';
import '../core/transport/pipelines_client_test.dart' show FakeChannel;
import 'search_wiring_test.dart'
show pumpApp, reply, replyRunList, tapTab, waitForSearch;
const _session = 'ses_chatsearch1';
Map<String, dynamic> _results(String kind, List<Map<String, dynamic>> hits) => {
'type': 'search_results',
'search_results': {
'query': 'flaky',
'kind': kind,
'results': hits,
'truncated': false,
'scanned_steps': 0,
'scanned_bytes': 0,
'cap': 50,
'scan_bound_bytes': 1 << 20,
},
};
/// The whole path from the Search tab: a typed query, the run search and the
/// chat search the app sends after it, then a tap on the chat hit opens that
/// chat in the Chat tab with its session selected.
void main() {
for (final cupertino in [false, true]) {
testWidgets('${cupertino ? 'Cupertino' : 'Material'}: a chat hit opens '
'its chat in the Chat tab', (tester) async {
tester.view.physicalSize = const Size(900, 1000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final channel = FakeChannel()..readyCompleter.complete();
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/runs')),
);
addTearDown(provider.dispose);
await pumpApp(
tester,
channel: channel,
client: PipelinesClient(channelFactory: (_) => channel),
provider: provider,
cupertino: cupertino,
);
await replyRunList(tester, channel);
await tapTab(tester, 'Search');
await tester.pump();
await tester.pump(const Duration(milliseconds: 600));
await tester.pump(const Duration(milliseconds: 100));
await tester.enterText(
find.byKey(const ValueKey('search.field')),
'flaky',
);
await tester.pump(const Duration(milliseconds: 300));
final runs = await waitForSearch(tester, channel);
channel.incoming.add(jsonEncode({'id': runs['id'], ..._results('', [])}));
await tester.pump();
await tester.pump();
final chats = await waitForSearch(tester, channel, chats: true);
expect(chats['search'], {'query': 'flaky', 'kind': 'chat', 'limit': 0});
channel.incoming.add(
jsonEncode({
'id': chats['id'],
..._results('chat', [
{
'kind': 'chat',
'target': 'chat:$_session',
'score': 1,
'matched_field': 'message',
'chat': {
'session_id': _session,
'title': 'Fix CI',
'directory': '/work/api',
'backend': 'claude',
'message_id': 'm2',
'snippet': 'the flaky retry loop',
},
},
]),
}),
);
await tester.pump();
await tester.pump();
expect(find.text('Chats (1)'), findsOneWidget);
expect(find.textContaining('the flaky retry loop'), findsOneWidget);
await tester.tap(
find.byKey(const ValueKey('search.result.chat:$_session')),
);
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
await tester.pump(const Duration(milliseconds: 400));
expect(provider.value.uri.path, '/chat/$_session');
expect(find.byType(SearchScreen), findsNothing);
final screen = tester.widget<ChatScreen>(find.byType(ChatScreen));
expect(screen.initialSessionId, _session);
await reply(
tester,
channel,
'chat_sessions',
body: {
'type': 'chat_sessions',
'chat_sessions': [
{
'id': _session,
'title': 'Fix CI',
'directory': '/work/api',
'backend': 'claude',
},
],
},
);
await tester.pump(const Duration(milliseconds: 400));
expect(find.text('Fix CI'), findsWidgets);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
});
}
}
+67 -10
View File
@@ -50,6 +50,63 @@ Future<Map<String, dynamic>> waitForRequest(
fail('Timed out waiting for $type #$index');
}
/// The search requests the app sent: the run/artifact searches, or with
/// [chats] the `kind: chat` searches it sends after each of them.
List<Map<String, dynamic>> searchRequestsOf(
FakeChannel channel, {
bool chats = false,
}) => requestsOf(channel, 'search')
.where(
(request) => ((request['search'] as Map?)?['kind'] == 'chat') == chats,
)
.toList();
Future<Map<String, dynamic>> waitForSearch(
WidgetTester tester,
FakeChannel channel, {
int index = 0,
bool chats = false,
}) async {
for (var attempt = 0; attempt < 80; attempt++) {
final requests = searchRequestsOf(channel, chats: chats);
if (index < requests.length) return requests[index];
await tester.pump(const Duration(milliseconds: 5));
}
fail('Timed out waiting for ${chats ? 'chat ' : ''}search #$index');
}
/// Answers the [index]th chat search (sent after each run search's reply)
/// with no chats, so the app's serialized requests continue.
Future<void> replyChatSearch(
WidgetTester tester,
FakeChannel channel, {
int index = 0,
}) async {
final request = await waitForSearch(
tester,
channel,
index: index,
chats: true,
);
channel.incoming.add(
jsonEncode({
'id': request['id'],
'type': 'search_results',
'search_results': {
'query': (request['search'] as Map)['query'],
'kind': 'chat',
'results': <JsonMap>[],
'cap': 50,
'scanned_steps': 0,
'scanned_bytes': 0,
'scan_bound_bytes': 1 << 20,
},
}),
);
await tester.pump();
await tester.pump();
}
Future<void> reply(
WidgetTester tester,
FakeChannel channel,
@@ -106,7 +163,7 @@ Future<void> searchArtifactHit(
await tester.pump(const Duration(milliseconds: 100));
await tester.enterText(find.byKey(const ValueKey('search.field')), 'report');
await tester.pump(const Duration(milliseconds: 300));
final request = await waitForRequest(tester, channel, 'search', index: index);
final request = await waitForSearch(tester, channel, index: index);
channel.incoming.add(
jsonEncode({
'id': request['id'],
@@ -125,6 +182,7 @@ Future<void> searchArtifactHit(
);
await tester.pump();
await tester.pump();
await replyChatSearch(tester, channel, index: index);
}
/// Selects the artifact hit, leaving run 7's `get_run` request unanswered.
@@ -401,7 +459,7 @@ void main() {
);
await tester.pump(const Duration(milliseconds: 300));
final request = await waitForRequest(tester, channel, 'search');
final request = await waitForSearch(tester, channel);
expect(request['search'], {'query': 'release', 'kind': '', 'limit': 0});
channel.incoming.add(
jsonEncode({
@@ -421,6 +479,7 @@ void main() {
);
await tester.pump();
await tester.pump();
await replyChatSearch(tester, channel);
expect(find.text('Run 7 · Preserved run'), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('search.result.run:7')));
@@ -437,7 +496,8 @@ void main() {
expect(find.text('Run 7'), findsWidgets);
// One app socket carried the search and the run reads.
expect(sockets, 1);
expect(requestsOf(channel, 'search'), hasLength(1));
expect(searchRequestsOf(channel), hasLength(1));
expect(searchRequestsOf(channel, chats: true), hasLength(1));
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
@@ -480,12 +540,7 @@ void main() {
await tester.pump(const Duration(milliseconds: 100));
await tester.enterText(find.byKey(const ValueKey('search.field')), query);
await tester.pump(const Duration(milliseconds: 300));
final request = await waitForRequest(
tester,
channel,
'search',
index: index,
);
final request = await waitForSearch(tester, channel, index: index);
channel.incoming.add(
jsonEncode({
'id': request['id'],
@@ -504,6 +559,7 @@ void main() {
);
await tester.pump();
await tester.pump();
await replyChatSearch(tester, channel, index: index);
}
// An artifact hit opens the run's Artifacts tab and that artifact's viewer.
@@ -592,7 +648,7 @@ void main() {
'report',
);
await tester.pump(const Duration(milliseconds: 300));
final request = await waitForRequest(tester, channel, 'search');
final request = await waitForSearch(tester, channel);
channel.incoming.add(
jsonEncode({
'id': request['id'],
@@ -611,6 +667,7 @@ void main() {
);
await tester.pump();
await tester.pump();
await replyChatSearch(tester, channel);
await tester.tap(
find.byKey(const ValueKey('search.result./artifacts/7/2/report.txt')),
@@ -0,0 +1,160 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/search/domain/search_chat_slice.dart';
import 'package:pipelines_app/features/search/domain/search_controller.dart';
import 'package:pipelines_app/features/search/domain/search_models.dart';
import 'search_test_support.dart';
const runHit = {
'kind': 'run',
'target': 'run:7',
'run': {'id': 7},
};
void main() {
test('an all-kind search sends the run search, then chats as their own '
'request, and shows runs before chats answer', () async {
final gateway = QueuedGateway(holdChats: true);
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('flaky');
await pumpEventQueue();
expect(gateway.lastSearch, {'query': 'flaky', 'kind': '', 'limit': 0});
expect(gateway.chatCalls.single['search'], {
'query': 'flaky',
'kind': 'chat',
'limit': 0,
});
gateway.succeed(0, envelope([runHit]));
await pumpEventQueue();
expect(controller.shownResults.single['target'], 'run:7');
expect(controller.bodyKind, SearchBodyKind.results);
expect(controller.shownChats, isEmpty);
expect(controller.showsChatSection, isFalse);
gateway.chatPending.single.complete(
envelope([
chatHit('ses_a', snippet: 'the flaky retry'),
// A non-chat row in a chat reply is not a chat.
runHit,
]),
);
await pumpEventQueue();
expect(controller.shownChats.single['target'], 'chat:ses_a');
expect(controller.showsChatSection, isTrue);
expect(controller.shownResults.single['target'], 'run:7');
expect(controller.chatsNote, isNull);
});
test('chat hits alone keep the body out of its empty state', () async {
final gateway = QueuedGateway(holdChats: true);
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('fix');
await pumpEventQueue();
gateway.succeed(0, envelope(const []));
await pumpEventQueue();
// Runs answered empty while chats still load: still searching.
expect(controller.bodyKind, SearchBodyKind.searching);
expect(controller.emptyMessage, isNull);
gateway.chatPending.single.complete(envelope([chatHit('ses_a')]));
await pumpEventQueue();
expect(controller.bodyKind, SearchBodyKind.results);
expect(controller.emptyMessage, isNull);
});
test(
'a narrowed kind sends no chat search; Chats alone sends only chats',
() async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('t:run flaky');
await pumpEventQueue();
expect(gateway.calls, hasLength(1));
expect(gateway.chatCalls, isEmpty);
controller.selectKind(SearchKind.chat);
await pumpEventQueue();
expect(gateway.calls, hasLength(1));
expect(gateway.chatCalls.single['search'], {
'query': 'flaky',
'kind': 'chat',
'limit': 0,
});
expect(controller.shownResults, isEmpty);
expect(controller.showsChatSection, isFalse);
},
);
test('a stale chat reply never replaces the newest query', () async {
final gateway = QueuedGateway(holdChats: true);
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('first');
await pumpEventQueue();
controller.updateQuery('second');
await pumpEventQueue();
expect(gateway.chatCalls, hasLength(2));
gateway.chatPending[0].complete(envelope([chatHit('ses_old')]));
await pumpEventQueue();
expect(controller.shownChats, isEmpty);
gateway.chatPending[1].complete(envelope([chatHit('ses_new')]));
await pumpEventQueue();
expect(controller.shownChats.single['target'], 'chat:ses_new');
});
test('a server without chat search says so beside its run results, and '
'is the error with Chats selected', () async {
final gateway = QueuedGateway(holdChats: true);
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('flaky');
await pumpEventQueue();
gateway.succeed(0, envelope([runHit]));
gateway.chatPending.single.completeError(
StateError(
'unknown search kind "chat"; use one of pipeline, version, run, '
'step, field, artifact',
),
);
await pumpEventQueue();
expect(controller.error, isNull);
expect(controller.shownResults, hasLength(1));
expect(controller.chatsNote, unsupportedChatSearchCopy);
expect(controller.showsChatSection, isTrue);
controller.selectKind(SearchKind.chat);
await pumpEventQueue();
gateway.chatPending.last.completeError(
StateError('unknown search kind "chat"'),
);
await pumpEventQueue();
expect(controller.error, unsupportedChatSearchCopy);
expect(controller.bodyKind, SearchBodyKind.error);
});
test('a truncated chat reply carries a bounds note', () async {
final gateway = QueuedGateway(holdChats: true);
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('flaky');
await pumpEventQueue();
gateway.succeed(0, envelope(const []));
gateway.chatPending.single.complete(
envelope([chatHit('ses_a')], truncated: true),
);
await pumpEventQueue();
expect(controller.chatsNote, contains('not searched'));
});
}
@@ -0,0 +1,73 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/search/domain/search_row.dart';
import 'package:pipelines_app/features/search/domain/search_target.dart';
import 'search_test_support.dart' show chatHit;
void main() {
test('a message hit shows the title, harness and directory and its '
'snippet with the match split out', () {
final row = searchRowView(
chatHit('ses_a', snippet: 'the FLAKY retry'),
'flaky',
);
expect(row.title, 'Fix CI');
expect(row.kindLabel, 'Chat');
expect(row.secondary, 'Claude Code · /work/api');
expect(row.snippet, 'the FLAKY retry');
expect(row.snippetSpans.map((span) => (span.text, span.matched)), [
('the ', false),
('FLAKY', true),
(' retry', false),
]);
expect(row.target, 'chat:ses_a');
expect(row.openable, isTrue);
});
test('a title hit has no snippet; closed and untitled chats say so', () {
final base = chatHit('ses_b', title: ' ');
final hit = {
...base,
'chat': <String, dynamic>{
...(base['chat'] as Map),
'backend': '',
'closed': true,
},
};
final row = searchRowView(hit, 'x');
expect(row.title, 'Untitled chat');
expect(row.secondary, 'OpenCode · /work/api · closed');
expect(row.snippet, isNull);
});
test('a chat hit resolves to its session, keeping the matched message', () {
final resolved = searchTargetFor(chatHit('ses_a'));
expect(resolved, isA<ResolvedSearchTarget>());
final target = (resolved as ResolvedSearchTarget).target;
expect(target, isA<SearchChatTarget>());
expect((target as SearchChatTarget).sessionId, 'ses_a');
expect(target.kind, SearchTargetKind.chat);
expect(target.wire, 'chat:ses_a');
final message = chatHit('ses_a', snippet: 'x');
(message['chat'] as Map)['message_id'] = 'm9';
final withMessage =
(searchTargetFor(message) as ResolvedSearchTarget).target
as SearchChatTarget;
expect(withMessage.messageId, 'm9');
expect(withMessage, target);
expect(SearchTarget.fromWire('chat:ses_a'), target);
expect(SearchTarget.fromWire('chat:'), isNull);
});
test('a chat hit without a session id or with a mismatched target is not '
'openable', () {
final missing = chatHit('ses_a');
(missing['chat'] as Map).remove('session_id');
expect(searchTargetFor(missing), isA<UnresolvedSearchTarget>());
final mismatched = {...chatHit('ses_a'), 'target': 'chat:ses_b'};
expect(searchTargetFor(mismatched), isA<UnresolvedSearchTarget>());
});
}
@@ -0,0 +1,124 @@
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/search/search_screen.dart';
import 'package:pipelines_app/features/search/ui/search_result_slivers.dart';
import 'search_screen_test.dart'
show ImmediateGateway, field, response, search, useNarrowSurface;
import 'search_test_support.dart' show chatHit;
/// Run hits for every kind but chat; chat hits for the chat request.
JsonMap replies(String query, String kind) => kind == 'chat'
? response([
chatHit('ses_a', title: 'API refactor', snippet: 'the release retry'),
chatHit('ses_b', title: 'Release notes'),
])
: response([field]);
Widget host(Widget child, {required bool cupertino}) =>
cupertino ? CupertinoApp(home: child) : MaterialApp(home: child);
void main() {
for (final cupertino in [false, true]) {
final platform = cupertino ? 'Cupertino' : 'Material';
testWidgets('$platform: chat hits lead as a Chats group with title, '
'harness, directory and snippet, and open their chat', (tester) async {
useNarrowSurface(tester);
final gateway = ImmediateGateway(replies);
JsonMap? opened;
await tester.pumpWidget(
host(
SearchScreen(
gateway: gateway,
onOpen: (value) => opened = value,
cupertino: cupertino,
),
cupertino: cupertino,
),
);
await search(tester, 'release');
expect(gateway.calls.single['search'], {
'query': 'release',
'kind': '',
'limit': 0,
});
expect(gateway.chatCalls.single['search'], {
'query': 'release',
'kind': 'chat',
'limit': 0,
});
expect(find.text('Chats (2)'), findsOneWidget);
expect(find.text('Pipelines and runs'), findsOneWidget);
final chats = tester.getTopLeft(find.byKey(searchChatsSectionKey));
final others = tester.getTopLeft(find.byKey(searchOthersSectionKey));
final chatRow = find.byKey(const ValueKey('search.result.chat:ses_a'));
final runRow = find.byKey(
const ValueKey('search.result.run:11:4:output'),
);
expect(chats.dy, lessThan(tester.getTopLeft(chatRow).dy));
expect(tester.getTopLeft(chatRow).dy, lessThan(others.dy));
expect(others.dy, lessThan(tester.getTopLeft(runRow).dy));
expect(find.text('API refactor'), findsOneWidget);
expect(find.text('Release notes'), findsOneWidget);
expect(
find.textContaining('Chat · Claude Code · /work/api'),
findsNWidgets(2),
);
expect(find.textContaining('the release retry'), findsOneWidget);
expect(tester.takeException(), isNull);
await tester.tap(chatRow);
await tester.pump();
expect(opened?['target'], 'chat:ses_a');
expect((opened?['chat'] as Map)['session_id'], 'ses_a');
});
}
testWidgets('Chats selected alone lists chats without group headings', (
tester,
) async {
useNarrowSurface(tester);
final gateway = ImmediateGateway(replies);
await tester.pumpWidget(
MaterialApp(
home: SearchScreen(gateway: gateway, onOpen: (_) {}, cupertino: false),
),
);
await search(tester, 't:chat release');
expect(gateway.calls, isEmpty);
expect(gateway.chatCalls, hasLength(1));
expect(find.text('API refactor'), findsOneWidget);
expect(find.byKey(searchChatsSectionKey), findsNothing);
expect(find.byKey(searchOthersSectionKey), findsNothing);
});
testWidgets('an older server without chat search keeps its run results and '
'says chats were not searched', (tester) async {
useNarrowSurface(tester);
final gateway = ImmediateGateway((query, kind) {
if (kind == 'chat') {
throw StateError('unknown search kind "chat"; use one of pipeline');
}
return response([field]);
});
await tester.pumpWidget(
MaterialApp(
home: SearchScreen(gateway: gateway, onOpen: (_) {}, cupertino: false),
),
);
await search(tester, 'release');
expect(
find.byKey(const ValueKey('search.result.run:11:4:output')),
findsOneWidget,
);
expect(find.byKey(searchChatsNoteKey), findsOneWidget);
expect(find.textContaining('does not search chats'), findsOneWidget);
});
}
@@ -14,6 +14,7 @@ void main() {
'step',
'field',
'artifact',
'chat',
'version',
]);
expect(SearchKind.values.map((kind) => kind.label), [
@@ -23,6 +24,7 @@ void main() {
'Steps',
'Fields',
'Artifacts',
'Chats',
'Versions',
]);
expect(SearchKind.fromWire('run'), SearchKind.run);
@@ -10,10 +10,13 @@ class RecordingGateway implements ApiGateway {
final JsonMap Function(String query, String kind) reply;
final calls = <JsonMap>[];
/// The `kind: chat` searches sent beside the others.
final chatCalls = <JsonMap>[];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add(Map.of(fields));
final search = Map<String, dynamic>.from(fields['search'] as Map);
(search['kind'] == 'chat' ? chatCalls : calls).add(Map.of(fields));
return reply(search['query'] as String, search['kind'] as String);
}
@@ -56,7 +59,7 @@ void main() {
expect(gateway.calls, isEmpty);
expect(
find.text('Search pipelines, runs and artifacts.'),
find.text('Search pipelines, runs, artifacts and chats.'),
findsOneWidget,
);
expect(find.textContaining('No matches'), findsNothing);
@@ -10,10 +10,13 @@ class ImmediateGateway implements ApiGateway {
final JsonMap Function(String query, String kind) reply;
final calls = <JsonMap>[];
/// The `kind: chat` searches sent beside the others.
final chatCalls = <JsonMap>[];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add(Map.of(fields));
final search = Map<String, dynamic>.from(fields['search'] as Map);
(search['kind'] == 'chat' ? chatCalls : calls).add(Map.of(fields));
return reply(search['query'] as String, search['kind'] as String);
}
@@ -29,6 +32,8 @@ class FailingThenSucceedingGateway implements ApiGateway {
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
final search = fields['search'];
if (search is Map && search['kind'] == 'chat') return success;
calls++;
if (calls == 1) throw StateError('unknown command: search');
return success;
@@ -4,12 +4,28 @@ import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/search/data/search_repository.dart';
import 'package:pipelines_app/features/search/domain/search_controller.dart';
/// Queues run/artifact searches in [calls]/[pending]. A `kind: chat` search
/// (sent beside every all-kind search) is recorded in [chatCalls] and, unless
/// [holdChats] is set, answered at once with no chats.
class QueuedGateway implements ApiGateway {
QueuedGateway({this.holdChats = false});
final bool holdChats;
final calls = <JsonMap>[];
final pending = <Completer<JsonMap>>[];
final chatCalls = <JsonMap>[];
final chatPending = <Completer<JsonMap>>[];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
final search = fields['search'];
if (search is Map && search['kind'] == 'chat') {
chatCalls.add(Map.of(fields));
if (!holdChats) return Future.value(envelope(const []));
final completer = Completer<JsonMap>();
chatPending.add(completer);
return completer.future;
}
calls.add(Map.of(fields));
final completer = Completer<JsonMap>();
pending.add(completer);
@@ -48,3 +64,18 @@ OmniSearchController controllerFor(ApiGateway gateway) => OmniSearchController(
repository: SearchRepository(gateway),
debounce: Duration.zero,
);
/// A server-shaped `kind: chat` hit; a [snippet] makes it a message match.
JsonMap chatHit(String id, {String title = 'Fix CI', String? snippet}) => {
'kind': 'chat',
'target': 'chat:$id',
'score': snippet == null ? 3 : 1,
'matched_field': snippet == null ? 'title' : 'message',
'chat': {
'session_id': id,
'title': title,
'directory': '/work/api',
'backend': 'claude',
'snippet': ?snippet,
},
};