@hapyp/dsh-session-search 0.0.0-stage → 1.0.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/client.js ADDED
@@ -0,0 +1,1211 @@
1
+ /**
2
+ * Browser half of @local/session-content-search.
3
+ *
4
+ * Registers three UI contributions:
5
+ * - `shell.overlay`: the cross-workspace content search palette (Ctrl+Shift+F).
6
+ * - `conversation.session.header.utilities`: the in-conversation find bar (Ctrl+F).
7
+ * - `sidebar.footer.action`: the sidebar button that opens the palette.
8
+ *
9
+ * Search runs on the Host half through an authenticated same-origin `/api`
10
+ * route; everything else is local. Plain React without JSX, own styles with
11
+ * the `scs-` class prefix and `--dsw-alias-*` theme tokens only.
12
+ */
13
+ window.__ModuleLoader__.load({
14
+ id: '@hapyp/dsh-session-search',
15
+ factory(require) {
16
+ const React = require('react')
17
+ const ReactDOM = require('react-dom')
18
+ const h = React.createElement
19
+
20
+ const PLUGIN_ID = 'session-content-search'
21
+ const NS = 'session-content-search'
22
+ const SEARCH_ROUTE = '/api/session-content-search/search'
23
+
24
+ /* ------------------------------------------------------------------ *
25
+ * Locale dictionaries (registered through the Client locale service).
26
+ * ------------------------------------------------------------------ */
27
+
28
+ const en = {
29
+ 'palette.open': 'Search session content',
30
+ 'entry.label': 'Search all sessions',
31
+ 'entry.keys': 'Ctrl Shift F',
32
+ 'palette.placeholder': 'Search all sessions…',
33
+ 'palette.includeTools': 'Include tool text',
34
+ 'palette.diskCache': 'Disk cache',
35
+ 'palette.diskCacheHint':
36
+ 'Off (default): nothing is written to disk; the first search after each DSH start takes a few seconds. On: session text is cached in the system temp folder so that first search is near-instant.',
37
+ 'palette.diskCacheHintShort': 'write scanned session text to the temp folder to speed up the first search after a restart',
38
+ 'palette.searching': 'Searching…',
39
+ 'palette.idle': 'Type a keyword to search every session in every workspace.',
40
+ 'palette.noMatches': 'No session matches this keyword.',
41
+ 'palette.noMatchesPartial': 'No match in the scanned sessions yet — scan older sessions to continue.',
42
+ 'palette.needBackend': 'Full-text search backend is unavailable on the Host mainline (session-content-search-query row).',
43
+ 'palette.error': 'Search failed. Try again in a moment.',
44
+ 'palette.more': 'Scan older sessions',
45
+ 'palette.hint': 'Enter open · ↑↓ select · Esc close',
46
+ 'row.untitled': 'Untitled session',
47
+ 'find.open': 'Find in conversation',
48
+ 'find.placeholder': 'Find in conversation…',
49
+ 'find.noMatches': 'No matches',
50
+ 'find.start': 'Start search',
51
+ 'find.atStart': 'Start of matches',
52
+ 'find.atEnd': 'End of matches',
53
+ 'find.historyOnly': '{count} match(es) in the full history — scroll up to load them',
54
+ 'find.historyMore': '{count} in full history',
55
+ }
56
+
57
+ const zh = {
58
+ 'palette.open': '搜索会话内容',
59
+ 'entry.label': '搜索全部会话',
60
+ 'entry.keys': 'Ctrl Shift F',
61
+ 'palette.placeholder': '搜索所有会话…',
62
+ 'palette.includeTools': '包含工具输出',
63
+ 'palette.diskCache': '磁盘缓存',
64
+ 'palette.diskCacheHint':
65
+ '关闭(默认):不向磁盘写入任何内容,每次 DSH 启动后的首次搜索需要数秒。开启:会话文本会缓存在系统临时目录,使首次搜索接近即时。',
66
+ 'palette.diskCacheHintShort': '把扫描过的会话文本写入系统临时目录,加快重启后的首次搜索',
67
+ 'palette.searching': '搜索中…',
68
+ 'palette.idle': '输入关键字,搜索所有工作区中的全部会话内容。',
69
+ 'palette.noMatches': '没有会话匹配该关键字。',
70
+ 'palette.noMatchesPartial': '已扫描的会话中暂无匹配——可继续扫描更早的会话。',
71
+ 'palette.needBackend': '全文搜索后端不可用:Host 主线未挂载搜索索引(session-content-search-query 行)。',
72
+ 'palette.error': '搜索失败,请稍后重试。',
73
+ 'palette.more': '继续扫描更早的会话',
74
+ 'palette.hint': 'Enter 打开 · ↑↓ 选择 · Esc 关闭',
75
+ 'row.untitled': '未命名会话',
76
+ 'find.open': '在会话中查找',
77
+ 'find.placeholder': '在会话中查找…',
78
+ 'find.noMatches': '无匹配',
79
+ 'find.start': '开始搜索',
80
+ 'find.atStart': '已到开头',
81
+ 'find.atEnd': '已到末尾',
82
+ 'find.historyOnly': '完整历史中共 {count} 条——向上滚动加载后可定位',
83
+ 'find.historyMore': '完整历史共 {count} 条',
84
+ }
85
+
86
+ /* ------------------------------------------------------------------ *
87
+ * Minimal observable store (snapshot stable between mutations).
88
+ * ------------------------------------------------------------------ */
89
+
90
+ function createStore(initial) {
91
+ let state = initial
92
+ const subscribers = new Set()
93
+ return {
94
+ get: () => state,
95
+ set: (next) => {
96
+ if (Object.is(next, state)) return
97
+ state = next
98
+ for (const notify of [...subscribers]) notify()
99
+ },
100
+ subscribe: (fn) => {
101
+ subscribers.add(fn)
102
+ return () => subscribers.delete(fn)
103
+ },
104
+ }
105
+ }
106
+
107
+ const paletteStore = createStore({ open: false })
108
+ const findStore = createStore({ open: false, focusRequest: 0, prefill: null })
109
+
110
+ /** localStorage key for the opt-in disk cache preference. */
111
+ const DISK_CACHE_KEY = 'dsh-session-search.diskCache'
112
+
113
+ /**
114
+ * Read the disk-cache preference. Disk caching is opt-in: an absent or
115
+ * unreadable value means off, so nothing reaches the disk by default.
116
+ * @returns {boolean} whether the person enabled disk caching.
117
+ */
118
+ function readDiskCachePreference() {
119
+ try {
120
+ return window.localStorage.getItem(DISK_CACHE_KEY) === '1'
121
+ } catch {
122
+ return false
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Persist the disk-cache preference.
128
+ * @param {boolean} enabled - the new value.
129
+ * @returns {void}
130
+ */
131
+ function writeDiskCachePreference(enabled) {
132
+ try {
133
+ window.localStorage.setItem(DISK_CACHE_KEY, enabled ? '1' : '0')
134
+ } catch {}
135
+ }
136
+
137
+ function useStoreValue(store) {
138
+ return React.useSyncExternalStore(store.subscribe, store.get)
139
+ }
140
+
141
+ /* ------------------------------------------------------------------ *
142
+ * Shared runtime seams (assigned in apply).
143
+ * ------------------------------------------------------------------ */
144
+
145
+ let sharedCtx = null
146
+ let translate = (key) => key
147
+
148
+ /** The session the main conversation view currently retains, if any. */
149
+ function currentSessionId() {
150
+ try {
151
+ const list = sharedCtx?.sessions?.list?.getSnapshot?.()
152
+ if (!list || !list.byId) return null
153
+ for (const row of Object.values(list.byId)) {
154
+ if ((row?.retainedBy?.mainView ?? 0) > 0) return row.id
155
+ }
156
+ } catch {}
157
+ return null
158
+ }
159
+
160
+ /**
161
+ * The page text the user currently has selected, collapsed to one line
162
+ * and bounded so it can serve as a find query. Empty when nothing is
163
+ * selected or the selection is too long to be a useful phrase.
164
+ * @returns {string} the selection text, or ''.
165
+ */
166
+ function selectedText() {
167
+ try {
168
+ const selection = window.getSelection?.()
169
+ if (!selection || selection.isCollapsed === true) return ''
170
+ const raw = String(selection.toString()).replace(/\s+/gu, ' ').trim()
171
+ if (raw === '' || raw.length > 200) return ''
172
+ return raw
173
+ } catch {
174
+ return ''
175
+ }
176
+ }
177
+
178
+ /** Authenticated same-origin POST used for every Host call. */
179
+ function postJson(path, body, signal) {
180
+ const carrier = globalThis.__DSH_TRANSPORT__?.fetch
181
+ const send = typeof carrier === 'function' ? carrier : fetch
182
+ // Resolve against the page base like the shipped uploaders do: the
183
+ // Desktop window may serve the GUI over its own dsh-app scheme.
184
+ const url = new URL(path, document.baseURI).href
185
+ return send(url, {
186
+ method: 'POST',
187
+ headers: { 'content-type': 'application/json' },
188
+ body: JSON.stringify(body),
189
+ signal,
190
+ }).then(async (response) => {
191
+ let data = null
192
+ try {
193
+ data = await response.json()
194
+ } catch {}
195
+ if (!response.ok) {
196
+ const error = new Error(data?.message || `HTTP ${response.status}`)
197
+ error.code = data?.error || 'request-failed'
198
+ error.detail = data?.code
199
+ throw error
200
+ }
201
+ return data
202
+ })
203
+ }
204
+
205
+ /* ------------------------------------------------------------------ *
206
+ * Small formatting helpers.
207
+ * ------------------------------------------------------------------ */
208
+
209
+ function timeText(ms) {
210
+ if (typeof ms !== 'number' || !Number.isFinite(ms)) return ''
211
+ const date = new Date(ms)
212
+ const now = new Date()
213
+ const sameDay = date.getFullYear() === now.getFullYear()
214
+ && date.getMonth() === now.getMonth()
215
+ && date.getDate() === now.getDate()
216
+ const clock = `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
217
+ if (sameDay) return clock
218
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
219
+ }
220
+
221
+ function cwdTail(cwd) {
222
+ if (typeof cwd !== 'string' || cwd === '') return ''
223
+ const parts = cwd.replace(/[\\/]+$/, '').split(/[\\/]/)
224
+ return parts[parts.length - 1] || cwd
225
+ }
226
+
227
+ function typeTagKey(type) {
228
+ switch (type) {
229
+ case 'user/message': return 'tag.user'
230
+ case 'assistant/message': return 'tag.assistant'
231
+ case 'tool/call': return 'tag.toolCall'
232
+ case 'tool/result': return 'tag.toolResult'
233
+ case 'todo/write': return 'tag.todo'
234
+ case 'turn/end': return 'tag.turnEnd'
235
+ default: return null
236
+ }
237
+ }
238
+
239
+ const TAG_DICT = {
240
+ en: {
241
+ 'tag.user': 'user', 'tag.assistant': 'assistant', 'tag.toolCall': 'tool call',
242
+ 'tag.toolResult': 'tool result', 'tag.todo': 'todo', 'tag.turnEnd': 'turn',
243
+ },
244
+ zh: {
245
+ 'tag.user': '用户', 'tag.assistant': '助手', 'tag.toolCall': '工具调用',
246
+ 'tag.toolResult': '工具结果', 'tag.todo': '任务', 'tag.turnEnd': '回合',
247
+ },
248
+ }
249
+ let tagLocale = 'en'
250
+
251
+ function tagLabel(type) {
252
+ const key = typeTagKey(type)
253
+ if (key === null) return type
254
+ const dict = TAG_DICT[tagLocale] || TAG_DICT.en
255
+ return dict[key] || type
256
+ }
257
+
258
+ /**
259
+ * Split a snippet into text and <mark> parts around the query tokens.
260
+ * @param {string} snippet - Host-returned plain text.
261
+ * @param {string} query - the raw query.
262
+ * @returns {Array} React nodes.
263
+ */
264
+ function snippetParts(snippet, query) {
265
+ const text = typeof snippet === 'string' ? snippet : ''
266
+ const tokens = [...new Set((query || '').trim().toLowerCase().split(/\s+/).filter(Boolean))]
267
+ if (text === '' || tokens.length === 0) return [text]
268
+ const lower = text.toLowerCase()
269
+ const ranges = []
270
+ for (const token of tokens) {
271
+ let idx = lower.indexOf(token)
272
+ while (idx !== -1) {
273
+ ranges.push([idx, idx + token.length])
274
+ idx = lower.indexOf(token, idx + token.length)
275
+ }
276
+ }
277
+ if (ranges.length === 0) return [text]
278
+ ranges.sort((a, b) => a[0] - b[0] || a[1] - b[1])
279
+ const merged = []
280
+ for (const range of ranges) {
281
+ const last = merged[merged.length - 1]
282
+ if (last && range[0] <= last[1]) last[1] = Math.max(last[1], range[1])
283
+ else merged.push([range[0], range[1]])
284
+ }
285
+ const parts = []
286
+ let position = 0
287
+ for (const [start, end] of merged) {
288
+ if (start > position) parts.push(text.slice(position, start))
289
+ parts.push(h('mark', { key: `${start}:${end}`, className: 'scs-mark' }, text.slice(start, end)))
290
+ position = end
291
+ }
292
+ if (position < text.length) parts.push(text.slice(position))
293
+ return parts
294
+ }
295
+
296
+ /* ------------------------------------------------------------------ *
297
+ * Global search palette (shell.overlay entry).
298
+ * ------------------------------------------------------------------ */
299
+
300
+ const SEARCH_DEBOUNCE_MS = 280
301
+
302
+ function PaletteOverlay(props) {
303
+ const { open } = useStoreValue(paletteStore)
304
+ const [query, setQuery] = React.useState('')
305
+ const [includeTools, setIncludeTools] = React.useState(true)
306
+ const [diskCache, setDiskCache] = React.useState(() => readDiskCachePreference())
307
+ const [status, setStatus] = React.useState('idle')
308
+ const [items, setItems] = React.useState([])
309
+ const [cursor, setCursor] = React.useState(null)
310
+ const [errorCode, setErrorCode] = React.useState(null)
311
+ const [selected, setSelected] = React.useState(0)
312
+ const inputRef = React.useRef(null)
313
+ const abortRef = React.useRef(null)
314
+ const queryRef = React.useRef('')
315
+ const lastErrorRef = React.useRef(null)
316
+
317
+ const listState = typeof props?.useSessions === 'function' ? props.useSessions((state) => state) : null
318
+ const workspaceState = typeof props?.useWorkspaces === 'function' ? props.useWorkspaces((state) => state) : null
319
+
320
+ // Focus the input whenever the palette opens.
321
+ React.useEffect(() => {
322
+ if (!open) return
323
+ const timer = window.setTimeout(() => {
324
+ const input = inputRef.current
325
+ if (input) {
326
+ input.focus()
327
+ input.select()
328
+ }
329
+ }, 0)
330
+ return () => window.clearTimeout(timer)
331
+ }, [open])
332
+
333
+ const runSearch = React.useCallback((rawQuery, appendCursor, includeToolText, cacheToDisk) => {
334
+ const trimmed = rawQuery.trim()
335
+ if (abortRef.current) abortRef.current.abort()
336
+ const controller = new AbortController()
337
+ abortRef.current = controller
338
+ if (trimmed === '') {
339
+ setStatus('idle')
340
+ setItems([])
341
+ setCursor(null)
342
+ setErrorCode(null)
343
+ setSelected(0)
344
+ lastErrorRef.current = null
345
+ return
346
+ }
347
+ setStatus('loading')
348
+ setErrorCode(null)
349
+ lastErrorRef.current = null
350
+ const recordFailure = (error) => {
351
+ if (controller.signal.aborted || error?.name === 'AbortError') return
352
+ lastErrorRef.current = [error?.code, error?.detail, error?.message]
353
+ .filter((part) => typeof part === 'string' && part !== '')
354
+ .join(' · ')
355
+ setStatus('error')
356
+ setErrorCode(error?.code || 'search-failed')
357
+ }
358
+ /**
359
+ * Second path: the built-in authorized content search over the RPC
360
+ * channel. It matches user/assistant messages only and carries no
361
+ * type/time metadata, but it does not depend on the plugin's own
362
+ * /api bridge, so it keeps the palette working when that bridge is
363
+ * the broken link.
364
+ */
365
+ const fallbackToBuiltinSearch = async () => {
366
+ try {
367
+ const result = await sharedCtx?.sessions?.search?.(trimmed, controller.signal)
368
+ if (controller.signal.aborted) return
369
+ if (result && result.ok === true && Array.isArray(result.value?.items)) {
370
+ setItems(result.value.items.map((item) => ({
371
+ sessionId: item.sessionId,
372
+ snippet: item.snippet,
373
+ type: 'user/message',
374
+ time: null,
375
+ cwd: null,
376
+ seq: null,
377
+ })))
378
+ setCursor(null)
379
+ setStatus('ready')
380
+ setSelected(0)
381
+ return
382
+ }
383
+ const failure = result && result.ok === false ? result.error : null
384
+ recordFailure(Object.assign(
385
+ new Error((failure && (failure.message || failure.rpcError?.message)) || 'builtin search failed'),
386
+ { code: 'search-failed', detail: failure && failure.rpcError?.code },
387
+ ))
388
+ } catch (error) {
389
+ if (controller.signal.aborted || error?.name === 'AbortError') return
390
+ recordFailure(error)
391
+ }
392
+ }
393
+ postJson(SEARCH_ROUTE, {
394
+ query: trimmed,
395
+ messagesOnly: !includeToolText,
396
+ limit: 30,
397
+ cache: cacheToDisk === true,
398
+ ...(appendCursor !== null && appendCursor !== undefined ? { scanOffset: appendCursor } : {}),
399
+ }, controller.signal).then((page) => {
400
+ if (controller.signal.aborted) return
401
+ setItems((previous) => (appendCursor ? [...previous, ...(page.items || [])] : [...(page.items || [])]))
402
+ setCursor(typeof page.nextOffset === 'number' ? page.nextOffset : null)
403
+ setStatus('ready')
404
+ setSelected((previous) => (appendCursor ? previous : 0))
405
+ }).catch((error) => {
406
+ if (controller.signal.aborted || error?.name === 'AbortError') return
407
+ if (error?.code === 'search-unavailable') {
408
+ recordFailure(error)
409
+ return
410
+ }
411
+ void fallbackToBuiltinSearch()
412
+ })
413
+ }, [])
414
+
415
+ // Debounced search whenever query/toggle/open change.
416
+ React.useEffect(() => {
417
+ if (!open) {
418
+ if (abortRef.current) abortRef.current.abort()
419
+ return undefined
420
+ }
421
+ const timer = window.setTimeout(() => {
422
+ runSearch(query, null, includeTools, diskCache)
423
+ }, queryRef.current === query ? 0 : SEARCH_DEBOUNCE_MS)
424
+ queryRef.current = query
425
+ return () => window.clearTimeout(timer)
426
+ }, [open, query, includeTools, diskCache, runSearch])
427
+
428
+ // Stop any in-flight request and drop highlights when closed.
429
+ React.useEffect(() => {
430
+ if (open) return undefined
431
+ return () => {}
432
+ }, [open])
433
+ React.useEffect(() => () => {
434
+ if (abortRef.current) abortRef.current.abort()
435
+ }, [])
436
+
437
+ if (!open) return null
438
+
439
+ const byId = listState?.byId || {}
440
+ const workspaceBySession = new Map()
441
+ if (workspaceState && Array.isArray(workspaceState.items)) {
442
+ for (const workspace of workspaceState.items) {
443
+ const ids = Array.isArray(workspace?.sessionIds) ? workspace.sessionIds : []
444
+ for (const sessionId of ids) {
445
+ if (!workspaceBySession.has(sessionId)) workspaceBySession.set(sessionId, workspace.title || '')
446
+ }
447
+ }
448
+ }
449
+
450
+ const rows = items.map((item) => {
451
+ const summary = byId[item.sessionId]
452
+ const title = typeof summary?.title === 'string' && summary.title.trim() !== ''
453
+ ? summary.title
454
+ : translate('row.untitled')
455
+ return {
456
+ ...item,
457
+ title,
458
+ workspace: workspaceBySession.get(item.sessionId) || cwdTail(item.cwd),
459
+ }
460
+ })
461
+
462
+ const openResult = (sessionId) => {
463
+ if (typeof sessionId !== 'string' || sessionId === '') return
464
+ paletteStore.set({ open: false })
465
+ try {
466
+ sharedCtx?.uiWorkspace?.openSession?.(sessionId)
467
+ } catch (error) {
468
+ console.error('[session-content-search] open session failed:', error)
469
+ }
470
+ }
471
+
472
+ const moveSelection = (delta) => {
473
+ if (rows.length === 0) return
474
+ setSelected((previous) => (previous + delta + rows.length) % rows.length)
475
+ }
476
+
477
+ const onKeyDown = (event) => {
478
+ if (event.key === 'ArrowDown') {
479
+ event.preventDefault()
480
+ moveSelection(1)
481
+ } else if (event.key === 'ArrowUp') {
482
+ event.preventDefault()
483
+ moveSelection(-1)
484
+ } else if (event.key === 'Enter') {
485
+ event.preventDefault()
486
+ const row = rows[selected]
487
+ if (row) openResult(row.sessionId)
488
+ }
489
+ }
490
+
491
+ const bodyStatus = status === 'loading' && rows.length === 0
492
+ ? hintOf(translate('palette.searching'))
493
+ : status === 'error'
494
+ ? hintOf(errorCode === 'search-unavailable' ? translate('palette.needBackend') : translate('palette.error'), true)
495
+ : rows.length === 0
496
+ ? hintOf(query.trim() === ''
497
+ ? translate('palette.idle')
498
+ : cursor !== null
499
+ ? translate('palette.noMatchesPartial')
500
+ : translate('palette.noMatches'))
501
+ : null
502
+
503
+ // Surface the Host-provided failure detail under the hint so a failing
504
+ // search can be diagnosed from the palette itself.
505
+ const errorDetail = status === 'error' && errorCode !== 'search-unavailable' ? lastErrorRef.current : null
506
+
507
+ return h('div', {
508
+ className: 'scs-backdrop',
509
+ onMouseDown: (event) => {
510
+ if (event.target === event.currentTarget) paletteStore.set({ open: false })
511
+ },
512
+ },
513
+ h('div', { className: 'scs-palette', 'data-scs-exclude': '', role: 'dialog', 'aria-label': translate('palette.open') },
514
+ h('div', { className: 'scs-palette-head' },
515
+ h('input', {
516
+ ref: inputRef,
517
+ className: 'scs-input',
518
+ type: 'text',
519
+ value: query,
520
+ placeholder: translate('palette.placeholder'),
521
+ spellCheck: false,
522
+ onChange: (event) => setQuery(event.target.value),
523
+ onKeyDown,
524
+ }),
525
+ h('label', { className: 'scs-toggle' },
526
+ h('input', {
527
+ type: 'checkbox',
528
+ checked: includeTools,
529
+ onChange: (event) => setIncludeTools(event.target.checked),
530
+ }),
531
+ translate('palette.includeTools'),
532
+ ),
533
+ ),
534
+ h('div', { className: 'scs-results' },
535
+ bodyStatus,
536
+ errorDetail !== null ? h('div', { className: 'scs-error-detail' }, errorDetail) : null,
537
+ rows.map((row, index) => h(PaletteRow, {
538
+ key: `${row.sessionId}:${index}`,
539
+ row,
540
+ query,
541
+ selected: index === selected,
542
+ onHover: () => setSelected(index),
543
+ onOpen: () => openResult(row.sessionId),
544
+ })),
545
+ status === 'ready' && cursor !== null
546
+ ? h('button', {
547
+ className: 'scs-more',
548
+ onClick: () => runSearch(query, cursor, includeTools, diskCache),
549
+ }, translate('palette.more'))
550
+ : null, ),
551
+ h('div', { className: 'scs-palette-foot' },
552
+ h('label', { className: 'scs-foot-toggle' },
553
+ h('input', {
554
+ type: 'checkbox',
555
+ checked: diskCache,
556
+ onChange: (event) => {
557
+ setDiskCache(event.target.checked)
558
+ writeDiskCachePreference(event.target.checked)
559
+ },
560
+ }),
561
+ h('span', { className: 'scs-foot-toggle-label' }, translate('palette.diskCache')),
562
+ ),
563
+ h('span', { className: 'scs-foot-hint' }, translate('palette.diskCacheHintShort')),
564
+ h('span', { className: 'scs-foot-keys' }, translate('palette.hint')),
565
+ ),
566
+ ),
567
+ )
568
+ }
569
+
570
+ function hintOf(text, isError) {
571
+ return h('div', { className: 'scs-hint' + (isError ? ' scs-hint-error' : '') }, text)
572
+ }
573
+
574
+ function PaletteRow({ row, query, selected, onHover, onOpen }) {
575
+ const ref = React.useRef(null)
576
+ React.useEffect(() => {
577
+ if (selected && ref.current) ref.current.scrollIntoView({ block: 'nearest' })
578
+ }, [selected])
579
+ return h('div', {
580
+ ref,
581
+ className: 'scs-row' + (selected ? ' scs-row-selected' : ''),
582
+ role: 'option',
583
+ 'aria-selected': selected,
584
+ onMouseEnter: onHover,
585
+ onClick: onOpen,
586
+ },
587
+ h('div', { className: 'scs-row-snippet' }, snippetParts(row.snippet, query)),
588
+ h('div', { className: 'scs-row-meta' },
589
+ h('span', { className: 'scs-tag' }, tagLabel(row.type)),
590
+ h('span', { className: 'scs-row-title' }, row.title),
591
+ row.workspace ? h('span', { className: 'scs-row-ws' }, row.workspace) : null,
592
+ h('span', { className: 'scs-row-time' }, timeText(row.time)),
593
+ ),
594
+ )
595
+ }
596
+
597
+ /* ------------------------------------------------------------------ *
598
+ * In-conversation find bar (conversation.session.header.utilities).
599
+ * ------------------------------------------------------------------ */
600
+
601
+ const HIGHLIGHT_NAME = 'scs-find'
602
+ const ACTIVE_HIGHLIGHT_NAME = 'scs-find-active'
603
+
604
+ function highlightApiAvailable() {
605
+ return typeof CSS !== 'undefined' && CSS.highlights != null && typeof Highlight !== 'undefined'
606
+ }
607
+
608
+ function clearHighlights() {
609
+ if (!highlightApiAvailable()) return
610
+ CSS.highlights.delete(HIGHLIGHT_NAME)
611
+ CSS.highlights.delete(ACTIVE_HIGHLIGHT_NAME)
612
+ }
613
+
614
+ function applyHighlights(ranges, activeIndex) {
615
+ if (!highlightApiAvailable()) return
616
+ clearHighlights()
617
+ if (ranges.length > 0) {
618
+ // Very large match sets stay under the engine's argument limit.
619
+ CSS.highlights.set(HIGHLIGHT_NAME, new Highlight(...ranges.slice(0, 2000)))
620
+ }
621
+ if (activeIndex >= 0 && ranges[activeIndex]) {
622
+ CSS.highlights.set(ACTIVE_HIGHLIGHT_NAME, new Highlight(ranges[activeIndex]))
623
+ }
624
+ }
625
+
626
+ /**
627
+ * Collect text-node ranges of every case-insensitive match inside the
628
+ * conversation's rendered rows, in document order.
629
+ * @param {string} query - raw query text.
630
+ * @returns {Range[]} flattened match ranges.
631
+ */
632
+ function scanConversation(query) {
633
+ const needle = query.trim().toLowerCase()
634
+ if (needle === '') return []
635
+ const ranges = []
636
+ const rows = document.querySelectorAll('[data-chat-anchor-key]')
637
+ for (const row of rows) {
638
+ if (row.closest('[hidden]')) continue
639
+ if (row.getClientRects().length === 0) continue
640
+ const walker = document.createTreeWalker(row, NodeFilter.SHOW_TEXT, {
641
+ acceptNode(node) {
642
+ const value = node.nodeValue
643
+ if (!value || value.trim() === '') return NodeFilter.FILTER_REJECT
644
+ const parent = node.parentElement
645
+ if (parent && parent.closest('[data-scs-exclude]')) return NodeFilter.FILTER_REJECT
646
+ return NodeFilter.FILTER_ACCEPT
647
+ },
648
+ })
649
+ let textNode = walker.nextNode()
650
+ while (textNode !== null) {
651
+ const value = textNode.nodeValue
652
+ const lower = value.toLowerCase()
653
+ let index = lower.indexOf(needle)
654
+ while (index !== -1) {
655
+ const range = document.createRange()
656
+ range.setStart(textNode, index)
657
+ range.setEnd(textNode, index + needle.length)
658
+ ranges.push(range)
659
+ index = lower.indexOf(needle, index + needle.length)
660
+ }
661
+ textNode = walker.nextNode()
662
+ }
663
+ }
664
+ return ranges
665
+ }
666
+
667
+ /**
668
+ * Index of the first match whose row is inside the current viewport, so a
669
+ * search can report and start navigating from what the reader sees.
670
+ * @param {Range[]} found - matches in document order.
671
+ * @returns {number} visible match index, or -1 when none is on screen.
672
+ */
673
+ function firstVisibleMatch(found) {
674
+ const viewportHeight = typeof window !== 'undefined' ? window.innerHeight : 0
675
+ for (let index = 0; index < found.length; index += 1) {
676
+ try {
677
+ const element = found[index].startContainer.parentElement
678
+ const rect = element?.getBoundingClientRect?.()
679
+ if (!rect || rect.height === 0) continue
680
+ if (rect.top >= 0 && rect.bottom <= viewportHeight) return index
681
+ } catch {}
682
+ }
683
+ return -1
684
+ }
685
+
686
+ function FindBar(props) {
687
+ const { open, focusRequest, prefill } = useStoreValue(findStore)
688
+ const sessionId = typeof props?.sessionId === 'string' ? props.sessionId : null
689
+ const [query, setQuery] = React.useState('')
690
+ const [ranges, setRanges] = React.useState([])
691
+ const [active, setActive] = React.useState(-1)
692
+ // Total matches in the complete session log (rendered and not yet loaded).
693
+ const [fullTotal, setFullTotal] = React.useState(null)
694
+ // A prefilled selection waits for Enter: the first render must not scan
695
+ // and jump the reader away from the text they just selected.
696
+ const [awaitingEnter, setAwaitingEnter] = React.useState(false)
697
+ // Edge feedback: pressing Next at the last match (or Previous at the
698
+ // first) stops there and reports the edge before wrapping.
699
+ const [boundaryHint, setBoundaryHint] = React.useState(null)
700
+ // Incremented by the Search button to force a fresh scan.
701
+ const [scanNonce, setScanNonce] = React.useState(0)
702
+ const inputRef = React.useRef(null)
703
+ const activeRef = React.useRef(-1)
704
+ const prefillNonceRef = React.useRef(0)
705
+ const boundaryTimerRef = React.useRef(0)
706
+ const lastBoundaryRef = React.useRef({ edge: null, at: 0 })
707
+
708
+ // Focus on open and again on every repeated Ctrl+F.
709
+ React.useEffect(() => {
710
+ if (!open) return undefined
711
+ const timer = window.setTimeout(() => {
712
+ const input = inputRef.current
713
+ if (input) {
714
+ input.focus()
715
+ if (prefill === null || prefill === undefined) input.select()
716
+ else input.setSelectionRange(prefill.text.length, prefill.text.length)
717
+ }
718
+ }, 0)
719
+ return () => window.clearTimeout(timer)
720
+ }, [open, focusRequest, prefill])
721
+
722
+ // A fresh page selection fills the box and arms the Enter gate.
723
+ React.useEffect(() => {
724
+ if (!open || prefill === null || prefill === undefined) return
725
+ if (prefillNonceRef.current === prefill.nonce) return
726
+ prefillNonceRef.current = prefill.nonce
727
+ setQuery(prefill.text)
728
+ setAwaitingEnter(true)
729
+ clearHighlights()
730
+ activeRef.current = -1
731
+ setRanges([])
732
+ setActive(-1)
733
+ }, [open, prefill])
734
+
735
+ React.useEffect(() => () => {
736
+ clearHighlights()
737
+ window.clearTimeout(boundaryTimerRef.current)
738
+ }, [])
739
+
740
+ React.useEffect(() => {
741
+ // A new scan invalidates any edge feedback from the previous query.
742
+ lastBoundaryRef.current = { edge: null, at: 0 }
743
+ setBoundaryHint(null)
744
+ if (!open || query.trim() === '' || awaitingEnter) {
745
+ clearHighlights()
746
+ activeRef.current = -1
747
+ setRanges([])
748
+ setActive(-1)
749
+ setFullTotal(null)
750
+ return undefined
751
+ }
752
+ const signatureOf = () => {
753
+ const rows = document.querySelectorAll('[data-chat-anchor-key]')
754
+ if (rows.length === 0) return '0'
755
+ return `${rows.length}|${String(rows[0].getAttribute('data-chat-anchor-key'))}|${String(rows[rows.length - 1].getAttribute('data-chat-anchor-key'))}`
756
+ }
757
+ let lastSignature = null
758
+ let pendingTimer = 0
759
+ const runScan = (isFresh) => {
760
+ const found = scanConversation(query)
761
+ setRanges(found)
762
+ if (found.length === 0) {
763
+ activeRef.current = -1
764
+ setActive(-1)
765
+ applyHighlights(found, -1)
766
+ return
767
+ }
768
+ if (isFresh) {
769
+ // A fresh scan keeps the current view: highlight everything, make
770
+ // the first on-screen match active, and never scroll the reader
771
+ // away from where they are looking. When nothing is on screen the
772
+ // bar reports 0/n and the first Next press lands on match one.
773
+ const visible = firstVisibleMatch(found)
774
+ activeRef.current = visible
775
+ setActive(visible)
776
+ applyHighlights(found, visible)
777
+ return
778
+ }
779
+ // A background rescan (rows scrolled in or out, or a session swap)
780
+ // keeps the reader's place instead of jumping back to the first hit.
781
+ const previous = activeRef.current
782
+ const next = previous >= 0 && previous < found.length ? previous : found.length - 1
783
+ activeRef.current = next
784
+ setActive(next)
785
+ applyHighlights(found, next)
786
+ }
787
+ const scheduleScan = (isFresh, delay) => {
788
+ window.clearTimeout(pendingTimer)
789
+ pendingTimer = window.setTimeout(() => {
790
+ lastSignature = signatureOf()
791
+ runScan(isFresh)
792
+ }, delay)
793
+ }
794
+ // The complete session log, independent of which turns the page has
795
+ // rendered: the counter tells the reader how many matches exist even
796
+ // when some of them are in history that has not been loaded yet.
797
+ const historyAbort = new AbortController()
798
+ if (sessionId !== null) {
799
+ setFullTotal(null)
800
+ postJson(SEARCH_ROUTE, { query, messagesOnly: false, limit: 30, sessionId }, historyAbort.signal)
801
+ .then((page) => {
802
+ if (historyAbort.signal.aborted) return
803
+ // Only the single-session answer carries a complete-log total; a
804
+ // Host version without that branch must not be mistaken for one.
805
+ if (page?.mode !== 'session') {
806
+ setFullTotal(null)
807
+ return
808
+ }
809
+ setFullTotal(typeof page.total === 'number' ? page.total : null)
810
+ })
811
+ .catch(() => {
812
+ if (!historyAbort.signal.aborted) setFullTotal(null)
813
+ })
814
+ }
815
+ scheduleScan(true, 200)
816
+ // The conversation virtualizes its rows: keep the match set in step
817
+ // with the rendered row window while the bar stays open.
818
+ const interval = window.setInterval(() => {
819
+ const current = signatureOf()
820
+ if (current !== lastSignature) scheduleScan(false, 150)
821
+ }, 500)
822
+ return () => {
823
+ historyAbort.abort()
824
+ window.clearTimeout(pendingTimer)
825
+ window.clearInterval(interval)
826
+ }
827
+ }, [open, query, awaitingEnter, sessionId, scanNonce])
828
+
829
+ const scrollToRange = (range) => {
830
+ try {
831
+ const element = range.startContainer.parentElement?.closest('[data-chat-anchor-key]')
832
+ const target = element || range.startContainer.parentElement
833
+ target?.scrollIntoView({ block: 'center', behavior: 'smooth' })
834
+ } catch {}
835
+ }
836
+
837
+ /** Apply one match index as the active, scrolled-to hit. */
838
+ const jumpTo = (index) => {
839
+ activeRef.current = index
840
+ setActive(index)
841
+ applyHighlights(ranges, index)
842
+ scrollToRange(ranges[index])
843
+ }
844
+
845
+ /**
846
+ * Move the active match. Reaching an edge stops there and reports it;
847
+ * repeating the same direction within 1.5s wraps around. Buttons and
848
+ * keyboard share this rule so both give the same edge feedback.
849
+ * @param {number} nextIndex - candidate index, possibly out of range.
850
+ */
851
+ const goto = (nextIndex) => {
852
+ if (ranges.length === 0) return
853
+ const edge = nextIndex < 0 ? 'start' : nextIndex >= ranges.length ? 'end' : null
854
+ if (edge !== null) {
855
+ const now = Date.now()
856
+ const last = lastBoundaryRef.current
857
+ if (last.edge === edge && now - last.at < 1500) {
858
+ lastBoundaryRef.current = { edge: null, at: 0 }
859
+ setBoundaryHint(null)
860
+ window.clearTimeout(boundaryTimerRef.current)
861
+ jumpTo(edge === 'end' ? 0 : ranges.length - 1)
862
+ return
863
+ }
864
+ lastBoundaryRef.current = { edge, at: now }
865
+ setBoundaryHint(edge)
866
+ window.clearTimeout(boundaryTimerRef.current)
867
+ boundaryTimerRef.current = window.setTimeout(() => setBoundaryHint(null), 1500)
868
+ return
869
+ }
870
+ lastBoundaryRef.current = { edge: null, at: 0 }
871
+ setBoundaryHint(null)
872
+ window.clearTimeout(boundaryTimerRef.current)
873
+ jumpTo((nextIndex + ranges.length) % ranges.length)
874
+ }
875
+
876
+ const onInputKeyDown = (event) => {
877
+ if (event.key === 'Enter') {
878
+ event.preventDefault()
879
+ // The prefilled selection has not scanned yet: Enter starts it.
880
+ if (awaitingEnter) {
881
+ setAwaitingEnter(false)
882
+ return
883
+ }
884
+ goto(active + (event.shiftKey ? -1 : 1))
885
+ } else if (event.key === 'ArrowDown') {
886
+ event.preventDefault()
887
+ if (awaitingEnter) {
888
+ setAwaitingEnter(false)
889
+ return
890
+ }
891
+ goto(active + 1)
892
+ } else if (event.key === 'ArrowUp') {
893
+ event.preventDefault()
894
+ if (awaitingEnter) {
895
+ setAwaitingEnter(false)
896
+ return
897
+ }
898
+ goto(active - 1)
899
+ }
900
+ }
901
+
902
+ const close = () => findStore.set({ open: false, focusRequest: 0, prefill: null })
903
+
904
+ /**
905
+ * Counter text: rendered position when there are highlights, plus the
906
+ * complete-log total when history holds more matches than are loaded.
907
+ * @returns {string} display text.
908
+ */
909
+ const countText = () => {
910
+ if (boundaryHint === 'end') return translate('find.atEnd')
911
+ if (boundaryHint === 'start') return translate('find.atStart')
912
+ // A prefilled selection has not been searched yet: keep the counter
913
+ // blank instead of reporting a false "no matches".
914
+ if (awaitingEnter) return ''
915
+ if (query.trim() === '') return ''
916
+ const rendered = ranges.length
917
+ if (rendered === 0) {
918
+ if (fullTotal !== null && fullTotal > 0) return translate('find.historyOnly', { count: fullTotal })
919
+ return translate('find.noMatches')
920
+ }
921
+ const base = active >= 0 ? `${active + 1}/${rendered}` : `0/${rendered}`
922
+ if (fullTotal !== null && fullTotal > rendered) {
923
+ return `${base} · ${translate('find.historyMore', { count: fullTotal })}`
924
+ }
925
+ return base
926
+ }
927
+
928
+ const iconProps = { viewBox: '0 0 24 24', width: 13, height: 13, 'aria-hidden': true }
929
+ const magnifier = h('svg', { viewBox: '0 0 24 24', width: 14, height: 14, 'aria-hidden': true },
930
+ h('circle', { cx: '11', cy: '11', r: '7', fill: 'none', stroke: 'currentColor', 'stroke-width': '2' }),
931
+ h('path', { d: 'm20 20-3.8-3.8', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round' }),
932
+ )
933
+
934
+ // A visible entry point stays in the header utilities row; the bar
935
+ // itself floats over the conversation through a body portal.
936
+ const bar = !open ? null : ReactDOM.createPortal(
937
+ h('div', { className: 'scs-find', 'data-scs-exclude': '', role: 'search' },
938
+ h('input', {
939
+ ref: inputRef,
940
+ className: 'scs-find-input',
941
+ type: 'text',
942
+ value: query,
943
+ placeholder: translate('find.placeholder'),
944
+ spellCheck: false,
945
+ onChange: (event) => {
946
+ setAwaitingEnter(false)
947
+ setQuery(event.target.value)
948
+ },
949
+ onKeyDown: onInputKeyDown,
950
+ }),
951
+ h('span', { className: 'scs-find-count' }, countText()),
952
+ h('button', {
953
+ type: 'button', className: 'scs-find-btn scs-find-start', title: translate('find.start'),
954
+ onClick: () => {
955
+ setAwaitingEnter(false)
956
+ setScanNonce((nonce) => nonce + 1)
957
+ },
958
+ disabled: query.trim() === '',
959
+ }, h('svg', { viewBox: '0 0 24 24', width: 13, height: 13, 'aria-hidden': true },
960
+ h('circle', { cx: '11', cy: '11', r: '6', fill: 'none', stroke: 'currentColor', 'stroke-width': '2' }),
961
+ h('path', { d: 'm20 20-3.5-3.5', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round' }),
962
+ )),
963
+ h('button', {
964
+ type: 'button', className: 'scs-find-btn', title: translate('find.open'),
965
+ onClick: () => goto(active - 1), disabled: ranges.length === 0,
966
+ }, h('svg', iconProps, h('path', { d: 'm18 15-6-6-6 6', fill: 'none', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }))),
967
+ h('button', {
968
+ type: 'button', className: 'scs-find-btn', title: translate('find.open'),
969
+ onClick: () => goto(active + 1), disabled: ranges.length === 0,
970
+ }, h('svg', iconProps, h('path', { d: 'm6 9 6 6 6-6', fill: 'none', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }))),
971
+ h('button', {
972
+ type: 'button', className: 'scs-find-btn scs-find-close', title: 'Esc',
973
+ onClick: close,
974
+ }, h('svg', iconProps, h('path', { d: 'M18 6 6 18M6 6l12 12', fill: 'none', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round' }))),
975
+ ),
976
+ document.body,
977
+ )
978
+
979
+ return [
980
+ h('button', {
981
+ type: 'button',
982
+ className: 'scs-utilities-btn' + (open ? ' scs-utilities-btn-active' : ''),
983
+ title: translate('find.open') + ' (Ctrl+F)',
984
+ 'aria-pressed': open,
985
+ onClick: () => findStore.set({ open: !open, focusRequest: (findStore.get().focusRequest || 0) + 1, prefill: null }),
986
+ }, magnifier),
987
+ bar,
988
+ ]
989
+ }
990
+
991
+ /* ------------------------------------------------------------------ *
992
+ * Sidebar foot button (sidebar.footer.action entry).
993
+ * ------------------------------------------------------------------ */
994
+
995
+ function SidebarButton(props) {
996
+ // The owner passes the sidebar width. Wide shows a full-width search
997
+ // pill (discoverable, reads as an input); the collapsed rail keeps a
998
+ // single icon button so the foot area never overflows.
999
+ const wide = props?.wide === true
1000
+ const label = translate('entry.label')
1001
+ const openPalette = () => paletteStore.set({ open: true })
1002
+ const magnifier = h('svg', {
1003
+ viewBox: '0 0 24 24', width: 14, height: 14, 'aria-hidden': true, className: 'scs-entry-icon',
1004
+ },
1005
+ h('circle', { cx: '11', cy: '11', r: '7', fill: 'none', stroke: 'currentColor', 'stroke-width': '2' }),
1006
+ h('path', { d: 'm20 20-3.8-3.8', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round' }),
1007
+ )
1008
+
1009
+ if (!wide) {
1010
+ return h('button', {
1011
+ type: 'button',
1012
+ className: 'scs-rail-btn',
1013
+ title: `${label} (Ctrl+Shift+F)`,
1014
+ 'aria-label': label,
1015
+ onClick: openPalette,
1016
+ }, magnifier)
1017
+ }
1018
+
1019
+ return h('div', { className: 'scs-entry-slot', 'data-scs-exclude': '' },
1020
+ h('button', {
1021
+ type: 'button',
1022
+ className: 'scs-entry',
1023
+ title: `${label} (Ctrl+Shift+F)`,
1024
+ 'aria-label': label,
1025
+ onClick: openPalette,
1026
+ },
1027
+ magnifier,
1028
+ h('span', { className: 'scs-entry-label' }, label),
1029
+ h('kbd', { className: 'scs-entry-kbd' }, translate('entry.keys')),
1030
+ ),
1031
+ )
1032
+ }
1033
+
1034
+ /* ------------------------------------------------------------------ *
1035
+ * Styles.
1036
+ * ------------------------------------------------------------------ */
1037
+
1038
+ const CSS_TEXT = `
1039
+ .scs-backdrop{position:fixed;inset:0;z-index:10000;background:rgba(0,0,0,.35);display:flex;align-items:flex-start;justify-content:center;padding-top:11vh}
1040
+ .scs-palette{width:min(680px,92vw);max-height:68vh;display:flex;flex-direction:column;overflow:hidden;background:var(--dsw-alias-bg-overlay);border:1px solid var(--dsw-alias-border-l2);border-radius:12px;box-shadow:0 16px 48px rgba(0,0,0,.3);color:var(--dsw-alias-label-primary)}
1041
+ .scs-palette-head{display:flex;align-items:center;gap:10px;padding:10px 12px;border-bottom:1px solid var(--dsw-alias-border-l1)}
1042
+ .scs-input{flex:1;min-width:0;background:var(--dsw-alias-bg-layer-1);border:1px solid var(--dsw-alias-border-l2);border-radius:8px;padding:8px 10px;font-size:14px;color:var(--dsw-alias-label-primary);outline:none}
1043
+ .scs-input:focus{border-color:var(--dsw-alias-brand-primary)}
1044
+ .scs-toggle{display:flex;align-items:center;gap:6px;flex:none;font-size:12px;color:var(--dsw-alias-label-secondary);cursor:pointer;white-space:nowrap;user-select:none}
1045
+ .scs-toggle input{accent-color:var(--dsw-alias-brand-primary);cursor:pointer}
1046
+ .scs-results{flex:1;overflow:auto;padding:6px}
1047
+ .scs-row{display:flex;flex-direction:column;gap:4px;padding:8px 10px;border-radius:8px;cursor:pointer}
1048
+ .scs-row-selected{background:var(--dsw-alias-bg-layer-2)}
1049
+ .scs-row-snippet{font-size:13px;line-height:1.5;color:var(--dsw-alias-label-primary);word-break:break-word;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
1050
+ .scs-row-meta{display:flex;align-items:center;gap:8px;font-size:12px;color:var(--dsw-alias-label-secondary);min-width:0}
1051
+ .scs-tag{flex:none;font-size:11px;line-height:16px;padding:0 6px;border-radius:999px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-secondary)}
1052
+ .scs-row-title{color:var(--dsw-alias-label-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1053
+ .scs-row-ws{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1054
+ .scs-row-ws::before{content:"·";margin-right:8px}
1055
+ .scs-row-time{margin-left:auto;flex:none}
1056
+ .scs-mark{background:var(--dsw-alias-state-warn-primary);color:var(--dsw-alias-bg-base);border-radius:2px;padding:0 1px}
1057
+ .scs-hint{padding:26px 16px;text-align:center;font-size:13px;color:var(--dsw-alias-label-secondary)}
1058
+ .scs-hint-error{color:var(--dsw-alias-state-error-primary)}
1059
+ .scs-error-detail{margin:0 6px 8px;padding:6px 10px;border:1px solid var(--dsw-alias-border-l1);border-radius:6px;background:var(--dsw-alias-bg-layer-1);font-size:11px;line-height:1.5;color:var(--dsw-alias-state-error-primary);word-break:break-all}
1060
+ .scs-more{display:block;margin:6px auto 10px;padding:6px 16px;font-size:12px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);cursor:pointer}
1061
+ .scs-more:hover{background:var(--dsw-alias-bg-layer-2)}
1062
+ .scs-palette-foot{display:flex;align-items:center;gap:10px;flex-wrap:wrap;padding:8px 12px;border-top:1px solid var(--dsw-alias-border-l1);font-size:11px;color:var(--dsw-alias-label-secondary)}
1063
+ .scs-foot-toggle{display:flex;align-items:center;gap:6px;flex:none;cursor:pointer;user-select:none;color:var(--dsw-alias-label-primary)}
1064
+ .scs-foot-toggle input{accent-color:var(--dsw-alias-brand-primary);cursor:pointer}
1065
+ .scs-foot-toggle-label{font-size:11px}
1066
+ .scs-foot-hint{flex:1;min-width:120px;font-size:10px;color:var(--dsw-alias-label-secondary);opacity:.85}
1067
+ .scs-foot-keys{flex:none;font-size:10px;color:var(--dsw-alias-label-secondary);opacity:.7}
1068
+ .scs-sidebar-btn{display:inline-flex;align-items:center;gap:6px;height:28px;padding:0 8px;border:none;border-radius:8px;background:transparent;color:var(--dsw-alias-label-secondary);font-size:12px;cursor:pointer}
1069
+ .scs-sidebar-btn:hover{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary)}
1070
+ .scs-entry-slot{width:100%;display:block}
1071
+ .scs-entry{display:flex;align-items:center;gap:8px;width:100%;height:32px;padding:0 9px;border:1px solid var(--dsw-alias-border-l1);border-radius:9px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font-size:12px;cursor:pointer;text-align:left}
1072
+ .scs-entry:hover{background:var(--dsw-alias-bg-layer-2);border-color:var(--dsw-alias-border-l2)}
1073
+ .scs-entry:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
1074
+ .scs-entry-icon{flex:none;color:var(--dsw-alias-brand-primary)}
1075
+ .scs-entry-label{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1076
+ .scs-entry-kbd{flex:none;font-family:inherit;font-size:9px;line-height:14px;padding:0 5px;border-radius:4px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-secondary);white-space:nowrap}
1077
+ .scs-rail-btn{width:30px;height:30px;display:inline-flex;align-items:center;justify-content:center;padding:0;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-brand-primary);cursor:pointer}
1078
+ .scs-rail-btn:hover{background:var(--dsw-alias-bg-layer-2);border-color:var(--dsw-alias-border-l2)}
1079
+ .scs-utilities-btn{width:26px;height:26px;display:inline-flex;align-items:center;justify-content:center;padding:0;border:none;border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer}
1080
+ .scs-utilities-btn:hover{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary)}
1081
+ .scs-utilities-btn-active{color:var(--dsw-alias-brand-primary)}
1082
+ .scs-find{position:fixed;top:60px;right:16px;z-index:10000;display:flex;align-items:center;gap:6px;padding:6px 8px;background:var(--dsw-alias-bg-overlay);border:1px solid var(--dsw-alias-border-l2);border-radius:10px;box-shadow:0 8px 24px rgba(0,0,0,.25);color:var(--dsw-alias-label-primary)}
1083
+ .scs-find-input{width:200px;background:var(--dsw-alias-bg-layer-1);border:1px solid var(--dsw-alias-border-l2);border-radius:6px;padding:4px 8px;font-size:13px;color:var(--dsw-alias-label-primary);outline:none}
1084
+ .scs-find-input:focus{border-color:var(--dsw-alias-brand-primary)}
1085
+ .scs-find-count{min-width:40px;max-width:220px;overflow:hidden;text-overflow:ellipsis;text-align:center;font-size:12px;color:var(--dsw-alias-label-secondary);white-space:nowrap}
1086
+ .scs-find-btn{width:24px;height:24px;display:inline-flex;align-items:center;justify-content:center;padding:0;border:1px solid var(--dsw-alias-border-l1);border-radius:6px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-secondary);cursor:pointer}
1087
+ .scs-find-btn:hover:not(:disabled){color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-2)}
1088
+ .scs-find-btn:disabled{opacity:.45;cursor:default}
1089
+ .scs-find-close{border-color:transparent;background:transparent}
1090
+ ::highlight(scs-find){background:rgba(250, 204, 21, 0.55)}
1091
+ ::highlight(scs-find-active){background:rgba(37, 99, 235, 0.85);color:#ffffff}
1092
+ `
1093
+
1094
+ /* ------------------------------------------------------------------ *
1095
+ * Plugin entry.
1096
+ * ------------------------------------------------------------------ */
1097
+
1098
+ return {
1099
+ inject: ['slots', 'locale', 'sessions', 'uiWorkspace'],
1100
+ apply(ctx) {
1101
+ sharedCtx = ctx
1102
+
1103
+ // Locale dictionaries for this plugin's UI text.
1104
+ ctx.effect(() => {
1105
+ const disposers = []
1106
+ try {
1107
+ disposers.push(ctx.locale.register(NS, 'en', en))
1108
+ disposers.push(ctx.locale.register(NS, 'zh', zh))
1109
+ } catch (error) {
1110
+ console.error('[session-content-search] locale registration failed:', error)
1111
+ }
1112
+ try {
1113
+ const snapshot = ctx.locale.getSnapshot()
1114
+ tagLocale = String(snapshot?.active || 'en').toLowerCase().startsWith('zh') ? 'zh' : 'en'
1115
+ } catch {}
1116
+ translate = ctx.locale.bind(NS)
1117
+ return () => {
1118
+ for (const dispose of disposers) {
1119
+ try {
1120
+ dispose()
1121
+ } catch {}
1122
+ }
1123
+ }
1124
+ }, 'session-content-search: locale')
1125
+
1126
+ // Shortcuts: Ctrl+Shift+F opens the palette, Ctrl+F the find bar,
1127
+ // Escape closes whichever is open. Capture phase, with editable
1128
+ // targets left to their own editors.
1129
+ ctx.effect(() => {
1130
+ const onKeyDown = (event) => {
1131
+ if (event.defaultPrevented) return
1132
+ const mod = event.ctrlKey || event.metaKey
1133
+ if (event.key === 'Escape') {
1134
+ if (paletteStore.get().open) {
1135
+ event.preventDefault()
1136
+ event.stopPropagation()
1137
+ paletteStore.set({ open: false })
1138
+ } else if (findStore.get().open) {
1139
+ const target = event.target
1140
+ const insideFind = target instanceof Element && target.closest('[data-scs-exclude]') !== null
1141
+ if (insideFind) {
1142
+ event.preventDefault()
1143
+ event.stopPropagation()
1144
+ }
1145
+ findStore.set({ open: false, focusRequest: 0, prefill: null })
1146
+ }
1147
+ return
1148
+ }
1149
+ if (!mod || event.altKey) return
1150
+ if (event.code !== 'KeyF') return
1151
+ const target = event.target
1152
+ const editable = target instanceof Element
1153
+ && target.closest('input, textarea, select, [contenteditable="true"], [contenteditable=""]') !== null
1154
+ if (editable) return
1155
+ event.preventDefault()
1156
+ event.stopPropagation()
1157
+ if (event.shiftKey) {
1158
+ findStore.set({ open: false, focusRequest: 0, prefill: null })
1159
+ paletteStore.set({ open: true })
1160
+ } else {
1161
+ // The find bar needs a conversation: without an open session
1162
+ // there is nothing rendered to search.
1163
+ if (currentSessionId() === null) return
1164
+ const current = findStore.get()
1165
+ paletteStore.set({ open: false })
1166
+ // A page selection prefills the box and waits for Enter, so a
1167
+ // quick read of the selected phrase never triggers a scan.
1168
+ const picked = selectedText()
1169
+ findStore.set({
1170
+ open: true,
1171
+ focusRequest: (current.focusRequest || 0) + 1,
1172
+ prefill: picked === ''
1173
+ ? null
1174
+ : { text: picked, nonce: ((current.prefill?.nonce || 0) + 1) },
1175
+ })
1176
+ }
1177
+ }
1178
+ document.addEventListener('keydown', onKeyDown, true)
1179
+ return () => document.removeEventListener('keydown', onKeyDown, true)
1180
+ }, 'session-content-search: shortcuts')
1181
+
1182
+ // Shared stylesheet; removed when the plugin unloads.
1183
+ ctx.effect(() => {
1184
+ const tag = document.createElement('style')
1185
+ tag.dataset.plugin = PLUGIN_ID
1186
+ tag.textContent = CSS_TEXT
1187
+ document.head.append(tag)
1188
+ return () => tag.remove()
1189
+ }, 'session-content-search: styles')
1190
+
1191
+ // Cross-workspace search palette, floating above the whole frame.
1192
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register(
1193
+ { name: 'shell.overlay', id: 'session-content-search.palette', order: 60, label: 'Session content search' },
1194
+ PaletteOverlay,
1195
+ ))
1196
+
1197
+ // Sidebar foot entry point.
1198
+ ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register(
1199
+ { name: 'sidebar.footer.action', id: 'session-content-search.button', order: 50, label: () => translate('palette.open') },
1200
+ SidebarButton,
1201
+ ))
1202
+
1203
+ // In-conversation find bar; the owner mounts it per open session.
1204
+ ctx.slots.inject('conversation.session.header.utilities', () => ctx.slots.register(
1205
+ { name: 'conversation.session.header.utilities', id: 'session-content-search.find', order: 80, label: () => translate('find.open') },
1206
+ FindBar,
1207
+ ))
1208
+ },
1209
+ }
1210
+ },
1211
+ })