@nandoblanco/opencode-local-search 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/tui.ts ADDED
@@ -0,0 +1,1470 @@
1
+ "use strict";
2
+
3
+ import type { TuiPluginContext } from "@opencode-ai/plugin/tui";
4
+ import { TextAttributes } from "@opentui/core";
5
+ import {
6
+ createComponent,
7
+ createElement,
8
+ createTextNode,
9
+ effect,
10
+ insert,
11
+ insertNode,
12
+ setProp,
13
+ use,
14
+ } from "@opentui/solid";
15
+ import {
16
+ createEffect,
17
+ createMemo,
18
+ createSignal,
19
+ For,
20
+ onCleanup,
21
+ onMount,
22
+ Show,
23
+ } from "solid-js";
24
+ import {
25
+ type DatePreset,
26
+ formatRelativeTime,
27
+ loadSessionIndex,
28
+ parseSearchQuery,
29
+ type RoleFilter,
30
+ type ScopeFilter,
31
+ type SearchMode,
32
+ type SearchSessionMatch,
33
+ searchSessionIndex,
34
+ type SessionIndex,
35
+ } from "./search.ts";
36
+
37
+ function splitHighlightedText(
38
+ text: string,
39
+ term: string
40
+ ): Array<{ text: string; match: boolean }> {
41
+ if (!term || !term.trim() || !text) {
42
+ return [{ text, match: false }];
43
+ }
44
+ const cleanTerm = term.trim().toLowerCase();
45
+ const words = cleanTerm.split(/\s+/).filter(Boolean);
46
+ const candidates = words.length > 1 ? [cleanTerm, ...words] : [cleanTerm];
47
+ const parts: Array<{ text: string; match: boolean }> = [];
48
+ const lower = text.toLowerCase();
49
+ let cursor = 0;
50
+
51
+ while (cursor < text.length) {
52
+ let bestIdx = -1;
53
+ let bestLen = 0;
54
+ for (const w of candidates) {
55
+ const idx = lower.indexOf(w, cursor);
56
+ if (idx !== -1 && (bestIdx === -1 || idx < bestIdx || (idx === bestIdx && w.length > bestLen))) {
57
+ bestIdx = idx;
58
+ bestLen = w.length;
59
+ }
60
+ }
61
+ if (bestIdx === -1) {
62
+ parts.push({ text: text.slice(cursor), match: false });
63
+ break;
64
+ }
65
+ if (bestIdx > cursor) {
66
+ parts.push({ text: text.slice(cursor, bestIdx), match: false });
67
+ }
68
+ parts.push({ text: text.slice(bestIdx, bestIdx + bestLen), match: true });
69
+ cursor = bestIdx + bestLen;
70
+ }
71
+ return parts.length ? parts : [{ text, match: false }];
72
+ }
73
+
74
+ interface SearchNavigationTarget {
75
+ messageId: string;
76
+ snippet: string;
77
+ matchedTerm: string;
78
+ kind: string;
79
+ timeCreated: number;
80
+ messageRatio?: number;
81
+ }
82
+
83
+ interface DialogProps {
84
+ context: TuiPluginContext;
85
+ initialQuery: string;
86
+ currentDirectory: string;
87
+ close: () => void;
88
+ navigateSession: (sessionId: string, target?: SearchNavigationTarget) => void;
89
+ }
90
+
91
+ const ROLE_CYCLE: RoleFilter[] = ["all", "user", "assistant", "shell"];
92
+ const DATE_CYCLE: DatePreset[] = ["all", "today", "yesterday", "7d", "30d"];
93
+ const MODE_CYCLE: SearchMode[] = ["smart", "fuzzy", "regex"];
94
+
95
+ function createTuiRenderer() {
96
+
97
+ function el(
98
+ tag: string,
99
+ props?: Record<string, unknown> | null,
100
+ ...children: unknown[]
101
+ ) {
102
+ const node = createElement(tag);
103
+ if (props) {
104
+ for (const [key, val] of Object.entries(props)) {
105
+ if (val === undefined) continue;
106
+ if (key === "ref" && typeof val === "function") {
107
+ use(val as (e: unknown) => void, node, undefined);
108
+ } else if (
109
+ typeof val === "function" &&
110
+ !key.startsWith("on") &&
111
+ key !== "renderBefore"
112
+ ) {
113
+ effect((prev: unknown) => setProp(node, key, (val as () => unknown)(), prev));
114
+ } else {
115
+ setProp(node, key, val);
116
+ }
117
+ }
118
+ }
119
+ for (const child of children) {
120
+ if (child === undefined || child === null || child === false) continue;
121
+ if (typeof child === "string") {
122
+ insertNode(node, createTextNode(child));
123
+ } else {
124
+ insert(node, child);
125
+ }
126
+ }
127
+ return node;
128
+ }
129
+
130
+ function SessionSearchDialog(props: DialogProps) {
131
+ const [query, setQuery] = createSignal(props.initialQuery);
132
+ const [scope, setScope] = createSignal<ScopeFilter>("all");
133
+ const [role, setRole] = createSignal<RoleFilter>("all");
134
+ const [datePreset, setDatePreset] = createSignal<DatePreset>("all");
135
+ const [mode, setMode] = createSignal<SearchMode>("smart");
136
+ const [focusPane, setFocusPane] = createSignal<"search" | "list" | "preview">("search");
137
+ const [selectedIndex, setSelectedIndex] = createSignal(0);
138
+ const [selectedSnippetIndex, setSelectedSnippetIndex] = createSignal(0);
139
+ const [indexData, setIndexData] = createSignal<SessionIndex>({
140
+ dbPath: "",
141
+ loadedAt: 0,
142
+ sessions: [],
143
+ });
144
+ const [loading, setLoading] = createSignal(true);
145
+ const [errorMsg, setErrorMsg] = createSignal("");
146
+
147
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
148
+ let rootRef: any;
149
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
150
+ let inputRef: any;
151
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
152
+ let listScrollRef: any;
153
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
154
+ let previewScrollRef: any;
155
+
156
+ const resolveDialogWidth = (): string | number => {
157
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
158
+ const opts = (props.context as any)?.options;
159
+ const raw =
160
+ opts?.dialogWidth ??
161
+ opts?.width ??
162
+ process.env.OPENCODE_SESSION_SEARCH_DIALOG_WIDTH ??
163
+ process.env.OPENCODE_DIALOG_WIDTH ??
164
+ "80%";
165
+ if (typeof raw === "number" && Number.isFinite(raw) && raw > 0) {
166
+ return raw <= 100 ? `${Math.round(raw)}%` : Math.round(raw);
167
+ }
168
+ if (typeof raw === "string") {
169
+ const trimmed = raw.trim();
170
+ if (/^\d+(\.\d+)?%$/.test(trimmed)) return trimmed;
171
+ const num = Number(trimmed);
172
+ if (Number.isFinite(num) && num > 0) {
173
+ return num <= 100 ? `${Math.round(num)}%` : Math.round(num);
174
+ }
175
+ }
176
+ return "80%";
177
+ };
178
+
179
+ const applyDialogWidth = () => {
180
+ try {
181
+ props.context.ui.dialog.set({
182
+ size: "xlarge",
183
+ centered: true,
184
+ });
185
+ } catch {
186
+ // ignore if dialog state is not ready yet
187
+ }
188
+
189
+ if (!rootRef) return;
190
+ try {
191
+ // Walk up to the dialog container box (direct child of the full-screen absolute overlay)
192
+ // and set its width/maxWidth to the configured percentage of the terminal viewport (default 80%).
193
+ const targetWidth = resolveDialogWidth();
194
+ let cursor = rootRef;
195
+ let dialogBox = rootRef;
196
+ while (cursor.parent && cursor.parent._positionType !== "absolute") {
197
+ cursor = cursor.parent;
198
+ dialogBox = cursor;
199
+ }
200
+ dialogBox.width = targetWidth;
201
+ dialogBox.maxWidth = targetWidth;
202
+ dialogBox.minWidth = 72;
203
+
204
+ let inner = rootRef;
205
+ while (inner && inner !== dialogBox) {
206
+ inner.width = "100%";
207
+ inner.maxWidth = "100%";
208
+ inner = inner.parent;
209
+ }
210
+ rootRef.requestRender?.();
211
+ } catch {
212
+ // ignore layout mutation errors
213
+ }
214
+ };
215
+
216
+ const theme = () => props.context.theme.surface("dialog");
217
+
218
+ const reloadIndex = async (force = false) => {
219
+ setLoading(true);
220
+ setErrorMsg("");
221
+ try {
222
+ const loaded = await loadSessionIndex(force);
223
+ setIndexData(loaded);
224
+ } catch (err) {
225
+ setErrorMsg(err instanceof Error ? err.message : String(err));
226
+ } finally {
227
+ setLoading(false);
228
+ }
229
+ };
230
+
231
+ const parsedQuery = createMemo(() =>
232
+ parseSearchQuery(query(), {
233
+ scope: scope(),
234
+ currentDirectory: props.currentDirectory,
235
+ role: role(),
236
+ datePreset: datePreset(),
237
+ mode: mode(),
238
+ })
239
+ );
240
+
241
+ const results = createMemo<SearchSessionMatch[]>(() => {
242
+ const idx = indexData();
243
+ if (!idx.sessions.length) return [];
244
+ return searchSessionIndex(idx, query(), {
245
+ scope: scope(),
246
+ currentDirectory: props.currentDirectory,
247
+ role: role(),
248
+ datePreset: datePreset(),
249
+ mode: mode(),
250
+ limit: 60,
251
+ });
252
+ });
253
+
254
+ createEffect(() => {
255
+ query();
256
+ scope();
257
+ role();
258
+ datePreset();
259
+ mode();
260
+ setSelectedIndex(0);
261
+ setSelectedSnippetIndex(0);
262
+ queueMicrotask(() => listScrollRef?.scrollTo?.(0));
263
+ });
264
+
265
+ const selectedMatch = createMemo<SearchSessionMatch | undefined>(() => {
266
+ const list = results();
267
+ if (!list.length) return undefined;
268
+ const idx = Math.max(0, Math.min(list.length - 1, selectedIndex()));
269
+ return list[idx];
270
+ });
271
+
272
+ const moveSelection = (delta: number) => {
273
+ if (focusPane() === "preview") {
274
+ const snippets = selectedMatch()?.matches ?? [];
275
+ if (!snippets.length) return;
276
+ const nextSnippet = Math.max(
277
+ 0,
278
+ Math.min(snippets.length - 1, selectedSnippetIndex() + delta)
279
+ );
280
+ setSelectedSnippetIndex(nextSnippet);
281
+ queueMicrotask(() => {
282
+ previewScrollRef?.scrollChildIntoView?.(`snippet-row-${nextSnippet}`);
283
+ });
284
+ return;
285
+ }
286
+ const list = results();
287
+ if (!list.length) return;
288
+ const next = Math.max(0, Math.min(list.length - 1, selectedIndex() + delta));
289
+ setSelectedIndex(next);
290
+ setSelectedSnippetIndex(0);
291
+ queueMicrotask(() => {
292
+ listScrollRef?.scrollChildIntoView?.(`session-row-${next}`);
293
+ previewScrollRef?.scrollTo?.(0);
294
+ });
295
+ };
296
+
297
+ const toggleScope = () => {
298
+ setScope((prev: ScopeFilter) => (prev === "all" ? "project" : "all"));
299
+ };
300
+
301
+ const cycleRole = () => {
302
+ setRole((prev: RoleFilter) => ROLE_CYCLE[(ROLE_CYCLE.indexOf(prev) + 1) % ROLE_CYCLE.length]);
303
+ };
304
+
305
+ const cycleDate = () => {
306
+ setDatePreset((prev: DatePreset) => DATE_CYCLE[(DATE_CYCLE.indexOf(prev) + 1) % DATE_CYCLE.length]);
307
+ };
308
+
309
+ const cycleMode = () => {
310
+ setMode((prev: SearchMode) => MODE_CYCLE[(MODE_CYCLE.indexOf(prev) + 1) % MODE_CYCLE.length]);
311
+ };
312
+
313
+ const openSelected = (explicitHit?: SearchSessionMatch["matches"][number]) => {
314
+ const current = selectedMatch();
315
+ if (!current) return;
316
+
317
+ const snippets = current.matches ?? [];
318
+ const chosen =
319
+ explicitHit ??
320
+ snippets[Math.max(0, Math.min(snippets.length - 1, selectedSnippetIndex()))] ??
321
+ current.bestMatch;
322
+
323
+ // If the active match is a session title match, prefer the first message match in the session if available
324
+ const messageHit =
325
+ chosen && chosen.messageId
326
+ ? chosen
327
+ : snippets.find((m) => Boolean(m.messageId)) ?? chosen;
328
+
329
+ let messageRatio: number | undefined;
330
+ if (messageHit?.messageId && current.session.entries.length > 0) {
331
+ const uniqueMsgIds: string[] = [];
332
+ const sortedEntries = [...current.session.entries].sort(
333
+ (a, b) => a.timeCreated - b.timeCreated
334
+ );
335
+ for (const entry of sortedEntries) {
336
+ const entryMsgId = entry.messageId || entry.id.split(":")[0];
337
+ if (entryMsgId && !uniqueMsgIds.includes(entryMsgId)) {
338
+ uniqueMsgIds.push(entryMsgId);
339
+ }
340
+ }
341
+ const msgIdx = uniqueMsgIds.indexOf(messageHit.messageId);
342
+ if (msgIdx !== -1 && uniqueMsgIds.length > 1) {
343
+ messageRatio = msgIdx / (uniqueMsgIds.length - 1);
344
+ } else if (msgIdx === 0) {
345
+ messageRatio = 0;
346
+ }
347
+ }
348
+
349
+ props.navigateSession(
350
+ current.session.id,
351
+ messageHit
352
+ ? {
353
+ messageId: messageHit.messageId,
354
+ snippet: messageHit.snippet,
355
+ matchedTerm: messageHit.matchedTerm,
356
+ kind: messageHit.kind,
357
+ timeCreated: messageHit.timeCreated,
358
+ messageRatio,
359
+ }
360
+ : undefined
361
+ );
362
+ };
363
+
364
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
365
+ const handleKeyPress = (event: any) => {
366
+ const name = String(event.name || "").toLowerCase();
367
+ const enter = ["return", "enter", "linefeed"].includes(name);
368
+
369
+ if (name === "escape") {
370
+ event.preventDefault();
371
+ event.stopPropagation();
372
+ props.close();
373
+ return;
374
+ }
375
+
376
+ if (enter) {
377
+ event.preventDefault();
378
+ event.stopPropagation();
379
+ openSelected();
380
+ return;
381
+ }
382
+
383
+ if (name === "tab") {
384
+ event.preventDefault();
385
+ event.stopPropagation();
386
+ const order: Array<"search" | "list" | "preview"> = ["search", "list", "preview"];
387
+ const idx = order.indexOf(focusPane());
388
+ const next = order[(idx + (event.shift ? -1 : 1) + order.length) % order.length];
389
+ setFocusPane(next);
390
+ return;
391
+ }
392
+
393
+ if (event.ctrl && name === "p") {
394
+ event.preventDefault();
395
+ event.stopPropagation();
396
+ toggleScope();
397
+ return;
398
+ }
399
+ if (event.ctrl && name === "g") {
400
+ event.preventDefault();
401
+ event.stopPropagation();
402
+ cycleRole();
403
+ return;
404
+ }
405
+ if (event.ctrl && name === "t") {
406
+ event.preventDefault();
407
+ event.stopPropagation();
408
+ cycleDate();
409
+ return;
410
+ }
411
+ if (event.ctrl && name === "r") {
412
+ event.preventDefault();
413
+ event.stopPropagation();
414
+ cycleMode();
415
+ return;
416
+ }
417
+ if (event.ctrl && name === "l") {
418
+ event.preventDefault();
419
+ event.stopPropagation();
420
+ reloadIndex(true);
421
+ return;
422
+ }
423
+
424
+ if (
425
+ name === "down" ||
426
+ (event.ctrl && name === "n") ||
427
+ (focusPane() === "list" && !event.ctrl && name === "j")
428
+ ) {
429
+ event.preventDefault();
430
+ event.stopPropagation();
431
+ moveSelection(1);
432
+ return;
433
+ }
434
+ if (
435
+ name === "up" ||
436
+ (event.ctrl && name === "k") ||
437
+ (focusPane() === "list" && !event.ctrl && name === "k")
438
+ ) {
439
+ event.preventDefault();
440
+ event.stopPropagation();
441
+ moveSelection(-1);
442
+ return;
443
+ }
444
+ if (name === "pagedown" || (event.ctrl && name === "d")) {
445
+ event.preventDefault();
446
+ event.stopPropagation();
447
+ if (focusPane() === "preview") {
448
+ previewScrollRef?.scrollBy?.(8);
449
+ } else {
450
+ moveSelection(6);
451
+ }
452
+ return;
453
+ }
454
+ if (name === "pageup" || (event.ctrl && name === "u")) {
455
+ event.preventDefault();
456
+ event.stopPropagation();
457
+ if (focusPane() === "preview") {
458
+ previewScrollRef?.scrollBy?.(-8);
459
+ } else {
460
+ moveSelection(-6);
461
+ }
462
+ return;
463
+ }
464
+ if (focusPane() === "preview" && !event.ctrl && (name === "j" || name === "k")) {
465
+ event.preventDefault();
466
+ event.stopPropagation();
467
+ previewScrollRef?.scrollBy?.(name === "j" ? 2 : -2);
468
+ return;
469
+ }
470
+ if (focusPane() !== "search" && !event.ctrl && name === "/") {
471
+ event.preventDefault();
472
+ event.stopPropagation();
473
+ setFocusPane("search");
474
+ return;
475
+ }
476
+ };
477
+
478
+ onMount(() => {
479
+ props.context.renderer.keyInput.prependListener("keypress", handleKeyPress);
480
+ applyDialogWidth();
481
+ queueMicrotask(() => {
482
+ applyDialogWidth();
483
+ if (props.initialQuery && inputRef && inputRef.value !== props.initialQuery) {
484
+ inputRef.value = props.initialQuery;
485
+ }
486
+ });
487
+ reloadIndex(false);
488
+ });
489
+
490
+ onCleanup(() => {
491
+ props.context.renderer.keyInput.removeListener("keypress", handleKeyPress);
492
+ });
493
+
494
+ const Pill = (pillProps: {
495
+ label: () => string;
496
+ shortcut?: string;
497
+ active: () => boolean;
498
+ onClick: () => void;
499
+ }) =>
500
+ el(
501
+ "box",
502
+ {
503
+ flexDirection: "row",
504
+ flexShrink: 0,
505
+ paddingX: 1,
506
+ backgroundColor: () =>
507
+ pillProps.active()
508
+ ? theme().background.action.primary.focused
509
+ : theme().background.raised.base,
510
+ onMouseUp: pillProps.onClick,
511
+ },
512
+ el(
513
+ "text",
514
+ {
515
+ fg: () =>
516
+ pillProps.active()
517
+ ? theme().text.action.primary.focused
518
+ : theme().text.base,
519
+ attributes: () => (pillProps.active() ? TextAttributes.BOLD : undefined),
520
+ },
521
+ pillProps.label
522
+ ),
523
+ pillProps.shortcut
524
+ ? el(
525
+ "text",
526
+ {
527
+ fg: () =>
528
+ pillProps.active()
529
+ ? theme().text.action.primary.focused
530
+ : theme().text.muted,
531
+ },
532
+ ` ${pillProps.shortcut}`
533
+ )
534
+ : null
535
+ );
536
+
537
+ return el(
538
+ "box",
539
+ {
540
+ ref: (r: unknown) => {
541
+ rootRef = r;
542
+ queueMicrotask(applyDialogWidth);
543
+ },
544
+ width: "100%",
545
+ height: 28,
546
+ flexDirection: "column",
547
+ backgroundColor: () => theme().background.base,
548
+ },
549
+ // 1. Header Bar
550
+ el(
551
+ "box",
552
+ {
553
+ flexDirection: "row",
554
+ justifyContent: "space-between",
555
+ alignItems: "center",
556
+ paddingX: 2,
557
+ paddingTop: 1,
558
+ flexShrink: 0,
559
+ },
560
+ el(
561
+ "box",
562
+ { flexDirection: "row", gap: 2, alignItems: "center" },
563
+ el(
564
+ "text",
565
+ {
566
+ fg: () => theme().text.base,
567
+ attributes: TextAttributes.BOLD,
568
+ },
569
+ "Session Search"
570
+ ),
571
+ el(
572
+ "text",
573
+ { fg: () => theme().text.muted },
574
+ () =>
575
+ loading()
576
+ ? "indexing SQLite..."
577
+ : `${results().length} of ${indexData().sessions.length} sessions`
578
+ )
579
+ ),
580
+ el(
581
+ "box",
582
+ {
583
+ flexDirection: "row",
584
+ gap: 2,
585
+ alignItems: "center",
586
+ },
587
+ el(
588
+ "text",
589
+ { fg: () => theme().text.muted },
590
+ () => props.context.ui.format.path(props.currentDirectory)
591
+ ),
592
+ el(
593
+ "box",
594
+ {
595
+ paddingX: 1,
596
+ onMouseUp: () => props.close(),
597
+ },
598
+ el("text", { fg: () => theme().text.muted }, "esc")
599
+ )
600
+ )
601
+ ),
602
+
603
+ // 2. Search Input + Filter Pills Row
604
+ el(
605
+ "box",
606
+ {
607
+ flexDirection: "column",
608
+ paddingX: 2,
609
+ paddingY: 1,
610
+ gap: 1,
611
+ flexShrink: 0,
612
+ border: ["bottom"],
613
+ borderColor: () => theme().border.base,
614
+ },
615
+ el(
616
+ "box",
617
+ {
618
+ flexDirection: "row",
619
+ alignItems: "center",
620
+ gap: 1,
621
+ },
622
+ el(
623
+ "text",
624
+ {
625
+ fg: () =>
626
+ focusPane() === "search"
627
+ ? theme().text.action.primary.base
628
+ : theme().text.muted,
629
+ attributes: TextAttributes.BOLD,
630
+ },
631
+ "›"
632
+ ),
633
+ el("input", {
634
+ id: "session-search-input",
635
+ ref: (r: unknown) => {
636
+ inputRef = r;
637
+ if (props.initialQuery && r && (r as { value?: string }).value !== props.initialQuery) {
638
+ (r as { value: string }).value = props.initialQuery;
639
+ }
640
+ },
641
+ flexGrow: 1,
642
+ value: () => query(),
643
+ focused: () => focusPane() === "search",
644
+ maxLength: 2000,
645
+ placeholder:
646
+ "Search keywords, \"exact phrase\", /regex/i, ~fuzzy, role:user, date:7d, file:path, tool:name...",
647
+ placeholderColor: () => theme().text.muted,
648
+ textColor: () => theme().text.base,
649
+ focusedTextColor: () => theme().text.formfield.focused,
650
+ cursorColor: () => theme().text.formfield.focused,
651
+ backgroundColor: () => theme().background.base,
652
+ focusedBackgroundColor: () => theme().background.formfield.focused,
653
+ onMouseDown: () => setFocusPane("search"),
654
+ onInput: (val: string) => setQuery(val),
655
+ })
656
+ ),
657
+ // Filter pills bar
658
+ el(
659
+ "box",
660
+ {
661
+ flexDirection: "row",
662
+ flexWrap: "wrap",
663
+ gap: 1,
664
+ alignItems: "center",
665
+ },
666
+ Pill({
667
+ label: () =>
668
+ `scope:${(parsedQuery().scope ?? scope()) === "project" ? "project" : "all"}`,
669
+ shortcut: "^p",
670
+ active: () => (parsedQuery().scope ?? scope()) === "project",
671
+ onClick: toggleScope,
672
+ }),
673
+ Pill({
674
+ label: () => `role:${parsedQuery().role}`,
675
+ shortcut: "^g",
676
+ active: () => parsedQuery().role !== "all",
677
+ onClick: cycleRole,
678
+ }),
679
+ Pill({
680
+ label: () =>
681
+ `date:${parsedQuery().dateRange?.label ?? datePreset()}`,
682
+ shortcut: "^t",
683
+ active: () => Boolean(parsedQuery().dateRange),
684
+ onClick: cycleDate,
685
+ }),
686
+ Pill({
687
+ label: () => `mode:${parsedQuery().effectiveMode}`,
688
+ shortcut: "^r",
689
+ active: () => parsedQuery().effectiveMode !== "smart",
690
+ onClick: cycleMode,
691
+ }),
692
+ createComponent(Show, {
693
+ get when() {
694
+ return Boolean(parsedQuery().fileFilter);
695
+ },
696
+ get children() {
697
+ return el(
698
+ "text",
699
+ { fg: () => theme().text.action.primary.base },
700
+ () => ` [file:${parsedQuery().fileFilter}]`
701
+ );
702
+ },
703
+ }),
704
+ createComponent(Show, {
705
+ get when() {
706
+ return Boolean(parsedQuery().toolFilter);
707
+ },
708
+ get children() {
709
+ return el(
710
+ "text",
711
+ { fg: () => theme().text.action.primary.base },
712
+ () => ` [tool:${parsedQuery().toolFilter}]`
713
+ );
714
+ },
715
+ }),
716
+ createComponent(Show, {
717
+ get when() {
718
+ return Boolean(parsedQuery().regexError);
719
+ },
720
+ get children() {
721
+ return el(
722
+ "text",
723
+ { fg: () => theme().text.feedback.error.base },
724
+ () => ` Regex: ${parsedQuery().regexError}`
725
+ );
726
+ },
727
+ })
728
+ )
729
+ ),
730
+
731
+ // 3. Split-Pane Main Body (Left: Session List, Right: Match Preview)
732
+ el(
733
+ "box",
734
+ {
735
+ flexDirection: "row",
736
+ flexGrow: 1,
737
+ minHeight: 0,
738
+ },
739
+ // Left Pane: Results List (44% width)
740
+ el(
741
+ "scrollbox",
742
+ {
743
+ id: "session-search-list",
744
+ ref: (r: unknown) => {
745
+ listScrollRef = r;
746
+ },
747
+ width: "44%",
748
+ height: "100%",
749
+ flexShrink: 0,
750
+ border: ["right"],
751
+ borderColor: () =>
752
+ focusPane() === "list" ? theme().text.base : theme().border.base,
753
+ scrollbarOptions: { visible: false },
754
+ onMouseDown: () => setFocusPane("list"),
755
+ },
756
+ createComponent(Show, {
757
+ get when() {
758
+ return !loading() && results().length > 0;
759
+ },
760
+ get fallback() {
761
+ return el(
762
+ "box",
763
+ { paddingX: 2, paddingY: 1 },
764
+ el(
765
+ "text",
766
+ { fg: () => theme().text.muted },
767
+ () =>
768
+ loading()
769
+ ? "Loading sessions..."
770
+ : errorMsg()
771
+ ? `Error: ${errorMsg()}`
772
+ : "No matching sessions found. Try ~fuzzy, scope:all, or fewer terms."
773
+ )
774
+ );
775
+ },
776
+ get children() {
777
+ return createComponent(For, {
778
+ get each() {
779
+ return results();
780
+ },
781
+ children: (item: SearchSessionMatch, idx: () => number) => {
782
+ const isSelected = () => selectedIndex() === idx();
783
+ return el(
784
+ "box",
785
+ {
786
+ id: () => `session-row-${idx()}`,
787
+ flexDirection: "column",
788
+ paddingX: 1,
789
+ paddingY: 0,
790
+ marginBottom: 1,
791
+ flexShrink: 0,
792
+ backgroundColor: () =>
793
+ isSelected()
794
+ ? theme().background.action.primary.focused
795
+ : undefined,
796
+ onMouseUp: () => {
797
+ setSelectedIndex(idx());
798
+ openSelected();
799
+ },
800
+ onMouseOver: () => {
801
+ setSelectedIndex(idx());
802
+ },
803
+ },
804
+ el(
805
+ "box",
806
+ {
807
+ flexDirection: "row",
808
+ justifyContent: "space-between",
809
+ width: "100%",
810
+ },
811
+ el(
812
+ "text",
813
+ {
814
+ wrapMode: "none",
815
+ truncate: true,
816
+ flexShrink: 1,
817
+ minWidth: 0,
818
+ fg: () =>
819
+ isSelected()
820
+ ? theme().text.action.primary.focused
821
+ : theme().text.base,
822
+ attributes: () =>
823
+ isSelected() ? TextAttributes.BOLD : undefined,
824
+ },
825
+ () =>
826
+ `${isSelected() ? "› " : " "}${item.session.title}`
827
+ ),
828
+ el(
829
+ "text",
830
+ {
831
+ wrapMode: "none",
832
+ flexShrink: 0,
833
+ fg: () =>
834
+ isSelected()
835
+ ? theme().text.action.primary.focused
836
+ : theme().text.muted,
837
+ },
838
+ () =>
839
+ ` [${item.matchBadge}] ${formatRelativeTime(item.session.timeUpdated)}`
840
+ )
841
+ ),
842
+ el(
843
+ "text",
844
+ {
845
+ wrapMode: "none",
846
+ truncate: true,
847
+ fg: () =>
848
+ isSelected()
849
+ ? theme().text.action.primary.focused
850
+ : theme().text.muted,
851
+ },
852
+ () => ` ${item.bestSnippet}`
853
+ )
854
+ );
855
+ },
856
+ });
857
+ },
858
+ })
859
+ ),
860
+
861
+ // Right Pane: Rich Match & Session Context Preview (56% width)
862
+ el(
863
+ "scrollbox",
864
+ {
865
+ id: "session-search-preview",
866
+ ref: (r: unknown) => {
867
+ previewScrollRef = r;
868
+ },
869
+ flexGrow: 1,
870
+ minWidth: 0,
871
+ minHeight: 0,
872
+ paddingX: 2,
873
+ paddingY: 1,
874
+ focused: () => focusPane() === "preview",
875
+ onMouseDown: () => setFocusPane("preview"),
876
+ },
877
+ createComponent(Show, {
878
+ get when() {
879
+ return selectedMatch();
880
+ },
881
+ get fallback() {
882
+ return el(
883
+ "text",
884
+ { fg: () => theme().text.muted },
885
+ "Select a session on the left to inspect matching messages, tools, and files."
886
+ );
887
+ },
888
+ get children() {
889
+ return el(
890
+ "box",
891
+ { flexDirection: "column", gap: 1 },
892
+ el(
893
+ "text",
894
+ {
895
+ fg: () => theme().text.base,
896
+ attributes: TextAttributes.BOLD,
897
+ },
898
+ () => selectedMatch()?.session.title ?? ""
899
+ ),
900
+ el(
901
+ "text",
902
+ { fg: () => theme().text.muted, wrapMode: "word" },
903
+ () => {
904
+ const m = selectedMatch();
905
+ if (!m) return "";
906
+ const dir = m.session.directory
907
+ ? props.context.ui.format.path(m.session.directory)
908
+ : "(no directory)";
909
+ return `${dir} · updated ${formatRelativeTime(m.session.timeUpdated)} · ${m.totalMatches} match${m.totalMatches === 1 ? "" : "es"}`;
910
+ }
911
+ ),
912
+ createComponent(Show, {
913
+ get when() {
914
+ return (selectedMatch()?.session.tools.length ?? 0) > 0;
915
+ },
916
+ get children() {
917
+ return el(
918
+ "text",
919
+ { fg: () => theme().text.muted, wrapMode: "word" },
920
+ () =>
921
+ `Tools: ${selectedMatch()?.session.tools.slice(0, 8).join(", ")}`
922
+ );
923
+ },
924
+ }),
925
+ createComponent(Show, {
926
+ get when() {
927
+ return (selectedMatch()?.session.files.length ?? 0) > 0;
928
+ },
929
+ get children() {
930
+ return el(
931
+ "text",
932
+ { fg: () => theme().text.muted, wrapMode: "word" },
933
+ () =>
934
+ `Files: ${selectedMatch()
935
+ ?.session.files.slice(0, 4)
936
+ .map((f: string) => props.context.ui.format.path(f))
937
+ .join(", ")}${(selectedMatch()?.session.files.length ?? 0) > 4 ? ` (+${(selectedMatch()?.session.files.length ?? 0) - 4} more)` : ""}`
938
+ );
939
+ },
940
+ }),
941
+ el(
942
+ "text",
943
+ {
944
+ fg: () => theme().text.base,
945
+ attributes: TextAttributes.BOLD,
946
+ marginTop: 1,
947
+ },
948
+ () =>
949
+ query().trim()
950
+ ? `Matching Snippets (${selectedMatch()?.matches.length ?? 0} shown)`
951
+ : "Recent Conversation Preview"
952
+ ),
953
+ createComponent(For, {
954
+ get each() {
955
+ return selectedMatch()?.matches ?? [];
956
+ },
957
+ children: (hit: SearchSessionMatch["matches"][number], idx: () => number) => {
958
+ const isActiveSnippet = () => idx() === selectedSnippetIndex();
959
+ return el(
960
+ "box",
961
+ {
962
+ id: () => `snippet-row-${idx()}`,
963
+ flexDirection: "column",
964
+ paddingLeft: 1,
965
+ marginBottom: 1,
966
+ border: ["left"],
967
+ borderColor: () =>
968
+ isActiveSnippet()
969
+ ? theme().text.action.primary.base
970
+ : theme().border.base,
971
+ onMouseUp: () => {
972
+ setSelectedSnippetIndex(idx());
973
+ openSelected(hit);
974
+ },
975
+ },
976
+ el(
977
+ "text",
978
+ {
979
+ fg: () =>
980
+ isActiveSnippet()
981
+ ? theme().text.action.primary.base
982
+ : theme().text.muted,
983
+ attributes: TextAttributes.BOLD,
984
+ },
985
+ () => {
986
+ const roleTag =
987
+ hit.kind === "title"
988
+ ? "[TITLE]"
989
+ : hit.kind === "fuzzy"
990
+ ? `[FUZZY · ${hit.role.toUpperCase()}]`
991
+ : hit.kind === "filepath"
992
+ ? "[FILE]"
993
+ : hit.kind === "tool"
994
+ ? `[TOOL:${hit.toolName || "call"}]`
995
+ : hit.role === "user"
996
+ ? "[USER]"
997
+ : "[ASSISTANT]";
998
+ const prefix = isActiveSnippet() ? "› " : "";
999
+ return `${prefix}${roleTag} · ${formatRelativeTime(hit.timeCreated)}`;
1000
+ }
1001
+ ),
1002
+ el(
1003
+ "text",
1004
+ {
1005
+ wrapMode: "word",
1006
+ fg: () => theme().text.base,
1007
+ },
1008
+ createComponent(For, {
1009
+ get each() {
1010
+ return splitHighlightedText(hit.snippet, hit.matchedTerm);
1011
+ },
1012
+ children: (seg: { text: string; match: boolean }) =>
1013
+ el(
1014
+ "span",
1015
+ {
1016
+ fg: () =>
1017
+ seg.match
1018
+ ? theme().text.action.primary.base
1019
+ : theme().text.base,
1020
+ attributes: () =>
1021
+ seg.match ? TextAttributes.BOLD : undefined,
1022
+ },
1023
+ seg.text
1024
+ ),
1025
+ })
1026
+ )
1027
+ );
1028
+ },
1029
+ })
1030
+ );
1031
+ },
1032
+ })
1033
+ )
1034
+ ),
1035
+
1036
+ // 4. Footer Shortcut Bar
1037
+ el(
1038
+ "box",
1039
+ {
1040
+ flexDirection: "row",
1041
+ justifyContent: "space-between",
1042
+ gap: 2,
1043
+ paddingX: 2,
1044
+ paddingY: 1,
1045
+ flexShrink: 0,
1046
+ border: ["top"],
1047
+ borderColor: () => theme().border.base,
1048
+ },
1049
+ el(
1050
+ "text",
1051
+ {
1052
+ fg: () => theme().text.muted,
1053
+ flexShrink: 1,
1054
+ minWidth: 0,
1055
+ wrapMode: "none",
1056
+ truncate: true,
1057
+ },
1058
+ "enter open · ↑/↓ or ^n/^k select · ^p scope · ^g role · ^t date · ^r mode · tab pane"
1059
+ ),
1060
+ el(
1061
+ "text",
1062
+ { fg: () => theme().text.muted, flexShrink: 0, wrapMode: "none" },
1063
+ "0 tokens"
1064
+ )
1065
+ )
1066
+ );
1067
+ }
1068
+
1069
+ return (props: DialogProps) => createComponent(SessionSearchDialog, props);
1070
+ }
1071
+
1072
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1073
+ function extractRenderableText(node: any): string {
1074
+ if (!node) return "";
1075
+ if (typeof node.plainText === "string" && node.plainText.length > 0) {
1076
+ return node.plainText;
1077
+ }
1078
+ if (typeof node._content === "string" && node._content.length > 0) {
1079
+ return node._content;
1080
+ }
1081
+ if (typeof node.content === "string" && node.content.length > 0) {
1082
+ return node.content;
1083
+ }
1084
+ if (typeof node.textBuffer?.getPlainText === "function") {
1085
+ try {
1086
+ const text = node.textBuffer.getPlainText();
1087
+ if (typeof text === "string" && text.length > 0) return text;
1088
+ } catch {
1089
+ // ignore buffer read errors
1090
+ }
1091
+ }
1092
+ return "";
1093
+ }
1094
+
1095
+ function normalizeSearchNeedle(raw: string): string {
1096
+ return raw
1097
+ .replace(/^\.{2,}\s*/, "")
1098
+ .replace(/\s*\.{2,}$/, "")
1099
+ .replace(/^\[[^\]]+\]\s*/, "")
1100
+ .replace(/\s+/g, " ")
1101
+ .trim()
1102
+ .toLowerCase();
1103
+ }
1104
+
1105
+ let activeScrollInterval: ReturnType<typeof setInterval> | null = null;
1106
+ let activeScrollTimeout: ReturnType<typeof setTimeout> | null = null;
1107
+
1108
+ function clearActiveScrollTimers() {
1109
+ if (activeScrollInterval) {
1110
+ clearInterval(activeScrollInterval);
1111
+ activeScrollInterval = null;
1112
+ }
1113
+ if (activeScrollTimeout) {
1114
+ clearTimeout(activeScrollTimeout);
1115
+ activeScrollTimeout = null;
1116
+ }
1117
+ }
1118
+
1119
+ function scrollToMatchedMessage(
1120
+ context: TuiPluginContext,
1121
+ sessionId: string,
1122
+ target?: SearchNavigationTarget
1123
+ ) {
1124
+ clearActiveScrollTimers();
1125
+ if (!target) return;
1126
+ if (target.kind === "title" && !target.messageId) return;
1127
+
1128
+ try {
1129
+ void Promise.resolve(context.data?.session?.message?.sync?.(sessionId)).catch(
1130
+ () => {}
1131
+ );
1132
+ } catch {
1133
+ // ignore sync errors
1134
+ }
1135
+
1136
+ const rawNeedle = normalizeSearchNeedle(target.snippet || "");
1137
+ const matchedTermLower = (target.matchedTerm || "").trim().toLowerCase();
1138
+
1139
+ // Build candidate phrase needles from most specific to broadest
1140
+ const needles: string[] = [];
1141
+ if (rawNeedle.length >= 8) {
1142
+ needles.push(rawNeedle.slice(0, 48));
1143
+ if (matchedTermLower && rawNeedle.includes(matchedTermLower)) {
1144
+ const idx = rawNeedle.indexOf(matchedTermLower);
1145
+ const start = Math.max(0, idx - 12);
1146
+ const windowSlice = rawNeedle.slice(start, start + 36).trim();
1147
+ if (windowSlice.length >= 6 && !needles.includes(windowSlice)) {
1148
+ needles.push(windowSlice);
1149
+ }
1150
+ }
1151
+ }
1152
+ if (matchedTermLower.length >= 2 && !needles.includes(matchedTermLower)) {
1153
+ needles.push(matchedTermLower);
1154
+ }
1155
+
1156
+ let attempts = 0;
1157
+ const maxAttempts = 25;
1158
+
1159
+ const tryScroll = (): boolean => {
1160
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1161
+ const root = (context.renderer as any)?.root;
1162
+ if (!root || typeof root.getChildren !== "function") return false;
1163
+
1164
+ // 1. Find the largest visible ScrollBoxRenderable in the active session view
1165
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1166
+ const scrollBoxes: any[] = [];
1167
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1168
+ const findScrollBoxes = (node: any) => {
1169
+ if (!node || node.isDestroyed || node.visible === false) return;
1170
+ if (
1171
+ typeof node.scrollTo === "function" &&
1172
+ typeof node.scrollBy === "function" &&
1173
+ node.content &&
1174
+ node.viewport
1175
+ ) {
1176
+ scrollBoxes.push(node);
1177
+ }
1178
+ const children =
1179
+ typeof node.getChildren === "function" ? node.getChildren() : [];
1180
+ for (const child of children) {
1181
+ findScrollBoxes(child);
1182
+ }
1183
+ };
1184
+ findScrollBoxes(root);
1185
+ if (!scrollBoxes.length) return false;
1186
+
1187
+ scrollBoxes.sort(
1188
+ (a, b) =>
1189
+ (b.viewport?.width ?? 0) * (b.viewport?.height ?? 0) -
1190
+ (a.viewport?.width ?? 0) * (a.viewport?.height ?? 0)
1191
+ );
1192
+ const scrollBox = scrollBoxes[0];
1193
+ const topChildren =
1194
+ typeof scrollBox.content?.getChildren === "function"
1195
+ ? scrollBox.content.getChildren()
1196
+ : [];
1197
+ if (!topChildren.length || (scrollBox.scrollHeight ?? 0) <= 0) {
1198
+ return false;
1199
+ }
1200
+
1201
+ // 2. Determine chronological message ratio (0 = oldest at top, 1 = newest at bottom)
1202
+ let ratio = target.messageRatio;
1203
+ try {
1204
+ const liveMessages = context.data?.session?.message?.list?.(sessionId);
1205
+ if (Array.isArray(liveMessages) && liveMessages.length > 0 && target.messageId) {
1206
+ const msgIdx = liveMessages.findIndex((m) => m?.id === target.messageId);
1207
+ if (msgIdx !== -1) {
1208
+ ratio =
1209
+ liveMessages.length > 1 ? msgIdx / (liveMessages.length - 1) : 0;
1210
+ const liveMsg = liveMessages[msgIdx] as unknown as Record<string, unknown>;
1211
+ if (typeof liveMsg?.text === "string") {
1212
+ const liveNeedle = normalizeSearchNeedle(liveMsg.text).slice(0, 48);
1213
+ if (liveNeedle.length >= 6 && !needles.includes(liveNeedle)) {
1214
+ needles.unshift(liveNeedle);
1215
+ }
1216
+ }
1217
+ }
1218
+ }
1219
+ } catch {
1220
+ // ignore data store lookup errors
1221
+ }
1222
+
1223
+ // 3. Walk descendants of scrollBox.content to locate the matching message node
1224
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1225
+ let idMatchNode: any = null;
1226
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1227
+ const textMatchesByTier: Array<Array<any>> = needles.map(() => []);
1228
+
1229
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1230
+ const walkContent = (node: any) => {
1231
+ if (!node || node.isDestroyed || node.visible === false) return;
1232
+ if (
1233
+ !idMatchNode &&
1234
+ target.messageId &&
1235
+ typeof node.id === "string" &&
1236
+ (node.id === target.messageId || node.id.includes(target.messageId))
1237
+ ) {
1238
+ idMatchNode = node;
1239
+ }
1240
+
1241
+ const rawText = extractRenderableText(node);
1242
+ if (rawText) {
1243
+ const normalized = rawText.replace(/\s+/g, " ").toLowerCase();
1244
+ for (let i = 0; i < needles.length; i++) {
1245
+ if (normalized.includes(needles[i])) {
1246
+ textMatchesByTier[i].push(node);
1247
+ break;
1248
+ }
1249
+ }
1250
+ }
1251
+
1252
+ const children =
1253
+ typeof node.getChildren === "function" ? node.getChildren() : [];
1254
+ for (const child of children) {
1255
+ walkContent(child);
1256
+ }
1257
+ };
1258
+ walkContent(scrollBox.content);
1259
+
1260
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1261
+ let targetNode: any = idMatchNode;
1262
+ if (!targetNode) {
1263
+ const candidates = textMatchesByTier.find((tier) => tier.length > 0);
1264
+ if (candidates && candidates.length > 0) {
1265
+ if (candidates.length === 1 || ratio === undefined) {
1266
+ targetNode = candidates[0];
1267
+ } else {
1268
+ const totalHeight = Math.max(1, scrollBox.scrollHeight || 1);
1269
+ const contentTop = scrollBox.content?.y ?? 0;
1270
+ let bestDist = Infinity;
1271
+ for (const candidate of candidates) {
1272
+ const relY = Math.max(0, (candidate.y ?? 0) - contentTop) / totalHeight;
1273
+ const dist = Math.abs(relY - ratio);
1274
+ if (dist < bestDist) {
1275
+ bestDist = dist;
1276
+ targetNode = candidate;
1277
+ }
1278
+ }
1279
+ }
1280
+ }
1281
+ }
1282
+
1283
+ const applyScrollToNode = (
1284
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1285
+ node: any
1286
+ ) => {
1287
+ const viewportTop = scrollBox.viewport?.y ?? 0;
1288
+ const viewportHeight = scrollBox.viewport?.height ?? 20;
1289
+ const desiredScreenY = viewportTop + Math.floor(viewportHeight * 0.22);
1290
+ const dy = (node.y ?? 0) - desiredScreenY;
1291
+ scrollBox._hasManualScroll = true;
1292
+ if (dy !== 0) {
1293
+ scrollBox.scrollBy({ x: 0, y: dy });
1294
+ }
1295
+ scrollBox._hasManualScroll = true;
1296
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1297
+ (context.renderer as any)?.requestRender?.();
1298
+ };
1299
+
1300
+ if (targetNode) {
1301
+ applyScrollToNode(targetNode);
1302
+ if (activeScrollTimeout) clearTimeout(activeScrollTimeout);
1303
+ activeScrollTimeout = setTimeout(() => {
1304
+ activeScrollTimeout = null;
1305
+ try {
1306
+ applyScrollToNode(targetNode);
1307
+ } catch {
1308
+ // ignore
1309
+ }
1310
+ }, 120);
1311
+ return true;
1312
+ }
1313
+
1314
+ // Fallback when text is inside a collapsed tool output and layout has stabilized
1315
+ if (attempts >= 6 && ratio !== undefined) {
1316
+ const childIdx = Math.max(
1317
+ 0,
1318
+ Math.min(topChildren.length - 1, Math.round(ratio * (topChildren.length - 1)))
1319
+ );
1320
+ const approxNode = topChildren[childIdx];
1321
+ if (approxNode) {
1322
+ applyScrollToNode(approxNode);
1323
+ return true;
1324
+ }
1325
+ }
1326
+
1327
+ return false;
1328
+ };
1329
+
1330
+ activeScrollInterval = setInterval(() => {
1331
+ attempts++;
1332
+ if (tryScroll() || attempts >= maxAttempts) {
1333
+ if (activeScrollInterval) {
1334
+ clearInterval(activeScrollInterval);
1335
+ activeScrollInterval = null;
1336
+ }
1337
+ }
1338
+ }, 60);
1339
+ }
1340
+
1341
+ async function openFallbackSelectDialog(
1342
+ context: TuiPluginContext,
1343
+ initialQuery: string,
1344
+ currentDirectory: string
1345
+ ) {
1346
+ const index = await loadSessionIndex(false);
1347
+ const matches = searchSessionIndex(index, initialQuery, {
1348
+ currentDirectory,
1349
+ limit: 50,
1350
+ });
1351
+
1352
+ if (!matches.length) {
1353
+ context.ui.toast.show({
1354
+ title: "Session Search",
1355
+ message: initialQuery
1356
+ ? `No sessions matched "${initialQuery}".`
1357
+ : "No sessions found.",
1358
+ variant: "warning",
1359
+ });
1360
+ return;
1361
+ }
1362
+
1363
+ const options = matches.map((m) => ({
1364
+ title: m.session.title,
1365
+ value: m.session.id,
1366
+ description: `[${m.matchBadge}] ${m.bestSnippet}`,
1367
+ footer: `${formatRelativeTime(m.session.timeUpdated)} · ${context.ui.format.path(m.session.directory || "")}`,
1368
+ }));
1369
+
1370
+ const selectedId = await context.ui.dialog.select<string>({
1371
+ title: initialQuery ? `Session Search: "${initialQuery}"` : "Session Search",
1372
+ placeholder: "Filter matching sessions...",
1373
+ options,
1374
+ });
1375
+
1376
+ if (selectedId) {
1377
+ context.ui.router.navigate({
1378
+ type: "session",
1379
+ sessionID: selectedId,
1380
+ });
1381
+ }
1382
+ }
1383
+
1384
+ export default {
1385
+ id: "opencode-local-search",
1386
+ async setup(context: TuiPluginContext) {
1387
+ if (!context?.ui) {
1388
+ return;
1389
+ }
1390
+ const currentDirectory = context.location?.directory ?? process.cwd();
1391
+ let renderDialog: ReturnType<typeof createTuiRenderer> | null = null;
1392
+ try {
1393
+ renderDialog = createTuiRenderer();
1394
+ } catch {
1395
+ renderDialog = null;
1396
+ }
1397
+
1398
+ const openSearchPopup = async (rawArgs?: unknown) => {
1399
+ const initialQuery =
1400
+ typeof rawArgs === "string"
1401
+ ? rawArgs.trim()
1402
+ : typeof (rawArgs as { arguments?: unknown } | undefined)?.arguments === "string"
1403
+ ? ((rawArgs as { arguments: string }).arguments).trim()
1404
+ : "";
1405
+ if (!renderDialog) {
1406
+ await openFallbackSelectDialog(context, initialQuery, currentDirectory);
1407
+ return;
1408
+ }
1409
+
1410
+ try {
1411
+ context.ui.dialog.show(() =>
1412
+ renderDialog({
1413
+ context,
1414
+ initialQuery,
1415
+ currentDirectory,
1416
+ close: () => context.ui.dialog.clear(),
1417
+ navigateSession: (
1418
+ sessionId: string,
1419
+ target?: SearchNavigationTarget
1420
+ ) => {
1421
+ context.ui.dialog.clear();
1422
+ context.ui.router.navigate({
1423
+ type: "session",
1424
+ sessionID: sessionId,
1425
+ });
1426
+ scrollToMatchedMessage(context, sessionId, target);
1427
+ },
1428
+ })
1429
+ );
1430
+ context.ui.dialog.set({
1431
+ size: "xlarge",
1432
+ centered: true,
1433
+ });
1434
+ } catch {
1435
+ await openFallbackSelectDialog(context, initialQuery, currentDirectory);
1436
+ }
1437
+ };
1438
+
1439
+ let layerRegistered = false;
1440
+ context.ui.slot({
1441
+ append: "app",
1442
+ render() {
1443
+ if (!layerRegistered) {
1444
+ layerRegistered = true;
1445
+ context.keymap.layer(() => ({
1446
+ mode: "global",
1447
+ commands: [
1448
+ {
1449
+ id: "session.history.search",
1450
+ title: "Search session history...",
1451
+ description:
1452
+ "Interactive zero-token popup to search past sessions (multi-term, regex, fuzzy, role/date/file/tool filters)",
1453
+ category: "Session",
1454
+ palette: true,
1455
+ slash: {
1456
+ name: "search",
1457
+ arguments: true,
1458
+ },
1459
+ run: (input) => {
1460
+ void openSearchPopup(input);
1461
+ },
1462
+ },
1463
+ ],
1464
+ }));
1465
+ }
1466
+ return null;
1467
+ },
1468
+ });
1469
+ },
1470
+ };