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,47 @@
import '../../../core/api_gateway.dart';
import 'search_row.dart';
/// The chat payload of a `chat` search hit, or null for any other hit.
JsonMap? searchChatOf(JsonMap hit) {
final chat = hit['chat'];
return hit['kind'] == 'chat' && chat is Map
? Map<String, dynamic>.from(chat)
: null;
}
/// A chat hit's row: the chat's title, its harness and directory as the
/// muted facts, and the matching message's snippet when message text matched.
/// It opens only with the server's own `chat:<session id>` target.
SearchRowView searchChatRowView(
JsonMap chat, {
required String query,
required String? target,
required String? recency,
}) {
final title = '${chat['title'] ?? ''}'.trim();
final directory = '${chat['directory'] ?? ''}'.trim();
final snippet = '${chat['snippet'] ?? ''}';
final facts = [
searchHarnessLabel('${chat['backend'] ?? ''}'),
if (directory.isNotEmpty) directory,
if (chat['closed'] == true) 'closed',
].join(' · ');
return SearchRowView(
title: title.isEmpty ? 'Untitled chat' : title,
secondary: facts,
kindLabel: 'Chat',
snippet: snippet.isEmpty ? null : snippet,
snippetSpans: snippetSpans(snippet, query),
recency: recency,
target: target,
);
}
/// The harness's display name, matching the server's own names; an unknown
/// harness shows as sent.
String searchHarnessLabel(String backend) => switch (backend) {
'claude' => 'Claude Code',
'codex' => 'Codex',
'' || 'opencode' => 'OpenCode',
_ => backend,
};
@@ -0,0 +1,83 @@
import '../../../core/api_gateway.dart';
import '../data/search_repository.dart';
import 'search_models.dart';
import 'search_query.dart';
/// Wording for a server whose search does not know the `chat` kind (it
/// predates chat search and rejects the kind by name).
const unsupportedChatSearchCopy =
'This server does not search chats. Update the Pipelines server to '
'include them.';
final _unknownKind = RegExp(r'unknown search kind', caseSensitive: false);
/// The Chats section's state: one `kind: chat` request per sent query, run
/// beside (never instead of, nor ahead of) the run/artifact search, so the
/// server's transcript readback cannot delay the other results.
class SearchChatSlice {
List<JsonMap> results = const [];
bool loading = false;
bool loaded = false;
bool truncated = false;
String? error;
void clear() {
results = const [];
loading = false;
loaded = false;
truncated = false;
error = null;
}
/// Requests chats for [query]. [current] reports whether this request is
/// still the newest edit; a stale reply is dropped without a change.
Future<void> load(
SearchRepository repository,
String query, {
required bool Function() current,
required void Function() changed,
}) async {
loading = true;
error = null;
changed();
try {
final response = await repository.search(
query: query,
kind: SearchKind.chat,
);
if (!current()) return;
if (response == null) {
results = const [];
truncated = false;
error = unsupportedChatSearchCopy;
} else {
results = response.results
.where((hit) => hit['kind'] == SearchKind.chat.wire)
.toList(growable: false);
truncated = response.truncated;
}
} catch (failure) {
if (!current()) return;
results = const [];
truncated = false;
final text = searchFailureText(failure);
error = _unknownKind.hasMatch(text) || text == unsupportedSearchCopy
? unsupportedChatSearchCopy
: text;
}
loading = false;
loaded = true;
changed();
}
/// A short honest note under the Chats section: why chats are missing, or
/// that the server's bounds left some transcripts unsearched.
String? get note {
if (error != null) return error;
if (truncated) {
return "Some chats were not searched within the server's time or "
'result limit.';
}
return null;
}
}
@@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../data/search_repository.dart';
import 'search_chat_slice.dart';
import 'search_models.dart';
import 'search_query.dart';
import 'search_row.dart';
@@ -24,6 +25,7 @@ class OmniSearchController extends ChangeNotifier {
final SearchRepository repository;
final Duration debounce;
final SearchSequencer _sequencer = SearchSequencer();
final SearchChatSlice _chats = SearchChatSlice();
Timer? _timer;
bool _disposed = false;
@@ -51,7 +53,35 @@ class OmniSearchController extends ChangeNotifier {
int get scannedBytes => _scannedBytes;
int get cap => _cap;
int get scanBoundBytes => _scanBoundBytes;
String? get error => _error;
/// The failure the body shows: the run search's, or with the Chats kind
/// selected (no run search is sent) the chat search's.
String? get error =>
_error ?? (parsed.kind == SearchKind.chat ? _chats.error : null);
/// Chat hits for the Chats section: shown for every kind that searches
/// chats (all kinds, or Chats alone).
List<JsonMap> get shownChats =>
_searchesChats(parsed.kind) ? _chats.results : const [];
/// The Chats section's note: why chats are missing, or that the server's
/// bounds left some unsearched. With Chats selected alone a failure is the
/// body's error instead, so only the bounds note remains.
String? get chatsNote => switch (parsed.kind) {
SearchKind.all => _chats.note,
SearchKind.chat when _chats.error == null => _chats.note,
_ => null,
};
/// Whether the Chats section is drawn as its own group above the others.
bool get showsChatSection =>
parsed.kind == SearchKind.all &&
(shownChats.isNotEmpty || chatsNote != null);
static bool _searchesChats(SearchKind kind) =>
kind == SearchKind.all || kind == SearchKind.chat;
bool get _hasShown => shownResults.isNotEmpty || shownChats.isNotEmpty;
/// The results already in hand, re-narrowed to the effective kind so the list
/// always matches the control while a narrowed request loads.
@@ -64,18 +94,22 @@ class OmniSearchController extends ChangeNotifier {
}
SearchBodyKind get bodyKind {
if (_error != null) return SearchBodyKind.error;
if (shownResults.isNotEmpty) return SearchBodyKind.results;
if (_loading && _results.isEmpty) return SearchBodyKind.searching;
if (error != null) return SearchBodyKind.error;
if (_hasShown || showsChatSection) return SearchBodyKind.results;
if ((_loading && _results.isEmpty) || _chats.loading) {
return SearchBodyKind.searching;
}
if (emptyMessage != null) return SearchBodyKind.empty;
return SearchBodyKind.idle;
}
/// A thin progress report above retained results while a newer query loads.
bool get showProgress => _loading && _results.isNotEmpty;
bool get showProgress =>
(_loading && _results.isNotEmpty) ||
(_chats.loading && _chats.results.isNotEmpty);
String? get emptyMessage {
if (_error != null || _loading || shownResults.isNotEmpty) return null;
if (error != null || _loading || _chats.loading || _hasShown) return null;
final effective = parsed;
if (effective.query.trim().isEmpty) {
if (!_loaded || effective.kind == SearchKind.all) return null;
@@ -171,14 +205,39 @@ class OmniSearchController extends ChangeNotifier {
Future<void> _send(SearchEdit sent) async {
final effective = parseSearchQuery(sent.query, _selectedKind);
final query = effective.query.trim();
final chatsOnly = effective.kind == SearchKind.chat;
// The run/artifact search goes first; the chat search follows as its own
// request, so a slow transcript readback never holds the other results.
final runs = chatsOnly
? null
: repository.search(query: query, kind: effective.kind);
if (_searchesChats(effective.kind) && (query.isNotEmpty || chatsOnly)) {
unawaited(
_chats.load(
repository,
query,
current: () => _sequencer.accepts(sent.token) && !_disposed,
changed: _notify,
),
);
} else {
_chats.clear();
}
if (runs == null) {
_results = const [];
_truncated = false;
_loading = false;
_loaded = true;
_error = null;
_notify();
return;
}
_loading = true;
_error = null;
_notify();
try {
final response = await repository.search(
query: effective.query.trim(),
kind: effective.kind,
);
final response = await runs;
if (!_sequencer.accepts(sent.token) || _disposed) return;
if (response == null) {
_loading = false;
@@ -207,6 +266,7 @@ class OmniSearchController extends ChangeNotifier {
}
void _clearResults() {
_chats.clear();
_results = const [];
_truncated = false;
_scannedSteps = 0;
@@ -9,6 +9,7 @@ enum SearchKind {
step('step', 'Steps'),
field('field', 'Fields'),
artifact('artifact', 'Artifacts'),
chat('chat', 'Chats'),
version('version', 'Versions');
const SearchKind(this.wire, this.label);
@@ -1,5 +1,6 @@
import '../../../core/api_gateway.dart';
import '../../../ui/text/relative_time.dart';
import 'search_chat_row.dart';
import 'search_format.dart';
export 'search_format.dart' show humanBytes, formatSearchTimestamp;
@@ -129,6 +130,15 @@ SearchRowView searchRowView(JsonMap hit, String query) {
target: target,
);
}
final chat = searchChatOf(hit);
if (chat != null) {
return searchChatRowView(
chat,
query: query,
target: target,
recency: recency,
);
}
final kind = _nonBlank(hit['kind']);
return SearchRowView(
title: _nonBlank(hit['target']) ?? 'Unrecognised result',
@@ -191,6 +201,7 @@ String? _serverTarget(JsonMap hit) {
'step',
'field',
'artifact',
'chat',
].any((key) => _map(hit[key]) != null);
return known ? target : null;
}
@@ -1,15 +1,16 @@
import '../../../core/api_gateway.dart';
/// The kind of recorded entity a resolved target names.
enum SearchTargetKind { pipeline, version, run, step, field, artifact }
enum SearchTargetKind { pipeline, version, run, step, field, artifact, chat }
/// The exact identity behind a recorded search hit.
///
/// [wire] is the server's own stable target token
/// (`internal/protocol/search.go`): `pipeline:<id>`, `pipeline:<id>:v<version>`,
/// `run:<id>`, `run:<id>:<sequence>`, `run:<id>:<sequence>:<field>` or the
/// recorded artifact URL. It is derived from the typed payload, never copied
/// from the hit, and [SearchTarget.fromWire] accepts it back.
/// `run:<id>`, `run:<id>:<sequence>`, `run:<id>:<sequence>:<field>`, the
/// recorded artifact URL or `chat:<session id>`. It is derived from the typed
/// payload, never copied from the hit, and [SearchTarget.fromWire] accepts it
/// back.
///
/// The token is the identity: two targets that serialise to the same token are
/// the same target even when one of them also carries recorded visit facts the
@@ -63,6 +64,10 @@ sealed class SearchTarget {
// The server's artifact target is its own relative file URL
// (`/artifacts/<run>/<step>/<name>`); an absolute form is accepted only when
// it carries that same path.
if (token.startsWith('chat:')) {
final session = token.substring('chat:'.length);
return session.trim().isEmpty ? null : SearchChatTarget(session);
}
if (token.startsWith('/artifacts/')) return SearchArtifactTarget(token);
if (token.startsWith('http://') || token.startsWith('https://')) {
final uri = Uri.tryParse(token);
@@ -172,6 +177,21 @@ final class SearchArtifactTarget extends SearchTarget {
String get wire => url;
}
/// An operator chat session hit. [messageId] is the matching message when the
/// hit matched message text; the token names only the session.
final class SearchChatTarget extends SearchTarget {
const SearchChatTarget(this.sessionId, {this.messageId});
final String sessionId;
final String? messageId;
@override
SearchTargetKind get kind => SearchTargetKind.chat;
@override
String get wire => 'chat:$sessionId';
}
/// Either the exact [SearchTarget] a hit names, or the reason it names none.
sealed class SearchTargetResolution {
const SearchTargetResolution();
@@ -272,6 +292,17 @@ SearchTargetResolution _identityFor(JsonMap hit) {
return ResolvedSearchTarget(SearchFieldTarget(runId, sequence, name));
}
final chat = _payload(hit, 'chat');
if (chat != null) {
final session = _text(chat['session_id']);
if (session == null) {
return const UnresolvedSearchTarget('chat session id is missing');
}
return ResolvedSearchTarget(
SearchChatTarget(session, messageId: _text(chat['message_id'])),
);
}
final artifact = _payload(hit, 'artifact');
if (artifact != null) {
final url = _text(artifact['url']);
@@ -2,7 +2,7 @@ import 'package:flutter/cupertino.dart';
import '../../../core/api_gateway.dart';
import '../domain/search_controller.dart';
import 'search_result_row.dart';
import 'search_result_slivers.dart';
import 'search_layout.dart';
/// The Cupertino search view: an optional status header and the shared list
@@ -59,18 +59,13 @@ class CupertinoSearchBody extends StatelessWidget {
),
];
case SearchBodyKind.results:
return [
SliverList.builder(
itemCount: controller.shownResults.length,
itemBuilder: (context, index) => SearchResultRow(
hit: controller.shownResults[index],
query: query,
onOpen: onOpen,
cupertino: true,
divider: index < controller.shownResults.length - 1,
),
),
];
return searchResultSlivers(
controller: controller,
query: query,
onOpen: onOpen,
cupertino: true,
message: (text) => _CupertinoMessage(message: text),
);
case SearchBodyKind.empty:
return [
SliverToBoxAdapter(
@@ -82,7 +77,7 @@ class CupertinoSearchBody extends StatelessWidget {
SliverFillRemaining(
hasScrollBody: false,
child: _CupertinoMessage(
message: 'Search pipelines, runs and artifacts.',
message: 'Search pipelines, runs, artifacts and chats.',
),
),
];
@@ -2,7 +2,7 @@ import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../domain/search_controller.dart';
import 'search_result_row.dart';
import 'search_result_slivers.dart';
import 'search_layout.dart';
/// The Material search view: an optional status header and a flat native
@@ -50,18 +50,13 @@ class MaterialSearchBody extends StatelessWidget {
SliverFillRemaining(hasScrollBody: false, child: _Searching()),
];
case SearchBodyKind.results:
return [
SliverList.builder(
itemCount: controller.shownResults.length,
itemBuilder: (context, index) => SearchResultRow(
hit: controller.shownResults[index],
query: query,
onOpen: onOpen,
cupertino: false,
divider: index < controller.shownResults.length - 1,
),
),
];
return searchResultSlivers(
controller: controller,
query: query,
onOpen: onOpen,
cupertino: false,
message: (text) => _SearchMessage(message: text),
);
case SearchBodyKind.empty:
return [
SliverToBoxAdapter(
@@ -73,7 +68,7 @@ class MaterialSearchBody extends StatelessWidget {
SliverFillRemaining(
hasScrollBody: false,
child: _SearchMessage(
message: 'Search pipelines, runs and artifacts.',
message: 'Search pipelines, runs, artifacts and chats.',
),
),
];
@@ -12,7 +12,7 @@ const searchBarControlsKey = ValueKey<String>('search.bar');
const searchTokenHint =
'Filter with t:pipeline or type:artifact (pipeline, run, step, field, '
'artifact, version). Last type wins; choosing Kind replaces it. Quote '
'artifact, chat, version). Last type wins; choosing Kind replaces it. Quote '
'tokens to search literally.';
/// Search's controls as the top bar's main pill (in place of a title): the
@@ -57,7 +57,7 @@ class SearchBarControls extends StatelessWidget {
autofocus: autofocus,
inBar: true,
cupertino: cupertino,
placeholder: 'Search pipelines, runs and artifacts',
placeholder: 'Search pipelines, runs, artifacts and chats',
onChanged: onChanged,
onSubmitted: (_) => onSubmitted(),
onCleared: onCleared,
@@ -11,7 +11,9 @@ import 'search_result_view.dart';
/// artifact's picture), the title with its recency, and one muted line that
/// names the kind and then shows the snippet (its first query occurrence
/// emphasised by weight, never by parsing server text as markup) or, without
/// one, the kind's own facts. An artifact hit's open choices are its menu.
/// one, the kind's own facts. A chat hit with a matching message shows its
/// harness and directory, then the snippet on a second line. An artifact
/// hit's open choices are its menu.
class SearchResultRow extends StatelessWidget {
const SearchResultRow({
super.key,
@@ -46,33 +48,55 @@ class SearchResultRow extends StatelessWidget {
),
title: Text(row.title),
time: row.recency,
subtitle: Text.rich(_line(row)),
subtitle: kind == 'chat' && row.snippet != null
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text.rich(_facts(row)),
Text.rich(TextSpan(children: _snippet(row))),
],
)
: Text.rich(_line(row)),
compactSubtitle: kind == 'chat' && row.snippet != null
? Text.rich(TextSpan(children: _snippet(row)))
: null,
menu: searchArtifactActions(context, hit),
);
}
TextSpan _line(SearchRowView row) {
final snippet = row.snippet;
return TextSpan(
children: [
TextSpan(
text: row.kindLabel,
style: const TextStyle(fontWeight: FontWeight.w600),
),
const TextSpan(text: ' · '),
if (snippet == null)
TextSpan(text: row.secondary)
else
for (final span in row.snippetSpans)
TextSpan(
text: span.text,
style: span.matched
? const TextStyle(fontWeight: FontWeight.bold)
: null,
),
],
);
}
TextSpan _line(SearchRowView row) => row.snippet == null
? _facts(row)
: TextSpan(children: [_kind(row), ..._snippet(row)]);
/// The kind, then the kind's own facts (a chat's harness and directory).
TextSpan _facts(SearchRowView row) => TextSpan(
children: [
_kind(row),
TextSpan(text: row.secondary),
],
);
TextSpan _kind(SearchRowView row) => TextSpan(
children: [
TextSpan(
text: row.kindLabel,
style: const TextStyle(fontWeight: FontWeight.w600),
),
const TextSpan(text: ' · '),
],
);
/// The snippet with its first query occurrence emphasised by weight.
List<TextSpan> _snippet(SearchRowView row) => [
for (final span in row.snippetSpans)
TextSpan(
text: span.text,
style: span.matched
? const TextStyle(fontWeight: FontWeight.bold)
: null,
),
];
}
IconData searchMaterialIcon(String kind) => switch (kind) {
@@ -82,6 +106,7 @@ IconData searchMaterialIcon(String kind) => switch (kind) {
'step' => Icons.arrow_forward,
'field' => Icons.notes,
'artifact' => Icons.attach_file,
'chat' => Icons.chat_bubble_outline,
_ => Icons.help_outline,
};
@@ -92,5 +117,6 @@ IconData searchCupertinoIcon(String kind) => switch (kind) {
'step' => CupertinoIcons.arrow_right,
'field' => CupertinoIcons.doc_text,
'artifact' => CupertinoIcons.paperclip,
'chat' => CupertinoIcons.chat_bubble,
_ => CupertinoIcons.question_circle,
};
@@ -0,0 +1,71 @@
import 'package:flutter/widgets.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/layout/section_heading.dart';
import '../domain/search_controller.dart';
import '../domain/search_models.dart';
import 'search_bounds_note.dart';
import 'search_result_row.dart';
const searchChatsSectionKey = ValueKey<String>('search.section.chats');
const searchOthersSectionKey = ValueKey<String>('search.section.others');
const searchChatsNoteKey = ValueKey<String>('search.chats.note');
/// The results body shared by both hosts. With every kind searched, chat hits
/// lead as their own "Chats" group above the pipeline/run/artifact hits; with
/// Chats selected alone they are the list. A run search with no hits still
/// says so under the Chats group.
List<Widget> searchResultSlivers({
required OmniSearchController controller,
required String query,
required ValueChanged<JsonMap> onOpen,
required bool cupertino,
required Widget Function(String message) message,
}) {
final chats = controller.shownChats;
final others = controller.shownResults;
final grouped = controller.showsChatSection;
final note = controller.chatsNote;
Widget rows(List<JsonMap> hits) => SliverList.builder(
itemCount: hits.length,
itemBuilder: (context, index) => SearchResultRow(
hit: hits[index],
query: query,
onOpen: onOpen,
cupertino: cupertino,
divider: index < hits.length - 1,
),
);
final empty = controller.emptyMessage;
return [
if (grouped)
SliverToBoxAdapter(
child: SectionHeading(
key: searchChatsSectionKey,
title: chats.isEmpty ? 'Chats' : 'Chats (${chats.length})',
header: true,
),
),
if (chats.isNotEmpty) rows(chats),
if (note != null)
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: SearchBoundsNote(key: searchChatsNoteKey, text: note),
),
),
if (grouped && others.isNotEmpty)
const SliverToBoxAdapter(
child: SectionHeading(
key: searchOthersSectionKey,
title: 'Pipelines and runs',
header: true,
),
),
if (others.isNotEmpty) rows(others),
if (others.isEmpty &&
controller.parsed.kind != SearchKind.chat &&
empty != null)
SliverToBoxAdapter(child: message(empty)),
];
}