@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.
@@ -0,0 +1,5 @@
1
+ # 本 bundle 的组合:只插入本插件一行,不改动任何官方行或官方配置。
2
+ - insert:
3
+ - id: session-content-search
4
+ name: '@hapyp/dsh-session-search'
5
+ config: {}
package/docs/DETAIL.md ADDED
@@ -0,0 +1,42 @@
1
+ # Session content search
2
+
3
+ Adds two search surfaces that the built-in sidebar search box does not provide:
4
+
5
+ 1. **Cross-workspace content palette** — press `Ctrl+Shift+F` or click the magnifier
6
+ button at the sidebar foot. Type a keyword to full-text search the content of
7
+ **all sessions in every workspace**, including user messages, assistant replies,
8
+ tool calls (name + arguments), tool results, and todo entries. Pick a result to
9
+ open that session. `Enter` opens the selected row, `↑`/`↓` move, `Esc` closes,
10
+ and *Load more* pages through further hits.
11
+ 2. **In-conversation find bar** — press `Ctrl+F` while a conversation is open (when
12
+ the focus is not in a text editor). A find bar appears over the conversation and
13
+ highlights every match in the currently rendered chat rows, with match counter,
14
+ previous/next navigation, and smooth scrolling to each match. `Enter` / `Shift+Enter`
15
+ step through matches, `Esc` closes.
16
+
17
+ ## How it works
18
+
19
+ - The browser half renders the palette, find bar, and sidebar button, and talks to
20
+ the Host half through an authenticated same-origin `/api` route.
21
+ - The Host half forwards queries to DSH's own `ctx.sessionQuery` full-text service
22
+ (the SQLite FTS5 backend mounted by the built-in **Session search** plugin) and
23
+ returns ranked hits with plain-text snippets. It never reads or writes session
24
+ storage directly.
25
+
26
+ ## Requirements and limits
27
+
28
+ - Full-text search needs the built-in **Session search** plugin to be enabled; when
29
+ it is off, the palette explains that the backend is missing instead of failing
30
+ silently.
31
+ - Matching is a **literal, case-insensitive, whitespace-flexible substring scan**:
32
+ a fragment inside a word matches (`AI` finds `BRAID`), and words separated by
33
+ arbitrary whitespace match each other. It is not token- or phrase-based.
34
+ - Reasoning ("thinking") text is not indexed by DSH and therefore not searchable.
35
+ - The `Ctrl+F` find bar searches what the conversation currently has rendered;
36
+ very old turns that are not rendered yet are covered by the cross-workspace
37
+ palette instead.
38
+ - The palette scans a bounded window of the newest sessions first (approximately
39
+ forty), so results arrive in a few seconds. When you need older sessions, use
40
+ *Scan older sessions* to page further. Inactive sessions are cached in Host
41
+ memory once read (never on disk, at most 128 MB), so repeat searches over
42
+ already-scanned sessions are near-instant.
@@ -0,0 +1,32 @@
1
+ # 会话内容搜索
2
+
3
+ 补上内置侧栏搜索框不具备的两个搜索入口:
4
+
5
+ 1. **跨工作区内容搜索面板** — 按 `Ctrl+Shift+F`,或点击侧栏底部的放大镜按钮。
6
+ 输入关键字即可对**所有工作区中的全部会话**做全文搜索,覆盖用户消息、助手回复、
7
+ 工具调用(名称 + 参数)、工具结果与任务清单条目。点击结果即可打开对应会话。
8
+ `Enter` 打开选中项,`↑`/`↓` 移动选择,`Esc` 关闭;命中较多时可点“加载更多”翻页。
9
+ 2. **会话内查找栏** — 在会话中按 `Ctrl+F`(焦点不在文本编辑器内时生效)。会在会话
10
+ 上方浮出查找栏,高亮当前已渲染的聊天内容中的全部匹配项,带命中计数、上一个/下一个
11
+ 导航并平滑滚动定位。`Enter` / `Shift+Enter` 逐个跳转,`Esc` 关闭。
12
+
13
+ ## 工作原理
14
+
15
+ - 浏览器半部负责渲染搜索面板、查找栏与侧栏按钮,并通过同源鉴权的 `/api` 路由
16
+ 调用 Host 半部。
17
+ - Host 半部把查询转发给 DSH 自带的 `ctx.sessionQuery` 全文搜索服务(内置
18
+ **会话搜索** 插件挂载的 SQLite FTS5 后端),返回带排序与纯文本摘录的结果;
19
+ 不直接读写会话存储。
20
+
21
+ ## 要求与限制
22
+
23
+ - 全文搜索依赖内置 **会话搜索** 插件处于启用状态;若未启用,面板会明确提示
24
+ 缺少后端,而不是静默失败。
25
+ - 匹配规则是**字面、大小写不敏感、空白灵活的子串扫描**:词中片段也会命中
26
+ (`AI` 能命中 `BRAID`),词之间任意空白(含换行)都能匹配。不是按词元或短语匹配。
27
+ - 思考过程(reasoning)文本未被 DSH 索引,因此不可搜索。
28
+ - `Ctrl+F` 查找栏只覆盖会话当前已渲染的内容;尚未渲染的更早回合请改用
29
+ 跨工作区搜索面板。
30
+ - 搜索面板先扫描最近的一批会话(约 40 个),数秒内给出结果;需要更早的会话时
31
+ 点击“继续扫描更早的会话”向后翻页。非活跃会话在被读取过一次后会缓存在 Host
32
+ 内存中(不落盘、上限 128 MB),重复搜索已扫描过的会话接近即时。
package/icon.svg ADDED
@@ -0,0 +1,9 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
2
+ <!-- Original artwork: chat bubbles + magnifier, for @local/session-content-search -->
3
+ <rect x="4" y="4" width="56" height="56" rx="14" fill="#1f6feb" opacity="0.12"/>
4
+ <path d="M12 20c0-3.3 2.7-6 6-6h20c3.3 0 6 2.7 6 6v10c0 3.3-2.7 6-6 6H24l-7 6v-6h-1c-2.2 0-4-1.8-4-4V20z" fill="#1f6feb" opacity="0.55"/>
5
+ <path d="M20 17h18c1.7 0 3 1.3 3 3v9c0 1.7-1.3 3-3 3H25l-5 4.4V20c0-1.7 1.3-3 3-3z" fill="#ffffff" opacity="0.9"/>
6
+ <circle cx="40" cy="38" r="9" fill="none" stroke="#0b3d91" stroke-width="4"/>
7
+ <path d="M46.5 44.5L54 52" stroke="#0b3d91" stroke-width="5" stroke-linecap="round"/>
8
+ <circle cx="40" cy="38" r="5.2" fill="#ffffff" opacity="0.85"/>
9
+ </svg>
package/index.js ADDED
@@ -0,0 +1,482 @@
1
+ /** Host half of @local/session-content-search.
2
+ *
3
+ * Serves the browser half's palette over one authenticated same-origin
4
+ * `/api` route. Search itself is a *scan* over DSH's session-query service:
5
+ * `listSessions()` plus per-session `filterEvents()` with a literal-text
6
+ * clause. Those read-only paths work in every deployment — including the
7
+ * default Desktop composition whose FTS index row stays at `openAt: never`
8
+ * — and they never build or open a SQLite index, so a search can neither
9
+ * block the Host event loop nor mutate any storage.
10
+ *
11
+ * The provider is resolved at call time so the plugin keeps working (with an
12
+ * explicit error) when `sessionQuery` is missing entirely.
13
+ */
14
+
15
+ import { appendFileSync, existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
16
+ import { tmpdir } from 'node:os'
17
+ import { join } from 'node:path'
18
+
19
+ /** The connection service is required: it owns the `/api` route table. */
20
+ export const inject = ['connection']
21
+
22
+ /** Absolute route below `/api` that answers search POSTs. */
23
+ const SEARCH_ROUTE = '/api/session-content-search/search'
24
+
25
+ const DEFAULT_LIMIT = 30
26
+ const MAX_LIMIT = 100
27
+ const MAX_QUERY_CHARS = 512
28
+ /** Events kept per session for result ordering; one hit per session is returned. */
29
+ const MAX_DOCS_PER_SESSION = 20
30
+ /** Sessions visited in one request; live and newest sessions are scanned first. */
31
+ const SCAN_WINDOW = 40
32
+ /** Hard ceiling for one request regardless of the requested window. */
33
+ const MAX_SESSIONS_PER_SCAN = 200
34
+ /** Overlapping read/filter calls; keeps large logs from serializing the scan. */
35
+ const SCAN_CONCURRENCY = 8
36
+ const SNIPPET_CHARS = 220
37
+ /** Filter that returns every current-surface semantic document of a session. */
38
+ const ALL_CURRENT_FILTERS = [{ kind: 'surface', values: ['current'] }]
39
+ /**
40
+ * Cold sessions never change while they stay cold, so their full semantic
41
+ * documents are cached in memory (never on disk, never in SQLite) and every
42
+ * later search matches locally. The budget bounds the cache; least recently
43
+ * used sessions are evicted first.
44
+ */
45
+ const COLD_DOC_CACHE_MAX_BYTES = 128 * 1024 * 1024
46
+ /** On-disk copy of the cold-document cache so first searches after a restart are warm. */
47
+ const PERSIST_FILE = join(tmpdir(), 'session-content-search-cache.v1.json')
48
+ const PERSIST_VERSION = 1
49
+ /** Bytes budget for the on-disk copy; it is a warm-start aid, not an index. */
50
+ const PERSIST_MAX_BYTES = 48 * 1024 * 1024
51
+ const PERSIST_DELAY_MS = 3000
52
+ /** Tests disable every disk touch; the cache itself is opt-in per request. */
53
+ const PERSIST_KILL = process.env.SESSION_CONTENT_SEARCH_NO_PERSIST === '1'
54
+ /** Diagnostics are off by default: a public plugin must not log user content. */
55
+ const DEBUG_LOG = process.env.SESSION_CONTENT_SEARCH_DEBUG === '1'
56
+
57
+ /** @type {Map<string, { docs: object[], bytes: number }>} */
58
+ const coldDocCache = new Map()
59
+ let coldDocCacheBytes = 0
60
+ let persistLoaded = false
61
+ let persistTimer = null
62
+
63
+ /**
64
+ * Read one cold session's cached documents and refresh its LRU position.
65
+ * @param {string} sessionId - session id.
66
+ * @returns {object[] | undefined} cached documents.
67
+ */
68
+ function cacheGet(sessionId) {
69
+ const entry = coldDocCache.get(sessionId)
70
+ if (entry === undefined) return undefined
71
+ coldDocCache.delete(sessionId)
72
+ coldDocCache.set(sessionId, entry)
73
+ return entry.docs
74
+ }
75
+
76
+ /**
77
+ * Cache one cold session's full semantic documents, evicting oldest entries.
78
+ * @param {string} sessionId - session id.
79
+ * @param {object[]} docs - every current-surface document of the session.
80
+ * @param {boolean} allowPersist - whether this search may schedule a disk write.
81
+ * @returns {void}
82
+ */
83
+ function cacheSet(sessionId, docs, allowPersist) {
84
+ let bytes = 0
85
+ for (const doc of docs) {
86
+ // Measure the on-disk JSON footprint in real UTF-8 bytes so the persist
87
+ // budget stays a hard cap for CJK-heavy text as well.
88
+ bytes += (typeof doc.text === 'string' ? Buffer.byteLength(doc.text, 'utf8') : 0) + 64
89
+ }
90
+ if (bytes > COLD_DOC_CACHE_MAX_BYTES) return
91
+ const existing = coldDocCache.get(sessionId)
92
+ if (existing !== undefined) {
93
+ coldDocCacheBytes -= existing.bytes
94
+ coldDocCache.delete(sessionId)
95
+ }
96
+ coldDocCache.set(sessionId, { docs, bytes })
97
+ coldDocCacheBytes += bytes
98
+ while (coldDocCacheBytes > COLD_DOC_CACHE_MAX_BYTES) {
99
+ const oldest = coldDocCache.keys().next().value
100
+ if (oldest === undefined) break
101
+ const entry = coldDocCache.get(oldest)
102
+ coldDocCache.delete(oldest)
103
+ coldDocCacheBytes -= entry?.bytes ?? 0
104
+ }
105
+ schedulePersist(allowPersist)
106
+ }
107
+
108
+ /**
109
+ * Remove one session's cached documents. A session that went live may have
110
+ * grown new events since it was cached, so its entry must be rebuilt.
111
+ * @param {string} sessionId - session id.
112
+ * @returns {void}
113
+ */
114
+ function cacheDelete(sessionId) {
115
+ const entry = coldDocCache.get(sessionId)
116
+ if (entry === undefined) return
117
+ coldDocCache.delete(sessionId)
118
+ coldDocCacheBytes -= entry.bytes
119
+ }
120
+
121
+ /**
122
+ * Load the on-disk cold-document cache once, honouring the in-memory budget.
123
+ * Disk caching is opt-in per search, so nothing is read unless asked.
124
+ * @param {boolean} allowPersist - whether this search enabled disk caching.
125
+ * @returns {void}
126
+ */
127
+ function loadPersistentCache(allowPersist) {
128
+ if (persistLoaded) return
129
+ if (!allowPersist || PERSIST_KILL) return
130
+ persistLoaded = true
131
+ try {
132
+ if (!existsSync(PERSIST_FILE)) return
133
+ const data = JSON.parse(readFileSync(PERSIST_FILE, 'utf8'))
134
+ if (data === null || typeof data !== 'object' || data.version !== PERSIST_VERSION) return
135
+ if (!Array.isArray(data.entries)) return
136
+ for (const entry of data.entries) {
137
+ if (entry === null || typeof entry !== 'object') continue
138
+ if (typeof entry.sessionId !== 'string' || !Array.isArray(entry.docs)) continue
139
+ cacheSet(entry.sessionId, entry.docs, false)
140
+ }
141
+ logLine('cache', `loaded ${coldDocCache.size} warm session(s)`)
142
+ } catch (error) {
143
+ logLine('warn', `cache load failed: ${String(error?.message ?? error)}`)
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Persist the cold-document cache after a quiet period. Writes are best
149
+ * effort, bounded, never block a search answer, and only happen when the
150
+ * person enabled disk caching.
151
+ * @param {boolean} allowPersist - whether disk caching is enabled.
152
+ * @returns {void}
153
+ */
154
+ function schedulePersist(allowPersist) {
155
+ if (!allowPersist || PERSIST_KILL || persistTimer !== null) return
156
+ persistTimer = setTimeout(() => {
157
+ persistTimer = null
158
+ try {
159
+ let entries = []
160
+ let bytes = 0
161
+ for (const [sessionId, entry] of coldDocCache) {
162
+ if (entries.length > 0 && bytes + entry.bytes > PERSIST_MAX_BYTES) break
163
+ bytes += entry.bytes
164
+ entries.push({ sessionId, docs: entry.docs })
165
+ }
166
+ let payload = JSON.stringify({ version: PERSIST_VERSION, savedAt: Date.now(), entries })
167
+ // The serialized size carries JSON escaping the per-document estimate
168
+ // cannot see; keep the written file inside the same hard budget.
169
+ while (entries.length > 1 && Buffer.byteLength(payload, 'utf8') > PERSIST_MAX_BYTES) {
170
+ entries = entries.slice(0, Math.max(1, Math.floor(entries.length / 2)))
171
+ payload = JSON.stringify({ version: PERSIST_VERSION, savedAt: Date.now(), entries })
172
+ }
173
+ // Replace atomically: another Host process may write the same warm copy.
174
+ const temporary = `${PERSIST_FILE}.${process.pid}.tmp`
175
+ writeFileSync(temporary, payload, 'utf8')
176
+ renameSync(temporary, PERSIST_FILE)
177
+ logLine('cache', `persisted ${entries.length} session(s), ${Math.round(Buffer.byteLength(payload, 'utf8') / 1024)} KiB`)
178
+ } catch (error) {
179
+ logLine('warn', `cache persist failed: ${String(error?.message ?? error)}`)
180
+ }
181
+ }, PERSIST_DELAY_MS)
182
+ // Never keep the Host alive only for a cache write.
183
+ persistTimer.unref?.()
184
+ }
185
+
186
+ /**
187
+ * Collapse whitespace and case for literal comparison, matching the
188
+ * session-query text clause's whitespace-flexible literal scan.
189
+ * @param {string} value - text to normalize.
190
+ * @returns {string} normalized text.
191
+ */
192
+ function normalizeText(value) {
193
+ return String(value).replace(/\s+/gu, ' ').trim().toLowerCase()
194
+ }
195
+
196
+ /**
197
+ * Match cached documents locally: current surface, message types when asked,
198
+ * literal whitespace-flexible substring.
199
+ * @param {object[]} docs - every current-surface document.
200
+ * @param {string} needle - normalized query.
201
+ * @param {boolean} messagesOnly - restrict to user/assistant messages.
202
+ * @returns {object[]} matching documents.
203
+ */
204
+ function matchDocuments(docs, needle, messagesOnly) {
205
+ const matched = []
206
+ for (const doc of docs) {
207
+ if (messagesOnly && doc.type !== 'user/message' && doc.type !== 'assistant/message') continue
208
+ if (normalizeText(doc.text ?? '').includes(needle)) matched.push(doc)
209
+ }
210
+ return matched
211
+ }
212
+
213
+ /**
214
+ * Append one diagnostic line. The profile directory is preferred when the
215
+ * Host process exposes it; the OS temp directory is the always-writable
216
+ * fallback (the Host main process may not inherit profile variables).
217
+ * Best effort by design: diagnostics never break the search answer.
218
+ * @param {string} kind - event tag, e.g. `request`, `ok`, `error`.
219
+ * @param {string} text - already-formatted detail.
220
+ * @returns {void}
221
+ */
222
+ function logLine(kind, text) {
223
+ if (!DEBUG_LOG) return
224
+ const line = `${new Date().toISOString()} [${kind}] ${text}\n`
225
+ try {
226
+ const dir = process.env.DSH_PROFILE_DIR
227
+ if (typeof dir === 'string' && dir !== '') {
228
+ appendFileSync(join(dir, 'session-content-search.log'), line, 'utf8')
229
+ return
230
+ }
231
+ } catch {}
232
+ try {
233
+ appendFileSync(join(tmpdir(), 'session-content-search.log'), line, 'utf8')
234
+ } catch {}
235
+ }
236
+
237
+ /**
238
+ * Activate the Host half.
239
+ * @param {import('@deepseek-ai/cordis').Context} ctx - plugin context.
240
+ * @returns {void}
241
+ */
242
+ export function apply(ctx) {
243
+ ctx.effect(
244
+ () =>
245
+ ctx.connection.fetch.register({
246
+ path: SEARCH_ROUTE,
247
+ methods: ['POST'],
248
+ requestBody: 'buffered',
249
+ fetch: (request) => handleSearch(request, ctx),
250
+ }),
251
+ 'session-content-search: search route',
252
+ )
253
+ }
254
+
255
+ /**
256
+ * Serve one search request.
257
+ * Body: `{ query, messagesOnly?, limit? }`.
258
+ * @param {Request} request - incoming request; its signal aborts the scan.
259
+ * @param {import('@deepseek-ai/cordis').Context} ctx - plugin context.
260
+ * @returns {Promise<Response>} JSON answer.
261
+ */
262
+ async function handleSearch(request, ctx) {
263
+ let body
264
+ try {
265
+ body = await request.json()
266
+ } catch {
267
+ return json({ error: 'invalid-json' }, 400)
268
+ }
269
+ // A request the browser superseded or cancelled never starts a scan.
270
+ if (request.signal.aborted) return json({ error: 'cancelled' }, 499)
271
+ const query = typeof body?.query === 'string' ? body.query.trim() : ''
272
+ if (query.length === 0) return json({ error: 'empty-query' }, 400)
273
+ if (query.length > MAX_QUERY_CHARS) {
274
+ return json({ error: 'query-too-long', message: `query must contain at most ${MAX_QUERY_CHARS} characters` }, 400)
275
+ }
276
+ if (query.includes('\0')) return json({ error: 'empty-query' }, 400)
277
+
278
+ const provider = ctx.get('sessionQuery')
279
+ if (provider === undefined || typeof provider.listSessions !== 'function'
280
+ || typeof provider.filterEvents !== 'function') {
281
+ logLine('error', 'sessionQuery read/filter capability is unavailable')
282
+ return json(
283
+ { error: 'search-unavailable', message: 'session-query service is not mounted (enable the built-in Session search plugin)' },
284
+ 503,
285
+ )
286
+ }
287
+
288
+ const limit = clampLimit(body?.limit)
289
+ const messagesOnly = body?.messagesOnly === true
290
+ const scanOffset = Number.isSafeInteger(body?.scanOffset) && body.scanOffset > 0 ? body.scanOffset : 0
291
+ const startedAt = Date.now()
292
+ logLine(
293
+ 'request',
294
+ `query=${JSON.stringify(query)} sessionId=${typeof body?.sessionId === 'string' ? body.sessionId : '-'} ` +
295
+ `messagesOnly=${String(messagesOnly)} limit=${limit} offset=${scanOffset} mode=${typeof body?.sessionId === 'string' && body.sessionId !== '' ? 'session' : 'scan'}`,
296
+ )
297
+
298
+ try {
299
+ // One session's complete log (the Ctrl+F find bar): reads every current
300
+ // document of that session, so matches include turns the page has not
301
+ // rendered yet.
302
+ if (typeof body?.sessionId === 'string' && body.sessionId !== '') {
303
+ const filters = [
304
+ { kind: 'text', text: query },
305
+ { kind: 'surface', values: ['current'] },
306
+ ]
307
+ if (messagesOnly) filters.push({ kind: 'type', values: ['user/message', 'assistant/message'] })
308
+ const documents = await provider.filterEvents(body.sessionId, filters)
309
+ logLine('ok', `session ${body.sessionId}: ${documents.length} hit(s) in ${Date.now() - startedAt}ms`)
310
+ return json({
311
+ mode: 'session',
312
+ items: documents.map((doc) => ({
313
+ seq: doc.seq,
314
+ type: doc.type,
315
+ time: doc.time,
316
+ surface: doc.surface,
317
+ snippet: snippetAround(doc.text ?? '', query),
318
+ })),
319
+ total: documents.length,
320
+ nextOffset: null,
321
+ })
322
+ }
323
+
324
+ const result = await scanSessions(provider, query, {
325
+ limit,
326
+ messagesOnly,
327
+ scanOffset,
328
+ allowPersist: body?.cache === true,
329
+ signal: request.signal,
330
+ })
331
+ logLine(
332
+ 'ok',
333
+ `${result.items.length} hit(s) from ${result.scanned}/${result.total} session(s) in ${Date.now() - startedAt}ms` +
334
+ (result.nextOffset === null ? '' : ` next=${result.nextOffset}`),
335
+ )
336
+ return json(result)
337
+ } catch (error) {
338
+ if (request.signal.aborted) return json({ error: 'cancelled' }, 499)
339
+ const code = error !== null && typeof error === 'object' && 'code' in error ? String(error.code) : 'search-failed'
340
+ const message = error instanceof Error ? error.message : String(error)
341
+ const stack = error instanceof Error && typeof error.stack === 'string' ? error.stack : ''
342
+ logLine('error', `${code}: ${message}${stack === '' ? '' : `\n${stack}`}`)
343
+ ctx.logger?.warn?.(`session-content-search: search failed: ${message}`)
344
+ return json({ error: 'search-failed', code, message }, 500)
345
+ }
346
+ }
347
+
348
+ /**
349
+ * Scan the newest sessions with provider-independent literal-text predicates.
350
+ * One request covers a bounded window of sessions so the palette answers
351
+ * quickly and pages on demand; each visited session is one `filterEvents`
352
+ * read of its own log, isolated so one damaged log cannot fail the search.
353
+ * @param {object} provider - `ctx.sessionQuery` face.
354
+ * @param {string} query - non-blank literal text.
355
+ * @param {{ limit: number, messagesOnly: boolean, scanOffset: number, allowPersist: boolean, signal: AbortSignal }} options - bounds.
356
+ * @returns {Promise<object>} wire payload.
357
+ */
358
+ async function scanSessions(provider, query, options) {
359
+ const { limit, messagesOnly, scanOffset, allowPersist, signal } = options
360
+ loadPersistentCache(allowPersist)
361
+ const records = await provider.listSessions(signal)
362
+ // Live sessions answer from memory without reading their logs, and the
363
+ // sessions a person searches most are the ones they recently worked in.
364
+ const candidates = [...records].sort(
365
+ (left, right) => (Number(right.live === true) - Number(left.live === true))
366
+ || ((right.header.createdAt ?? 0) - (left.header.createdAt ?? 0)),
367
+ )
368
+ const window = candidates.slice(scanOffset, scanOffset + Math.min(SCAN_WINDOW, MAX_SESSIONS_PER_SCAN))
369
+ const needle = normalizeText(query)
370
+ const liveFilters = [
371
+ { kind: 'text', text: query },
372
+ { kind: 'surface', values: ['current'] },
373
+ ]
374
+ if (messagesOnly) {
375
+ liveFilters.push({ kind: 'type', values: ['user/message', 'assistant/message'] })
376
+ }
377
+
378
+ const items = []
379
+ let scanned = 0
380
+ for (let offset = 0; offset < window.length && items.length < limit; offset += SCAN_CONCURRENCY) {
381
+ signal.throwIfAborted()
382
+ const batch = window.slice(offset, offset + SCAN_CONCURRENCY)
383
+ scanned += batch.length
384
+ // One failing log must not fail its batch: each slot resolves to a hit,
385
+ // null (no match), or undefined (failed).
386
+ const settled = await Promise.all(batch.map(async (record) => {
387
+ const sessionId = record.header.id
388
+ try {
389
+ let documents
390
+ if (record.live === true) {
391
+ // Live content changes between calls, so it is always read fresh;
392
+ // a session that went live may also have outgrown its cached copy.
393
+ cacheDelete(sessionId)
394
+ documents = await provider.filterEvents(sessionId, liveFilters)
395
+ } else {
396
+ const cached = cacheGet(sessionId)
397
+ if (cached !== undefined) {
398
+ documents = matchDocuments(cached, needle, messagesOnly)
399
+ } else {
400
+ // One read of the frozen session: cache every document, then match.
401
+ const all = await provider.filterEvents(sessionId, ALL_CURRENT_FILTERS)
402
+ cacheSet(sessionId, all, allowPersist)
403
+ documents = matchDocuments(all, needle, messagesOnly)
404
+ }
405
+ }
406
+ if (documents.length === 0) return null
407
+ // The scan returns every match in the session; the newest matching
408
+ // document is the strongest signal for the session row.
409
+ const selected = documents.slice(-MAX_DOCS_PER_SESSION)
410
+ const best = selected[selected.length - 1]
411
+ return {
412
+ sessionId,
413
+ cwd: record.header.cwd ?? null,
414
+ live: record.live === true,
415
+ seq: best.seq,
416
+ type: best.type,
417
+ time: best.time,
418
+ surface: best.surface,
419
+ snippet: snippetAround(best.text ?? '', query),
420
+ }
421
+ } catch (error) {
422
+ if (signal.aborted) throw error
423
+ logLine('warn', `session ${sessionId} skipped: ${String(error?.message ?? error)}`)
424
+ return undefined
425
+ }
426
+ }))
427
+ for (const hit of settled) {
428
+ if (hit !== null && hit !== undefined) items.push(hit)
429
+ if (items.length >= limit) break
430
+ }
431
+ }
432
+ const nextOffset = scanOffset + window.length < candidates.length
433
+ ? scanOffset + window.length
434
+ : null
435
+ return {
436
+ mode: 'sessions',
437
+ items,
438
+ nextCursor: null,
439
+ nextOffset,
440
+ scanned: scanOffset + scanned,
441
+ total: candidates.length,
442
+ cached: coldDocCache.size,
443
+ }
444
+ }
445
+
446
+ /**
447
+ * Extract a plain-text excerpt around the first literal occurrence.
448
+ * @param {string} text - semantic document text.
449
+ * @param {string} query - literal query.
450
+ * @returns {string} excerpt of at most SNIPPET_CHARS characters.
451
+ */
452
+ function snippetAround(text, query) {
453
+ const source = typeof text === 'string' ? text : ''
454
+ if (source === '') return ''
455
+ const at = source.toLowerCase().indexOf(query.toLowerCase())
456
+ const start = at <= 0 ? 0 : Math.max(0, at - Math.floor(SNIPPET_CHARS / 3))
457
+ const excerpt = source.slice(start, start + SNIPPET_CHARS).replace(/\s+/g, ' ').trim()
458
+ return `${start > 0 ? '…' : ''}${excerpt}${start + SNIPPET_CHARS < source.length ? '…' : ''}`
459
+ }
460
+
461
+ /**
462
+ * Clamp a requested page size into the accepted range.
463
+ * @param {unknown} value - raw request field.
464
+ * @returns {number} limit between 1 and MAX_LIMIT.
465
+ */
466
+ function clampLimit(value) {
467
+ const parsed = typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : DEFAULT_LIMIT
468
+ return Math.min(MAX_LIMIT, Math.max(1, parsed))
469
+ }
470
+
471
+ /**
472
+ * Serialize one JSON answer.
473
+ * @param {unknown} data - JSON-serializable payload.
474
+ * @param {number} status - HTTP status code.
475
+ * @returns {Response} the answer.
476
+ */
477
+ function json(data, status) {
478
+ return new Response(JSON.stringify(data), {
479
+ status,
480
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
481
+ })
482
+ }
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Session content search",
4
+ "description": "Search message and tool text across every workspace from a palette (Ctrl+Shift+F or the sidebar button), and find inside the current conversation with Ctrl+F. Requires the built-in Session search backend.",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "会话内容搜索",
4
+ "description": "通过搜索面板(Ctrl+Shift+F 或侧栏按钮)跨所有工作区搜索会话的消息与工具文本;在会话中按 Ctrl+F 在当前对话内查找。需要内置的“会话搜索”后端。",
5
+ "detail": "docs/DETAIL.zh.md"
6
+ }
7
+ }