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