@nandoblanco/opencode-local-search 1.0.2 → 1.2.0

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/gui.tsx ADDED
@@ -0,0 +1,1251 @@
1
+ import {
2
+ Command,
3
+ MenuItem,
4
+ Panel,
5
+ Plugin,
6
+ Style,
7
+ type PanelTab,
8
+ type PluginContext,
9
+ type UiMenuEntry,
10
+ } from "@opencode/plugin/gui"
11
+ import {
12
+ For,
13
+ Show,
14
+ createEffect,
15
+ createMemo,
16
+ createSignal,
17
+ onCleanup,
18
+ } from "solid-js"
19
+ import css from "./gui.css?inline"
20
+ import {
21
+ SearchRpc,
22
+ type RpcParsedQueryInfo,
23
+ type RpcSessionMatch,
24
+ } from "./rpc.ts"
25
+ import type {
26
+ DatePreset,
27
+ RoleFilter,
28
+ ScopeFilter,
29
+ SearchMode,
30
+ SearchSort,
31
+ } from "./search.ts"
32
+ import { SEARCH_SORT_LABELS } from "./sort.ts"
33
+
34
+ const ROLE_ORDER: RoleFilter[] = ["all", "user", "assistant", "shell"]
35
+ const DATE_ORDER: DatePreset[] = ["all", "today", "yesterday", "7d", "30d"]
36
+ const MODE_ORDER: SearchMode[] = ["smart", "fuzzy", "regex"]
37
+
38
+ const DATE_LABELS: Record<DatePreset, string> = {
39
+ all: "Any time",
40
+ today: "Today",
41
+ yesterday: "Yesterday",
42
+ "7d": "Last 7 days",
43
+ "30d": "Last 30 days",
44
+ }
45
+
46
+ const MODE_LABELS: Record<SearchMode, string> = {
47
+ smart: "Smart",
48
+ fuzzy: "Fuzzy",
49
+ regex: "Regex",
50
+ }
51
+
52
+ const ROLE_LABELS: Record<RoleFilter, string> = {
53
+ all: "All roles",
54
+ user: "User",
55
+ assistant: "Assistant",
56
+ shell: "Shell",
57
+ }
58
+
59
+ function formatRelativeTime(timestampMs: number, nowMs = Date.now()): string {
60
+ if (!timestampMs || timestampMs <= 0) return ""
61
+ const diffSec = Math.max(0, Math.floor((nowMs - timestampMs) / 1000))
62
+ if (diffSec < 60) return "just now"
63
+ const diffMin = Math.floor(diffSec / 60)
64
+ if (diffMin < 60) return `${diffMin}m ago`
65
+ const diffHr = Math.floor(diffMin / 60)
66
+ if (diffHr < 24) return `${diffHr}h ago`
67
+ const diffDays = Math.floor(diffHr / 24)
68
+ if (diffDays < 30) return `${diffDays}d ago`
69
+ const d = new Date(timestampMs)
70
+ const yyyy = d.getFullYear()
71
+ const mm = String(d.getMonth() + 1).padStart(2, "0")
72
+ const dd = String(d.getDate()).padStart(2, "0")
73
+ return `${yyyy}-${mm}-${dd}`
74
+ }
75
+
76
+ function formatDateFull(ts: number): string {
77
+ if (!ts) return "unknown"
78
+ const d = new Date(ts)
79
+ const yyyy = d.getFullYear()
80
+ const mm = String(d.getMonth() + 1).padStart(2, "0")
81
+ const dd = String(d.getDate()).padStart(2, "0")
82
+ const hh = String(d.getHours()).padStart(2, "0")
83
+ const min = String(d.getMinutes()).padStart(2, "0")
84
+ return `${yyyy}-${mm}-${dd} ${hh}:${min}`
85
+ }
86
+
87
+ function shortFolder(dir: string): string {
88
+ if (!dir) return "Global"
89
+ const parts = dir.replace(/\\/g, "/").split("/").filter(Boolean)
90
+ if (parts.length <= 2) return parts.join("/")
91
+ return `${parts.slice(-2).join("/")}`
92
+ }
93
+
94
+ interface HighlightSegment {
95
+ text: string
96
+ match: boolean
97
+ }
98
+
99
+ function splitHighlightSegments(
100
+ text: string,
101
+ highlightTerms: string[],
102
+ regexPattern?: string,
103
+ regexFlags?: string,
104
+ ): HighlightSegment[] {
105
+ if (!text) return [{ text: "", match: false }]
106
+
107
+ if (regexPattern) {
108
+ try {
109
+ const flags = regexFlags?.includes("g")
110
+ ? regexFlags
111
+ : `${regexFlags ?? "i"}g`
112
+ const globalRe = new RegExp(regexPattern, flags)
113
+ const segments: HighlightSegment[] = []
114
+ let lastIdx = 0
115
+ let m: RegExpExecArray | null
116
+ let safety = 0
117
+ while ((m = globalRe.exec(text)) !== null && safety++ < 40) {
118
+ if (m[0].length === 0) {
119
+ globalRe.lastIndex++
120
+ continue
121
+ }
122
+ if (m.index > lastIdx) {
123
+ segments.push({ text: text.slice(lastIdx, m.index), match: false })
124
+ }
125
+ segments.push({ text: m[0], match: true })
126
+ lastIdx = m.index + m[0].length
127
+ }
128
+ if (lastIdx < text.length) {
129
+ segments.push({ text: text.slice(lastIdx), match: false })
130
+ }
131
+ return segments.length > 0 ? segments : [{ text, match: false }]
132
+ } catch {
133
+ return [{ text, match: false }]
134
+ }
135
+ }
136
+
137
+ const cleanTerms = highlightTerms
138
+ .map((t) => t.trim().toLowerCase())
139
+ .filter((t) => t.length > 0)
140
+ .sort((a, b) => b.length - a.length)
141
+
142
+ if (cleanTerms.length === 0) return [{ text, match: false }]
143
+
144
+ const lower = text.toLowerCase()
145
+ const segments: HighlightSegment[] = []
146
+ let cursor = 0
147
+
148
+ while (cursor < text.length) {
149
+ let bestPos = -1
150
+ let bestLen = 0
151
+ for (const term of cleanTerms) {
152
+ const idx = lower.indexOf(term, cursor)
153
+ if (idx !== -1 && (bestPos === -1 || idx < bestPos)) {
154
+ bestPos = idx
155
+ bestLen = term.length
156
+ }
157
+ }
158
+ if (bestPos === -1) {
159
+ segments.push({ text: text.slice(cursor), match: false })
160
+ break
161
+ }
162
+ if (bestPos > cursor) {
163
+ segments.push({ text: text.slice(cursor, bestPos), match: false })
164
+ }
165
+ segments.push({
166
+ text: text.slice(bestPos, bestPos + bestLen),
167
+ match: true,
168
+ })
169
+ cursor = bestPos + bestLen
170
+ }
171
+
172
+ return segments.length > 0 ? segments : [{ text, match: false }]
173
+ }
174
+
175
+ function HighlightedText(props: {
176
+ text: string
177
+ terms: string[]
178
+ regexPattern?: string
179
+ regexFlags?: string
180
+ }) {
181
+ const segments = createMemo(() =>
182
+ splitHighlightSegments(
183
+ props.text,
184
+ props.terms,
185
+ props.regexPattern,
186
+ props.regexFlags,
187
+ ),
188
+ )
189
+ return (
190
+ <>
191
+ <For each={segments()}>
192
+ {(seg) =>
193
+ seg.match ? <mark class="ols-mark">{seg.text}</mark> : seg.text
194
+ }
195
+ </For>
196
+ </>
197
+ )
198
+ }
199
+
200
+ function resolveServerId(ctx: PluginContext): string {
201
+ const active = ctx.sessions.current()
202
+ if (active?.server?.id) return active.server.id
203
+ const list = ctx.servers.list()
204
+ for (const id of list) {
205
+ if (ctx.servers.get(id)?.builtin) return id
206
+ }
207
+ return list[0] ?? "sidecar"
208
+ }
209
+
210
+ function roleLabel(role: string): string {
211
+ if (role === "user") return "You"
212
+ if (role === "assistant") return "Assistant"
213
+ if (role === "shell") return "Command"
214
+ if (role === "title") return "Title"
215
+ return role
216
+ }
217
+
218
+ // Module-level signal so commands/intercepted clicks can drive the shared
219
+ // search panel's query without re-mounting SearchSurface (no modals).
220
+ const [olsPanelQuery, setOlsPanelQuery] = createSignal("")
221
+
222
+ function SearchSurface(props: {
223
+ ctx: PluginContext
224
+ initialQuery?: string
225
+ variant: "panel" | "modal"
226
+ onClose?: () => void
227
+ }) {
228
+ const ui = props.ctx.ui
229
+ const [query, setQuery] = createSignal(props.initialQuery ?? "")
230
+ const [scope, setScope] = createSignal<ScopeFilter>(
231
+ props.ctx.sessions.current()?.directory ? "project" : "all",
232
+ )
233
+ const [role, setRole] = createSignal<RoleFilter>("all")
234
+ const [datePreset, setDatePreset] = createSignal<DatePreset>("all")
235
+ const [mode, setMode] = createSignal<SearchMode>("smart")
236
+ const [sort, setSort] = createSignal<SearchSort>("updated")
237
+ const [restoring, setRestoring] = createSignal(false)
238
+ const [selectedIndex, setSelectedIndex] = createSignal(0)
239
+ const [selectedMatchIdx, setSelectedMatchIdx] = createSignal(0)
240
+ const [activePane, setActivePane] = createSignal<"sessions" | "matches">(
241
+ "sessions",
242
+ )
243
+ const [loading, setLoading] = createSignal(true)
244
+ const [refreshing, setRefreshing] = createSignal(false)
245
+ const [errorMsg, setErrorMsg] = createSignal<string | null>(null)
246
+ const [totalSessions, setTotalSessions] = createSignal(0)
247
+ const [results, setResults] = createSignal<RpcSessionMatch[]>([])
248
+ const [parsedInfo, setParsedInfo] = createSignal<RpcParsedQueryInfo | null>(
249
+ null,
250
+ )
251
+
252
+ // External openers (commands, intercepted clicks) push the query here.
253
+ createEffect(() => {
254
+ const q = olsPanelQuery()
255
+ if (q) setQuery(q)
256
+ })
257
+
258
+ let reqSeq = 0
259
+ let debounceTimer: ReturnType<typeof setTimeout> | undefined
260
+
261
+ const currentDirectory = createMemo(
262
+ () => props.ctx.sessions.current()?.directory ?? "",
263
+ )
264
+
265
+ const colorScheme = createMemo(() => props.ctx.appearance.mode())
266
+
267
+ async function runQuery(forceReload = false) {
268
+ const seq = ++reqSeq
269
+ if (forceReload) setRefreshing(true)
270
+ setLoading(true)
271
+ setErrorMsg(null)
272
+
273
+ try {
274
+ const client =
275
+ props.ctx.sessions.current()?.server?.client ??
276
+ props.ctx.servers.get(resolveServerId(props.ctx))?.client ??
277
+ props.ctx.client
278
+ const response = await client.rpc(SearchRpc).query({
279
+ query: query(),
280
+ scope: scope(),
281
+ currentDirectory: currentDirectory(),
282
+ role: role(),
283
+ datePreset: datePreset(),
284
+ mode: mode(),
285
+ sort: sort(),
286
+ limit: 60,
287
+ forceReload,
288
+ })
289
+ if (seq !== reqSeq) return
290
+ setTotalSessions(response.totalSessions)
291
+ setResults(response.results)
292
+ setParsedInfo(response.parsed)
293
+ setSelectedIndex((prev) =>
294
+ Math.max(0, Math.min(prev, Math.max(0, response.results.length - 1))),
295
+ )
296
+ setSelectedMatchIdx(0)
297
+ if (forceReload) {
298
+ props.ctx.toast.show({
299
+ variant: "success",
300
+ title: `Refreshed ${response.totalSessions} sessions`,
301
+ })
302
+ }
303
+ } catch (err) {
304
+ if (seq !== reqSeq) return
305
+ setErrorMsg(
306
+ err instanceof Error ? err.message : "Failed to query session index",
307
+ )
308
+ } finally {
309
+ if (seq === reqSeq) {
310
+ setLoading(false)
311
+ setRefreshing(false)
312
+ }
313
+ }
314
+ }
315
+
316
+ createEffect(() => {
317
+ void query()
318
+ void scope()
319
+ void role()
320
+ void datePreset()
321
+ void mode()
322
+ void sort()
323
+ void currentDirectory()
324
+
325
+ if (debounceTimer) clearTimeout(debounceTimer)
326
+ debounceTimer = setTimeout(() => {
327
+ void runQuery(false)
328
+ }, 16)
329
+ })
330
+
331
+ onCleanup(() => {
332
+ if (debounceTimer) clearTimeout(debounceTimer)
333
+ })
334
+
335
+ const selectedSession = createMemo<RpcSessionMatch | undefined>(
336
+ () => results()[selectedIndex()] ?? results()[0],
337
+ )
338
+
339
+ const highlightTerms = createMemo(() => {
340
+ const p = parsedInfo()
341
+ const base = p ? [...p.terms, ...p.fuzzyTerms] : []
342
+ const matched = selectedSession()?.matches[selectedMatchIdx()]?.matchedTerm
343
+ if (matched && !base.includes(matched)) base.push(matched)
344
+ return base
345
+ })
346
+
347
+ const activeFilterCount = createMemo(() => {
348
+ let count = 0
349
+ if (role() !== "all") count++
350
+ if (datePreset() !== "all") count++
351
+ if (mode() !== "smart") count++
352
+ return count
353
+ })
354
+
355
+ const filterMenuItems = createMemo<UiMenuEntry[]>(() => [
356
+ {
357
+ type: "group",
358
+ label: "Search Mode",
359
+ items: MODE_ORDER.map((m) => ({
360
+ label: MODE_LABELS[m],
361
+ icon: mode() === m ? "check-small" : undefined,
362
+ onSelect: () => {
363
+ setMode(m)
364
+ setSelectedIndex(0)
365
+ },
366
+ })),
367
+ },
368
+ { type: "separator" },
369
+ {
370
+ type: "group",
371
+ label: "Message Role",
372
+ items: ROLE_ORDER.map((r) => ({
373
+ label: ROLE_LABELS[r],
374
+ icon: role() === r ? "check-small" : undefined,
375
+ onSelect: () => {
376
+ setRole(r)
377
+ setSelectedIndex(0)
378
+ },
379
+ })),
380
+ },
381
+ { type: "separator" },
382
+ {
383
+ type: "group",
384
+ label: "Time Range",
385
+ items: DATE_ORDER.map((d) => ({
386
+ label: DATE_LABELS[d],
387
+ icon: datePreset() === d ? "check-small" : undefined,
388
+ onSelect: () => {
389
+ setDatePreset(d)
390
+ setSelectedIndex(0)
391
+ },
392
+ })),
393
+ },
394
+ { type: "separator" },
395
+ {
396
+ label: "Reset filters",
397
+ disabled: activeFilterCount() === 0,
398
+ onSelect: () => {
399
+ setMode("smart")
400
+ setRole("all")
401
+ setDatePreset("all")
402
+ setSelectedIndex(0)
403
+ },
404
+ },
405
+ ])
406
+
407
+ function toggleScope() {
408
+ setScope((prev) => (prev === "project" ? "all" : "project"))
409
+ setSelectedIndex(0)
410
+ }
411
+
412
+ function cycleRole() {
413
+ setRole((prev) => {
414
+ const idx = ROLE_ORDER.indexOf(prev)
415
+ return ROLE_ORDER[(idx + 1) % ROLE_ORDER.length] ?? "all"
416
+ })
417
+ setSelectedIndex(0)
418
+ }
419
+
420
+ function cycleDatePreset() {
421
+ setDatePreset((prev) => {
422
+ const idx = DATE_ORDER.indexOf(prev)
423
+ return DATE_ORDER[(idx + 1) % DATE_ORDER.length] ?? "all"
424
+ })
425
+ setSelectedIndex(0)
426
+ }
427
+
428
+ function cycleMode() {
429
+ setMode((prev) => {
430
+ const idx = MODE_ORDER.indexOf(prev)
431
+ return MODE_ORDER[(idx + 1) % MODE_ORDER.length] ?? "smart"
432
+ })
433
+ setSelectedIndex(0)
434
+ }
435
+
436
+ function openSession(session: RpcSessionMatch | undefined) {
437
+ if (!session) return
438
+ const serverId = resolveServerId(props.ctx)
439
+ props.ctx.tabs.open({ server: serverId, id: session.id }, { focus: true })
440
+ props.onClose?.()
441
+ }
442
+
443
+ async function copySessionId(session: RpcSessionMatch | undefined) {
444
+ if (!session) return
445
+ await props.ctx.system.copy(session.id)
446
+ props.ctx.toast.show({
447
+ variant: "success",
448
+ title: "Copied session ID",
449
+ description: session.id,
450
+ })
451
+ }
452
+
453
+ async function unarchiveSession(session: RpcSessionMatch) {
454
+ if (restoring()) return
455
+ setRestoring(true)
456
+ try {
457
+ const client = props.ctx.sessions.current()?.server?.client ??
458
+ props.ctx.servers.get(resolveServerId(props.ctx))?.client ?? props.ctx.client
459
+ await client.session.update({ sessionID: session.id, archived: false })
460
+ await runQuery(true)
461
+ } catch (err) {
462
+ props.ctx.toast.show({ variant: "error", title: "Unable to unarchive session", description: err instanceof Error ? err.message : String(err) })
463
+ } finally {
464
+ setRestoring(false)
465
+ }
466
+ }
467
+
468
+ function appendSyntaxToken(token: string) {
469
+ const cur = query().trim()
470
+ setQuery(cur ? `${cur} ${token}` : token)
471
+ }
472
+
473
+ function handleKeyDown(e: KeyboardEvent) {
474
+ if ((e.ctrlKey || e.altKey) && !e.shiftKey) {
475
+ const key = e.key.toLowerCase()
476
+ if (key === "p") {
477
+ e.preventDefault()
478
+ toggleScope()
479
+ return
480
+ }
481
+ if (key === "g") {
482
+ e.preventDefault()
483
+ cycleRole()
484
+ return
485
+ }
486
+ if (key === "t") {
487
+ e.preventDefault()
488
+ cycleDatePreset()
489
+ return
490
+ }
491
+ if (key === "r") {
492
+ e.preventDefault()
493
+ cycleMode()
494
+ return
495
+ }
496
+ if (key === "l") {
497
+ e.preventDefault()
498
+ void runQuery(true)
499
+ return
500
+ }
501
+ }
502
+
503
+ if (e.key === "Tab") {
504
+ e.preventDefault()
505
+ setActivePane((prev) => (prev === "sessions" ? "matches" : "sessions"))
506
+ return
507
+ }
508
+
509
+ const total = results().length
510
+ const matchCount = selectedSession()?.matches.length ?? 0
511
+
512
+ if (e.key === "ArrowDown") {
513
+ e.preventDefault()
514
+ if (activePane() === "matches" && matchCount > 0) {
515
+ setSelectedMatchIdx((i) => Math.min(matchCount - 1, i + 1))
516
+ } else if (total > 0) {
517
+ setSelectedIndex((i) => Math.min(total - 1, i + 1))
518
+ setSelectedMatchIdx(0)
519
+ }
520
+ return
521
+ }
522
+
523
+ if (e.key === "ArrowUp") {
524
+ e.preventDefault()
525
+ if (activePane() === "matches" && matchCount > 0) {
526
+ setSelectedMatchIdx((i) => Math.max(0, i - 1))
527
+ } else if (total > 0) {
528
+ setSelectedIndex((i) => Math.max(0, i - 1))
529
+ setSelectedMatchIdx(0)
530
+ }
531
+ return
532
+ }
533
+
534
+ if (e.key === "PageDown") {
535
+ e.preventDefault()
536
+ if (total > 0) {
537
+ setSelectedIndex((i) => Math.min(total - 1, i + 8))
538
+ setSelectedMatchIdx(0)
539
+ }
540
+ return
541
+ }
542
+
543
+ if (e.key === "PageUp") {
544
+ e.preventDefault()
545
+ if (total > 0) {
546
+ setSelectedIndex((i) => Math.max(0, i - 8))
547
+ setSelectedMatchIdx(0)
548
+ }
549
+ return
550
+ }
551
+
552
+ if (e.key === "Enter" && !e.shiftKey) {
553
+ e.preventDefault()
554
+ openSession(selectedSession())
555
+ }
556
+ }
557
+
558
+ return (
559
+ <div
560
+ class={`ols-root ols-root--${props.variant}`}
561
+ data-scheme={colorScheme()}
562
+ onKeyDown={handleKeyDown}
563
+ >
564
+ <div class="ols-header">
565
+ <div class="ols-input-wrap">
566
+ <ui.TextInput
567
+ type="search"
568
+ size="large"
569
+ label="Search session history"
570
+ value={query()}
571
+ onInput={(val) => {
572
+ setQuery(val)
573
+ setSelectedIndex(0)
574
+ setSelectedMatchIdx(0)
575
+ }}
576
+ onSubmit={() => openSession(selectedSession())}
577
+ placeholder='Search conversations, "exact phrase", fuzzy~, /regex/i, role:user, tool:shell...'
578
+ invalid={Boolean(parsedInfo()?.regexError)}
579
+ autofocus
580
+ />
581
+ </div>
582
+
583
+ <div class="ols-controls-bar">
584
+ <div class="ols-controls-left">
585
+ <div class="ols-segment" role="group" aria-label="Search scope">
586
+ <button
587
+ type="button"
588
+ class={`ols-segment-btn ${
589
+ scope() === "project" ? "ols-segment-btn--active" : ""
590
+ }`}
591
+ onClick={() => {
592
+ setScope("project")
593
+ setSelectedIndex(0)
594
+ }}
595
+ title={
596
+ currentDirectory()
597
+ ? `Current project (${currentDirectory()})`
598
+ : "Current project"
599
+ }
600
+ >
601
+ <ui.Icon name="folder" size="small" />
602
+ <span>
603
+ {currentDirectory()
604
+ ? shortFolder(currentDirectory())
605
+ : "Project"}
606
+ </span>
607
+ </button>
608
+ <button
609
+ type="button"
610
+ class={`ols-segment-btn ${
611
+ scope() === "all" ? "ols-segment-btn--active" : ""
612
+ }`}
613
+ onClick={() => {
614
+ setScope("all")
615
+ setSelectedIndex(0)
616
+ }}
617
+ >
618
+ <span>All workspaces</span>
619
+ </button>
620
+ </div>
621
+
622
+ <ui.Menu
623
+ label={`Sort: ${SEARCH_SORT_LABELS[sort()]}`}
624
+ trigger="button"
625
+ items={(Object.entries(SEARCH_SORT_LABELS) as [SearchSort, string][]).map(([value, label]) => ({
626
+ label,
627
+ icon: sort() === value ? "check-small" : undefined,
628
+ onSelect: () => { setSort(value); setSelectedIndex(0) },
629
+ }))}
630
+ />
631
+
632
+ <ui.Menu
633
+ label={
634
+ activeFilterCount() > 0
635
+ ? `Filters (${activeFilterCount()})`
636
+ : "Filters"
637
+ }
638
+ icon="sliders"
639
+ trigger="button"
640
+ items={filterMenuItems()}
641
+ />
642
+
643
+ <Show when={mode() !== "smart"}>
644
+ <button
645
+ type="button"
646
+ class="ols-active-pill"
647
+ onClick={() => setMode("smart")}
648
+ title="Click to reset search mode"
649
+ >
650
+ <span>{MODE_LABELS[mode()]}</span>
651
+ <ui.Icon name="close-small" size="small" />
652
+ </button>
653
+ </Show>
654
+
655
+ <Show when={role() !== "all"}>
656
+ <button
657
+ type="button"
658
+ class="ols-active-pill"
659
+ onClick={() => setRole("all")}
660
+ title="Click to reset role filter"
661
+ >
662
+ <span>{ROLE_LABELS[role()]}</span>
663
+ <ui.Icon name="close-small" size="small" />
664
+ </button>
665
+ </Show>
666
+
667
+ <Show when={datePreset() !== "all"}>
668
+ <button
669
+ type="button"
670
+ class="ols-active-pill"
671
+ onClick={() => setDatePreset("all")}
672
+ title="Click to reset time filter"
673
+ >
674
+ <span>{DATE_LABELS[datePreset()]}</span>
675
+ <ui.Icon name="close-small" size="small" />
676
+ </button>
677
+ </Show>
678
+
679
+ <Show when={parsedInfo()?.regexError}>
680
+ {(err) => <span class="ols-error-pill">{err()}</span>}
681
+ </Show>
682
+ </div>
683
+
684
+ <div class="ols-controls-right">
685
+ <span class="ols-status-count">
686
+ <Show when={!loading()} fallback={<ui.Loader size="small" />}>
687
+ {results().length} of {totalSessions()} sessions
688
+ </Show>
689
+ </span>
690
+
691
+ <ui.Tooltip value="Refresh index" keys={["Ctrl", "L"]}>
692
+ <ui.IconButton
693
+ icon="refresh"
694
+ label="Refresh index"
695
+ variant="ghost"
696
+ size="small"
697
+ busy={refreshing()}
698
+ onClick={() => void runQuery(true)}
699
+ />
700
+ </ui.Tooltip>
701
+ </div>
702
+ </div>
703
+ </div>
704
+
705
+ <Show when={errorMsg()}>
706
+ {(err) => (
707
+ <div class="ols-empty">
708
+ <div class="ols-empty-title">Unable to search sessions</div>
709
+ <div class="ols-empty-sub">{err()}</div>
710
+ </div>
711
+ )}
712
+ </Show>
713
+
714
+ <Show when={!errorMsg()}>
715
+ <div class="ols-split">
716
+ <Show when={loading()}>
717
+ <div class="ols-loading-center" role="status" aria-live="polite">
718
+ <div class="ols-loading-pill">
719
+ <span class="ols-spinner" aria-hidden="true" />
720
+ <span>Searching...</span>
721
+ </div>
722
+ </div>
723
+ </Show>
724
+ <div
725
+ class={`ols-column ols-column--list ${
726
+ activePane() === "sessions" ? "ols-column--active" : ""
727
+ }`}
728
+ onClick={() => setActivePane("sessions")}
729
+ >
730
+ <div class="ols-list-scroll">
731
+ <Show
732
+ when={results().length > 0}
733
+ fallback={
734
+ <Show when={!loading()}>
735
+ <div class="ols-empty">
736
+ <div class="ols-empty-title">No matching sessions</div>
737
+ <div class="ols-empty-sub">
738
+ <Show
739
+ when={scope() === "project"}
740
+ fallback="Try Fuzzy mode or fewer search terms."
741
+ >
742
+ No hits in this workspace. Switch to{" "}
743
+ <button
744
+ type="button"
745
+ class="ols-inline-link"
746
+ onClick={toggleScope}
747
+ >
748
+ All workspaces
749
+ </button>{" "}
750
+ to search everywhere.
751
+ </Show>
752
+ </div>
753
+ </div>
754
+ </Show>
755
+ }
756
+ >
757
+ <For each={results()}>
758
+ {(item, idx) => {
759
+ const isSelected = () => idx() === selectedIndex()
760
+ return (
761
+ <button
762
+ type="button"
763
+ class={`ols-row ${
764
+ isSelected() ? "ols-row--selected" : ""
765
+ }`}
766
+ onClick={() => {
767
+ setSelectedIndex(idx())
768
+ setSelectedMatchIdx(0)
769
+ setActivePane("sessions")
770
+ }}
771
+ onDblClick={() => openSession(item)}
772
+ >
773
+ <div class="ols-row-top">
774
+ <span class="ols-row-title">
775
+ <HighlightedText
776
+ text={item.title || "Untitled session"}
777
+ terms={highlightTerms()}
778
+ regexPattern={parsedInfo()?.regexPattern}
779
+ regexFlags={parsedInfo()?.regexFlags}
780
+ />
781
+ </span>
782
+ <span class="ols-row-time">
783
+ {formatRelativeTime(item.timeUpdated)}
784
+ </span>
785
+ </div>
786
+
787
+ <Show when={item.bestSnippet}>
788
+ <div class="ols-row-snippet">
789
+ <HighlightedText
790
+ text={item.bestSnippet}
791
+ terms={highlightTerms()}
792
+ regexPattern={parsedInfo()?.regexPattern}
793
+ regexFlags={parsedInfo()?.regexFlags}
794
+ />
795
+ </div>
796
+ </Show>
797
+
798
+ <div class="ols-row-meta">
799
+ <Show when={item.archived}><span class="ols-row-hit-badge">Archived</span></Show>
800
+ <Show when={sort() === "context" || sort() === "tokens"}>
801
+ <span>{sort() === "context" ? "Context" : "Total"}: {(sort() === "context" ? item.contextTokens : item.totalTokens)?.toLocaleString() ?? "Not recorded"}</span>
802
+ </Show>
803
+ <Show when={query().trim().length > 0}>
804
+ <span class="ols-row-hit-badge">
805
+ {item.matchBadge}
806
+ </span>
807
+ </Show>
808
+ <Show when={scope() === "all" && item.directory}>
809
+ <span class="ols-row-folder">
810
+ {shortFolder(item.directory)}
811
+ </span>
812
+ </Show>
813
+ <span>{item.entryCount} messages</span>
814
+ </div>
815
+ </button>
816
+ )
817
+ }}
818
+ </For>
819
+ </Show>
820
+ </div>
821
+ </div>
822
+
823
+ <div
824
+ class={`ols-column ols-column--detail ${
825
+ activePane() === "matches" ? "ols-column--active" : ""
826
+ }`}
827
+ onClick={() => setActivePane("matches")}
828
+ >
829
+ <Show
830
+ when={selectedSession()}
831
+ fallback={
832
+ <div class="ols-empty">
833
+ <div class="ols-empty-sub">
834
+ Select a session to inspect conversation matches.
835
+ </div>
836
+ </div>
837
+ }
838
+ >
839
+ {(session) => (
840
+ <>
841
+ <div class="ols-detail-header">
842
+ <div class="ols-detail-heading">
843
+ <div class="ols-detail-title">{session().title}</div>
844
+ <div class="ols-detail-meta">
845
+ <Show when={session().archived}><span>Archived</span></Show>
846
+ <span>{session().directory || "Global"}</span>
847
+ <span>·</span>
848
+ <span>{formatDateFull(session().timeUpdated)}</span>
849
+ </div>
850
+ </div>
851
+
852
+ <div class="ols-detail-actions">
853
+ <Show when={session().archived}>
854
+ <ui.Button size="small" busy={restoring()} onClick={() => void unarchiveSession(session())}>Unarchive</ui.Button>
855
+ </Show>
856
+ <ui.Tooltip value="Copy session ID">
857
+ <ui.IconButton
858
+ icon="copy"
859
+ label="Copy session ID"
860
+ variant="ghost"
861
+ size="small"
862
+ onClick={() => void copySessionId(session())}
863
+ />
864
+ </ui.Tooltip>
865
+ <ui.Button
866
+ variant="contrast"
867
+ size="small"
868
+ icon="square-arrow-top-right"
869
+ onClick={() => openSession(session())}
870
+ >
871
+ Open
872
+ </ui.Button>
873
+ </div>
874
+ </div>
875
+
876
+ <Show
877
+ when={
878
+ query().trim().length === 0 &&
879
+ props.variant === "modal"
880
+ }
881
+ >
882
+ <div class="ols-quick-bar">
883
+ <span class="ols-quick-label">Try:</span>
884
+ <button
885
+ type="button"
886
+ class="ols-quick-chip"
887
+ onClick={() => appendSyntaxToken("role:user")}
888
+ >
889
+ role:user
890
+ </button>
891
+ <button
892
+ type="button"
893
+ class="ols-quick-chip"
894
+ onClick={() => appendSyntaxToken("tool:shell")}
895
+ >
896
+ tool:shell
897
+ </button>
898
+ <button
899
+ type="button"
900
+ class="ols-quick-chip"
901
+ onClick={() => appendSyntaxToken("in:title")}
902
+ >
903
+ in:title
904
+ </button>
905
+ <button
906
+ type="button"
907
+ class="ols-quick-chip"
908
+ onClick={() => appendSyntaxToken("since:7d")}
909
+ >
910
+ since:7d
911
+ </button>
912
+ </div>
913
+ </Show>
914
+
915
+ <div class="ols-detail-scroll">
916
+ <Show
917
+ when={session().matches.length > 0}
918
+ fallback={
919
+ <div class="ols-timeline">
920
+ <For each={session().recentEntries}>
921
+ {(entry) => (
922
+ <div
923
+ class="ols-turn"
924
+ onClick={() => openSession(session())}
925
+ >
926
+ <div class="ols-turn-header">
927
+ <span
928
+ class={`ols-turn-author ols-turn-author--${entry.role}`}
929
+ >
930
+ {roleLabel(entry.role)}
931
+ </span>
932
+ <Show when={entry.toolName}>
933
+ <span class="ols-turn-chip">
934
+ {entry.toolName}
935
+ </span>
936
+ </Show>
937
+ <span class="ols-turn-time">
938
+ {formatRelativeTime(entry.timeCreated)}
939
+ </span>
940
+ </div>
941
+ <div class="ols-turn-body">{entry.text}</div>
942
+ </div>
943
+ )}
944
+ </For>
945
+ </div>
946
+ }
947
+ >
948
+ <div class="ols-timeline">
949
+ <For each={session().matches}>
950
+ {(m, mIdx) => {
951
+ const isSelectedMatch = () =>
952
+ activePane() === "matches" &&
953
+ mIdx() === selectedMatchIdx()
954
+ return (
955
+ <div
956
+ class={`ols-turn ${
957
+ isSelectedMatch() ? "ols-turn--selected" : ""
958
+ }`}
959
+ onClick={() => {
960
+ setActivePane("matches")
961
+ setSelectedMatchIdx(mIdx())
962
+ }}
963
+ onDblClick={() => openSession(session())}
964
+ >
965
+ <div class="ols-turn-header">
966
+ <span
967
+ class={`ols-turn-author ols-turn-author--${m.role}`}
968
+ >
969
+ {roleLabel(m.role)}
970
+ </span>
971
+ <Show when={m.kind === "tool" && m.toolName}>
972
+ <span class="ols-turn-chip">
973
+ {m.toolName}
974
+ </span>
975
+ </Show>
976
+ <Show when={m.kind === "filepath"}>
977
+ <span class="ols-turn-chip">file</span>
978
+ </Show>
979
+ <Show when={m.kind === "fuzzy"}>
980
+ <span class="ols-turn-chip">
981
+ ~{m.matchedTerm}
982
+ </span>
983
+ </Show>
984
+ <span class="ols-turn-time">
985
+ {formatRelativeTime(m.timeCreated)}
986
+ </span>
987
+ </div>
988
+ <div class="ols-turn-body">
989
+ <HighlightedText
990
+ text={m.snippet}
991
+ terms={highlightTerms()}
992
+ regexPattern={parsedInfo()?.regexPattern}
993
+ regexFlags={parsedInfo()?.regexFlags}
994
+ />
995
+ </div>
996
+ </div>
997
+ )
998
+ }}
999
+ </For>
1000
+ </div>
1001
+ </Show>
1002
+ </div>
1003
+ </>
1004
+ )}
1005
+ </Show>
1006
+ </div>
1007
+ </div>
1008
+ </Show>
1009
+ </div>
1010
+ )
1011
+ }
1012
+
1013
+ export default Plugin.define({
1014
+ i18n: {
1015
+ en: {
1016
+ "search.title": "Search",
1017
+ "search.command": "Search session history...",
1018
+ "search.panel": "Search",
1019
+ },
1020
+ },
1021
+ setup(ctx) {
1022
+ const ui = ctx.ui
1023
+
1024
+ ctx.add(Style, css)
1025
+
1026
+ let searchFallbackDialog: { close(): void } | undefined
1027
+
1028
+ function openSearchPanel(initialQuery = "") {
1029
+ setOlsPanelQuery(initialQuery)
1030
+ const session = ctx.sessions.current()
1031
+ if (!session) {
1032
+ if (searchFallbackDialog) return
1033
+ searchFallbackDialog = ctx.dialogs.open((dialog) => {
1034
+ onCleanup(() => { searchFallbackDialog = undefined })
1035
+ return (
1036
+ <ui.Dialog title="Search" size="x-large">
1037
+ <SearchSurface ctx={ctx} variant="modal" initialQuery={initialQuery} onClose={dialog.close} />
1038
+ </ui.Dialog>
1039
+ )
1040
+ })
1041
+ return
1042
+ }
1043
+ searchFallbackDialog?.close()
1044
+ try {
1045
+ // Always select the tab so it becomes the focused panel even if another
1046
+ // panel (usage, memory, backups) is already open.
1047
+ ctx.layout.open(`${ctx.id}:search`, session)
1048
+ } catch {
1049
+ // Layout not ready; retry on next interaction.
1050
+ }
1051
+ }
1052
+
1053
+ ctx.add(
1054
+ Command,
1055
+ (): Command => ({
1056
+ id: "search",
1057
+ title: "Search session history...",
1058
+ description:
1059
+ "Full-text, fuzzy, regex, tool, and file search across all session conversations",
1060
+ keywords: "find history messages conversation regex fuzzy search grep",
1061
+ group: "Session",
1062
+ section: "session",
1063
+ bind: "mod+shift+f",
1064
+ slash: {
1065
+ name: "search",
1066
+ arguments: true,
1067
+ },
1068
+ featured: true,
1069
+ run(input) {
1070
+ openSearchPanel(typeof input === "string" ? input : "")
1071
+ },
1072
+ }),
1073
+ )
1074
+
1075
+ ctx.add(
1076
+ Command,
1077
+ (): Command => ({
1078
+ id: "search-panel",
1079
+ title: "Toggle session search panel",
1080
+ description: "Open or close the Session Search side panel",
1081
+ keywords: "panel sidebar search history",
1082
+ group: "Session",
1083
+ section: "session",
1084
+ bind: "mod+alt+f",
1085
+ run() {
1086
+ const session = ctx.sessions.current()
1087
+ if (session) {
1088
+ ctx.layout.toggle(`${ctx.id}:search`, session)
1089
+ } else {
1090
+ openSearchPanel("")
1091
+ }
1092
+ },
1093
+ }),
1094
+ )
1095
+
1096
+ if (typeof document !== "undefined") {
1097
+ const isBuiltinTitlebarSearchButton = (el: Element): boolean => {
1098
+ const btn = el.closest("button")
1099
+ if (!btn || btn.closest(".ols-root")) return false
1100
+ if (btn.getAttribute("data-action") === "vertical-tabs-search") {
1101
+ return true
1102
+ }
1103
+ if (!btn.closest('[data-slot="titlebar-v2"]')) return false
1104
+ if (btn.closest("[data-titlebar-plugin-item]")) return false
1105
+ const aria = (btn.getAttribute("aria-label") ?? "").toLowerCase()
1106
+ if (aria.includes("search")) return true
1107
+ const useEl = btn.querySelector('svg[data-slot="icon-svg"] use')
1108
+ const href =
1109
+ useEl?.getAttribute("href") ??
1110
+ useEl?.getAttribute("xlink:href") ??
1111
+ ""
1112
+ return href.includes("magnifying-glass")
1113
+ }
1114
+
1115
+ const handleCaptureClick = (e: MouseEvent) => {
1116
+ const target = e.target
1117
+ if (!(target instanceof Element)) return
1118
+
1119
+ if (isBuiltinTitlebarSearchButton(target)) {
1120
+ e.preventDefault()
1121
+ e.stopPropagation()
1122
+ openSearchPanel("")
1123
+ return
1124
+ }
1125
+
1126
+ const homeSearch = target.closest(
1127
+ '[data-component="home-session-search"]',
1128
+ )
1129
+ if (homeSearch) {
1130
+ e.preventDefault()
1131
+ e.stopPropagation()
1132
+ const input = homeSearch.querySelector("input")
1133
+ const initial = input instanceof HTMLInputElement ? input.value : ""
1134
+ if (input instanceof HTMLElement) input.blur()
1135
+ openSearchPanel(initial)
1136
+ }
1137
+ }
1138
+
1139
+ const handleCaptureFocusIn = (e: FocusEvent) => {
1140
+ const target = e.target
1141
+ if (!(target instanceof Element)) return
1142
+ const homeSearch = target.closest(
1143
+ '[data-component="home-session-search"]',
1144
+ )
1145
+ if (!homeSearch) return
1146
+ const initial =
1147
+ target instanceof HTMLInputElement ? target.value : ""
1148
+ if (target instanceof HTMLElement) {
1149
+ target.blur()
1150
+ }
1151
+ openSearchPanel(initial)
1152
+ }
1153
+
1154
+ document.addEventListener("click", handleCaptureClick, true)
1155
+ document.addEventListener("focusin", handleCaptureFocusIn, true)
1156
+
1157
+ const syncBuiltinSearchButtonLabel = () => {
1158
+ const buttons = document.querySelectorAll<HTMLButtonElement>(
1159
+ 'button[data-action="vertical-tabs-search"]',
1160
+ )
1161
+ for (const btn of buttons) {
1162
+ for (const span of btn.querySelectorAll("span")) {
1163
+ const txt = span.textContent?.trim().toLowerCase() ?? ""
1164
+ if (txt === "search sessions") {
1165
+ span.textContent = "Search"
1166
+ span.classList.add("whitespace-nowrap")
1167
+ } else if (span.classList.contains("ms-auto") || span.querySelector("bdi, kbd")) {
1168
+ span.remove()
1169
+ }
1170
+ }
1171
+ if (btn.getAttribute("aria-label")?.toLowerCase() === "search sessions") {
1172
+ btn.setAttribute("aria-label", "Search")
1173
+ }
1174
+ if (btn.getAttribute("title")?.toLowerCase() === "search sessions") {
1175
+ btn.setAttribute("title", "Search")
1176
+ }
1177
+ }
1178
+ }
1179
+
1180
+ syncBuiltinSearchButtonLabel()
1181
+ setTimeout(syncBuiltinSearchButtonLabel, 50)
1182
+
1183
+ const redirectedInputs = new WeakSet<HTMLInputElement>()
1184
+ const observer = new MutationObserver(() => {
1185
+ syncBuiltinSearchButtonLabel()
1186
+ const builtinInput = document.querySelector<HTMLInputElement>(
1187
+ '.command-palette input[placeholder="Search sessions"], .command-palette-dialog input[placeholder="Search sessions..."]',
1188
+ )
1189
+ if (builtinInput && !redirectedInputs.has(builtinInput)) {
1190
+ redirectedInputs.add(builtinInput)
1191
+ const initial = builtinInput.value || ""
1192
+ builtinInput.dispatchEvent(new KeyboardEvent("keydown", {
1193
+ key: "Escape", code: "Escape", bubbles: true, cancelable: true,
1194
+ }))
1195
+ openSearchPanel(initial)
1196
+ }
1197
+ })
1198
+
1199
+ if (document.body) {
1200
+ observer.observe(document.body, { childList: true, subtree: true })
1201
+ }
1202
+
1203
+ onCleanup(() => {
1204
+ document.removeEventListener("click", handleCaptureClick, true)
1205
+ document.removeEventListener("focusin", handleCaptureFocusIn, true)
1206
+ observer.disconnect()
1207
+ })
1208
+ }
1209
+
1210
+ const searchTab: PanelTab = {
1211
+ id: "search",
1212
+ get title() {
1213
+ return ctx.t("search.panel")
1214
+ },
1215
+ closable: "compact",
1216
+ }
1217
+
1218
+ ctx.add(Panel, {
1219
+ id: "search",
1220
+ region: "side",
1221
+ list: (input) => (input.open.includes("search") ? [searchTab] : []),
1222
+ render: () => <SearchSurface ctx={ctx} variant="panel" />,
1223
+ })
1224
+
1225
+ ctx.add(
1226
+ MenuItem,
1227
+ (): MenuItem => {
1228
+ const session = ctx.sessions.current()
1229
+ return {
1230
+ menu: "session.panel",
1231
+ id: "search",
1232
+ title: "Search",
1233
+ description: "Search conversation history",
1234
+ icon: "magnifying-glass",
1235
+ keybind: `${ctx.id}.search-panel`,
1236
+ opened:
1237
+ !!session &&
1238
+ ctx.layout.state(`${ctx.id}:search`, session) !== "closed",
1239
+ run: () => {
1240
+ const current = ctx.sessions.current()
1241
+ if (current) {
1242
+ ctx.layout.open(`${ctx.id}:search`, current)
1243
+ } else {
1244
+ openSearchPanel("")
1245
+ }
1246
+ },
1247
+ }
1248
+ },
1249
+ )
1250
+ },
1251
+ })