Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Search existing cached session excerpts without extra reads

dee44148d7d04d0
diff --git a/desktop/lib/state/session_preview.dart b/desktop/lib/state/session_preview.dart
index 64cd26077..4031c3811 100644
--- a/desktop/lib/state/session_preview.dart
+++ b/desktop/lib/state/session_preview.dart
@@ -15,6 +15,7 @@ class SessionPreview {
final List<String> earlierResponses = [];
String? currentRequest, liveText, completedText, savedText, activity;
String _streamText = '';
+ String? _searchText;
bool turnOpen = false,
interrupted = false,
fetched = false,
@@ -61,6 +62,18 @@ class SessionPreview {
bool get hasContent =>
latestRequest != null || liveText != null || response != null;
+ /// A lazy, normalized field over the same bounded excerpts as the preview.
+ /// Keystrokes reuse it; it owns no history or separate search index.
+ String get searchText => _searchText ??= {
+ currentRequest,
+ latestRequest,
+ earlierRequest,
+ liveText,
+ responseExcerpt,
+ ...earlierResponses,
+ activity,
+ }.whereType<String>().join('\n').toLowerCase();
+
void _rememberRequest(Object? value) {
final text = previewText(value, limit: 1600);
if (text == null) return;
@@ -97,6 +110,7 @@ class SessionPreviewStore extends ChangeNotifier {
SessionPreview _entry(SessionPreviewKey key) {
final entry = _records.remove(key) ?? SessionPreview();
+ entry._searchText = null;
_records[key] = entry;
while (_records.length > capacity) {
_records.remove(_records.keys.first);
@@ -187,6 +201,7 @@ class SessionPreviewStore extends ChangeNotifier {
entry.receivedAt = _now();
}
entry.fetched = true;
+ entry._searchText = null;
_changed();
} catch (_) {
if (current()) {
diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dart
index 17faf4f72..b0447970e 100644
--- a/desktop/lib/state/swarm_navigation.dart
+++ b/desktop/lib/state/swarm_navigation.dart
@@ -4,6 +4,7 @@ import '../core/fuzzy_match.dart';
import '../core/models.dart';
import 'app_state.dart';
import 'pane_arrangement.dart';
+import 'session_preview.dart';
import 'swarm.dart';
import 'swarm_catalog.dart';
import 'terminal_pane.dart';
@@ -165,6 +166,7 @@ class SwarmDestination {
this.paneId,
this.swarmName = '',
this.projectId,
+ this.previewKey,
this.members = const {},
Iterable<String?> searchFields = const [],
}) : fields = [
@@ -185,6 +187,7 @@ class SwarmDestination {
final String swarmName;
bool get isCommand => commandId != null;
final String? projectId;
+ final SessionPreviewKey? previewKey;
final Set<String> members;
final bool current;
final List<String> fields;
@@ -430,6 +433,7 @@ class SwarmLocationCatalog {
machineId: pane.machineId,
machineLabel: machineLabel,
agentId: pane.agentId,
+ previewKey: agent == null ? null : app.previewKey(pane.machineId, agent),
engine: engine,
current: swarm.id == app.activeSwarmId && pane.id == app.focusedPaneId,
searchFields: [detail.text, project?.cwd, engine, swarm.name],
@@ -444,13 +448,19 @@ List<SwarmDestination> rankSwarmLocations(
List<SwarmDestination> all,
String query, {
List<String> recent = const [],
+ SessionPreviewStore? previews,
}) {
final groups = <String, List<SwarmDestination>>{};
final parents = {
for (final row in all)
if (row.agentId == null) row.swarmId!: row,
};
- for (final row in rankSwarmDestinations(all, query, recent: recent)) {
+ for (final row in rankSwarmDestinations(
+ all,
+ query,
+ recent: recent,
+ previews: previews,
+ )) {
(groups[row.swarmId!] ??= []).add(row);
}
return [
@@ -840,6 +850,7 @@ List<SwarmDestination> swarmDestinations(
machineId: machineId,
machineLabel: machineName,
agentId: agentId,
+ previewKey: row == null ? null : app.previewKey(machineId, row.$2),
engine: engine,
current:
owner?.id == app.activeSwarmId && pane?.id == app.focusedPaneId,
@@ -882,21 +893,27 @@ int? swarmFieldMatchScore(String field, String term, {required bool title}) {
/// Each word may match a different field, in either order: "mini auth" and
/// "auth mini" both find Auth on Mac mini. Names outrank incidental metadata.
+/// Existing preview text is a fallback, with literal word fragments rather
+/// than scattered-letter matches across long paragraphs. Reading it never
+/// warms the cache or contacts a machine.
List<SwarmDestination> rankSwarmDestinations(
List<SwarmDestination> all,
String query, {
List<String> recent = const [],
+ SessionPreviewStore? previews,
}) {
final needle = query.trim().toLowerCase();
final terms = swarmQueryTerms(query);
final recency = {for (var i = 0; i < recent.length; i++) recent[i]: i};
- final ranked = <({SwarmDestination entry, int score})>[];
+ final ranked = <({SwarmDestination entry, int score, bool content})>[];
for (final entry in all) {
if (entry.fields.first == needle) {
- ranked.add((entry: entry, score: -1));
+ ranked.add((entry: entry, score: -1, content: false));
continue;
}
var total = 0;
+ var content = false;
+ String? excerpt;
for (final term in terms) {
int? best;
for (var i = 0; i < entry.fields.length; i++) {
@@ -910,13 +927,20 @@ List<SwarmDestination> rankSwarmDestinations(
if (best <= 64) break;
}
if (best == null) {
- total = -1;
- break;
+ excerpt ??= entry.previewKey == null
+ ? ''
+ : previews?.read(entry.previewKey!)?.searchText ?? '';
+ if (!excerpt.contains(term)) {
+ total = -1;
+ break;
+ }
+ content = true;
+ best = 256;
}
total += best;
}
if (total >= 0) {
- ranked.add((entry: entry, score: total));
+ ranked.add((entry: entry, score: total, content: content));
}
}
int tier(SwarmDestination e) => !e.hasView
@@ -927,7 +951,8 @@ List<SwarmDestination> rankSwarmDestinations(
? 0
: 1;
ranked.sort((a, b) {
- var order = a.score.compareTo(b.score);
+ var order = (a.content ? 1 : 0).compareTo(b.content ? 1 : 0);
+ if (order == 0) order = a.score.compareTo(b.score);
if (order == 0 && needle.isEmpty) {
order = tier(a.entry).compareTo(tier(b.entry));
}
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index 472d3ca39..62a520054 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -35,6 +35,7 @@ class SwarmSearchController extends ChangeNotifier {
_refresh();
app.addListener(_refresh);
projects?.addListener(_refresh);
+ app.sessionPreviews.addListener(_previewChanged);
}
final AppNotifier app;
@@ -169,7 +170,20 @@ class SwarmSearchController extends ChangeNotifier {
notifyListeners();
}
- void _filter() {
+ void _previewChanged() {
+ if (query.trim().isEmpty || isCommandMode || history != null) return;
+ final previous = rows;
+ final previousSelection = selected?.id;
+ _filter(keepOrder: true);
+ // Live text can add/remove a match, but never shuffle matching rows under
+ // the keyboard or repaint the editor when the result set is unchanged.
+ if (!listEquals(previous, rows) || previousSelection != selected?.id) {
+ notifyListeners();
+ }
+ }
+
+ void _filter({bool keepOrder = false}) {
+ final previous = rows;
final availableCommands = isCommandMode
? commands?.call() ?? const <SwarmDestination>[]
: const <SwarmDestination>[];
@@ -177,7 +191,12 @@ class SwarmSearchController extends ChangeNotifier {
rows = isCommandMode
? rankSwarmDestinations(availableCommands, commandQuery)
: navigating
- ? rankSwarmLocations(_catalog, query, recent: recent)
+ ? rankSwarmLocations(
+ _catalog,
+ query,
+ recent: recent,
+ previews: app.sessionPreviews,
+ )
: rankSwarmDestinations(
adding
? _catalog
@@ -191,13 +210,26 @@ class SwarmSearchController extends ChangeNotifier {
: _catalog,
query,
recent: recent,
+ previews: history == null ? app.sessionPreviews : null,
);
+ if (keepOrder && !navigating) {
+ final remaining = {for (final row in rows) row.id: row};
+ rows = [
+ for (final row in previous) ?remaining.remove(row.id),
+ ...remaining.values,
+ ];
+ }
// The parent stays above its children visually, but Enter after a query
// still targets the best match, including an agent nested under that parent.
final preferred =
_selectedId ??
(navigating && !isCommandMode
- ? rankSwarmDestinations(rows, query, recent: recent).firstOrNull?.id
+ ? rankSwarmDestinations(
+ rows,
+ query,
+ recent: recent,
+ previews: app.sessionPreviews,
+ ).firstOrNull?.id
: null);
final index = rows.indexWhere((row) => row.id == preferred);
cursor = rows.isEmpty
@@ -291,6 +323,7 @@ class SwarmSearchController extends ChangeNotifier {
void dispose() {
app.removeListener(_refresh);
projects?.removeListener(_refresh);
+ app.sessionPreviews.removeListener(_previewChanged);
_previewPage.dispose();
super.dispose();
}
diff --git a/desktop/test/swarm_content_search_test.dart b/desktop/test/swarm_content_search_test.dart
new file mode 100644
index 000000000..182fb75dd
--- /dev/null
+++ b/desktop/test/swarm_content_search_test.dart
@@ -0,0 +1,179 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/state/swarm_search.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'swarm_interactions_test.dart' show chord;
+import 'swarm_screen_test.dart' show mount, terminal;
+import 'swarm_search_preview_test.dart' show seedPreviews;
+import 'swarm_state_test.dart' show createApp;
+
+class _Recent extends WsConn {
+ _Recent()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final calls = <String>[];
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ calls.add(type);
+ expect(payload, {'agentId': 'a0', 'n': 3});
+ return {
+ 'agentId': 'a0',
+ 'asks': ['Make the tab close control appear on hover.'],
+ 'events': [
+ {'kind': 'summary', 'fullText': 'The skylark animation is complete.'},
+ ],
+ };
+ }
+}
+
+void main() {
+ testWidgets(
+ 'cached content matches across fields without additional requests',
+ (tester) async {
+ final conn = _Recent();
+ final app = createApp(connectionForTest: (_) => conn);
+ final machine = app.machineStates['m']!;
+ machine.nodeOnline = true;
+ machine.agents = const [
+ Agent(
+ id: 'a0',
+ sessionId: 'old',
+ name: 'Design',
+ terminalAvailable: true,
+ ),
+ Agent(
+ id: 'a1',
+ sessionId: 'other',
+ name: 'Skylark',
+ terminalAvailable: true,
+ ),
+ ];
+ final key = app.previewKey('m', machine.agents.first);
+ final catalog = SwarmSearchCatalog();
+ final metadata = catalog.read(app, []);
+ final search = SwarmSearchController(app, [], catalog: catalog);
+ search.setQuery('tab close hover');
+ expect(search.rows, isEmpty);
+ app.sessionPreviews.warm([key]);
+ await tester.pump(const Duration(milliseconds: 80));
+ expect(search.rows.single.agentId, 'a0');
+ expect(catalog.read(app, []), same(metadata));
+ search.setQuery('DESIGN HOVER');
+ expect(search.rows.single.agentId, 'a0');
+ search.setQuery('skylark');
+ expect(search.rows.map((row) => row.agentId), ['a1', 'a0']);
+ search.setQuery(
+ 'sklark',
+ ); // No fuzzy letters across a response paragraph.
+ expect(search.rows.map((row) => row.agentId), ['a1']);
+ search.setQuery('tab close hover');
+ var resultChanges = 0;
+ search.addListener(() => resultChanges++);
+ for (var i = 0; i < 100; i++) {
+ app.sessionPreviews.ingest(key, 'text_delta', {
+ 'content': 'Progress $i',
+ });
+ }
+ await tester.pump(const Duration(milliseconds: 80));
+ expect(resultChanges, 0);
+ expect(search.selected?.agentId, 'a0');
+ search.setQuery('progress 99');
+ expect(search.rows.single.agentId, 'a0');
+ machine.agents = [
+ const Agent(
+ id: 'a0',
+ sessionId: 'new',
+ name: 'Design',
+ terminalAvailable: true,
+ ),
+ machine.agents.last,
+ ];
+ app.notifyListeners();
+ expect(
+ search.rows,
+ isEmpty,
+ ); // An old session's cache cannot leak into a restart.
+ expect(conn.calls, ['agent_recent']);
+ search.dispose();
+ app.dispose();
+ },
+ );
+
+ testWidgets(
+ 'live matches preserve order and selection until the query changes',
+ (tester) async {
+ final app = createApp();
+ final machine = app.machineStates['m']!;
+ machine.agents = const [
+ Agent(id: 'a0', name: 'Zulu', terminalAvailable: true),
+ Agent(id: 'a1', name: 'Alpha', terminalAvailable: true),
+ ];
+ final search = SwarmSearchController(app, []);
+ search.setQuery('cobalt');
+ final zulu = app.previewKey('m', machine.agents.first);
+ final alpha = app.previewKey('m', machine.agents.last);
+ app.sessionPreviews.ingest(zulu, 'text_delta', {
+ 'content': 'Cobalt paint',
+ });
+ await tester.pump(const Duration(milliseconds: 80));
+ expect(search.selected?.agentId, 'a0');
+ app.sessionPreviews.ingest(alpha, 'text_delta', {
+ 'content': 'Cobalt blue',
+ });
+ await tester.pump(const Duration(milliseconds: 80));
+ expect(search.rows.map((row) => row.agentId), ['a0', 'a1']);
+ expect(search.selected?.agentId, 'a0');
+ search.setQuery('cobal');
+ expect(search.rows.map((row) => row.agentId), ['a1', 'a0']);
+ app.sessionPreviews.ingest(alpha, 'text_delta', {
+ 'content': 'Changed topic',
+ });
+ await tester.pump(const Duration(milliseconds: 80));
+ expect(search.rows.single.agentId, 'a0');
+ search.dispose();
+ app.dispose();
+ },
+ );
+
+ for (final inline in [false, true]) {
+ testWidgets('content finds the matching preview (inline=$inline)', (
+ tester,
+ ) async {
+ final app = createApp();
+ await seedPreviews(app);
+ app.adoptSessionForTest(terminal('a69', []));
+ app.newSwarm();
+ await mount(tester, app);
+ if (!inline) await chord(tester, LogicalKeyboardKey.keyO);
+ final field = find.byKey(
+ ValueKey(inline ? 'harness-start-search' : 'swarm-search-input'),
+ );
+ await tester.enterText(field, 'IDEMPOTENCY receipt');
+ await tester.pump();
+ final search = tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search;
+ expect(search.rows.single.agentId, 'a0');
+ expect(find.textContaining('Payment retries now reuse'), findsOneWidget);
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+ }
+}