dsh-remote-plugin 0.8.8 → 0.9.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/README.en.md +16 -5
- package/README.md +15 -4
- package/apk/dsh-remote.apk +0 -0
- package/gateway.cjs +527 -78
- package/index.mjs +1 -0
- package/package.json +8 -3
- package/public/activity.js +53 -4
- package/public/admin.html +34 -33
- package/public/admin.js +10 -2
- package/public/app.js +1204 -174
- package/public/bc-integration.css +81 -0
- package/public/build.json +2 -2
- package/public/composer-tools.css +184 -0
- package/public/composer-tools.js +888 -0
- package/public/desktop/desktop.html +92 -73
- package/public/desktop/desktop.js +631 -77
- package/public/file-inbox.js +77 -18
- package/public/genui.css +10 -0
- package/public/genui.js +22 -4
- package/public/host-queue.js +232 -0
- package/public/host-schedule.js +301 -0
- package/public/host-state.css +19 -0
- package/public/index.html +330 -140
- package/public/md.js +21 -1
- package/public/network.js +33 -1
- package/public/onboarding.js +3 -3
- package/public/operations.js +4 -3
- package/public/plan-review.css +297 -0
- package/public/plan-review.js +621 -0
- package/public/plugin.html +29 -28
- package/public/relay-autopair.js +25 -10
- package/public/relay-settings.css +11 -0
- package/public/relay-settings.js +350 -28
- package/public/session-management.css +61 -0
- package/public/session-management.js +742 -0
- package/public/session-search.css +137 -0
- package/public/session-search.js +977 -0
- package/public/skins/blue-fish/preview.html +3 -3
- package/public/skins/bocchi/preview.html +5 -5
- package/public/skins/kita/preview.html +6 -6
- package/public/skins/miku/SOURCES.json +10 -0
- package/public/skins/miku/chibi.png +0 -0
- package/public/skins/miku/preview.html +33 -0
- package/public/skins/miku/skin.css +82 -0
- package/public/skins/nijika/preview.html +6 -6
- package/public/skins/penguin/preview.html +3 -3
- package/public/skins/ryo/preview.html +6 -6
- package/public/slash-suggestions.js +15 -3
- package/public/sponsor-entry.js +11 -3
- package/public/styles.css +141 -21
- package/public/subagents.css +5 -0
- package/public/subagents.js +52 -0
- package/public/theme-vars.css +65 -1
- package/public/theme.js +4 -3
- package/public/turn-diff.css +323 -0
- package/public/turn-diff.js +778 -0
- package/public/update.json +8 -8
- package/public/version.json +1 -1
- package/public/workflow.css +305 -34
- package/public/workflow.js +141 -41
|
@@ -0,0 +1,977 @@
|
|
|
1
|
+
/* dsh-remote session search — host-backed full-text search, workspace filter and hit locating.
|
|
2
|
+
*
|
|
3
|
+
* Everything in this module is transport-agnostic: the Host call, the catalog and
|
|
4
|
+
* navigation arrive through an explicit adapter (see init). The module never reads
|
|
5
|
+
* app.js lexical state and never treats a local title/ID filter as content search.
|
|
6
|
+
*/
|
|
7
|
+
;(function (root) {
|
|
8
|
+
'use strict'
|
|
9
|
+
|
|
10
|
+
const STATUS = Object.freeze({
|
|
11
|
+
IDLE: 'idle',
|
|
12
|
+
LOADING: 'loading',
|
|
13
|
+
RESULTS: 'results',
|
|
14
|
+
EMPTY: 'empty',
|
|
15
|
+
DENIED: 'denied',
|
|
16
|
+
ERROR: 'error',
|
|
17
|
+
UNSUPPORTED: 'unsupported',
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
/* Mirrored from @deepseek-ai/dsh-api-session-controller: the Host rejects a
|
|
21
|
+
* longer query and truncates snippets to this many code points. */
|
|
22
|
+
const MAX_QUERY_CHARS = 500
|
|
23
|
+
const MAX_SNIPPET_CODE_POINTS = 240
|
|
24
|
+
const HOST_RESULT_LIMIT = 20
|
|
25
|
+
const UNGROUPED = '__ungrouped__'
|
|
26
|
+
|
|
27
|
+
function isEnglish() { return !!root.I18N && root.I18N.lang === 'en' }
|
|
28
|
+
function text(zh, en) { return isEnglish() ? en : zh }
|
|
29
|
+
|
|
30
|
+
function esc(value) {
|
|
31
|
+
return String(value == null ? '' : value).replace(/[&<>"']/g, c => ({
|
|
32
|
+
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
|
|
33
|
+
}[c]))
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function clipCodePoints(value, max = MAX_SNIPPET_CODE_POINTS) {
|
|
37
|
+
const points = Array.from(String(value == null ? '' : value))
|
|
38
|
+
return points.length <= max ? points.join('') : points.slice(0, max).join('') + '…'
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Trim, reject blank/NUL/oversized queries exactly as the Host does. */
|
|
42
|
+
function normalizeQuery(raw) {
|
|
43
|
+
const value = String(raw == null ? '' : raw).trim()
|
|
44
|
+
if (!value) return { ok: false, query: '', error: 'empty', message: text('请输入搜索关键词', 'Enter a search query') }
|
|
45
|
+
if (value.includes('\0')) return { ok: false, query: '', error: 'nul', message: text('搜索关键词不能包含空字符', 'The query must not contain NUL') }
|
|
46
|
+
if (value.length > MAX_QUERY_CHARS) {
|
|
47
|
+
return { ok: false, query: '', error: 'too-long', message: text(`搜索关键词最多 ${MAX_QUERY_CHARS} 个字符`, `The query may contain at most ${MAX_QUERY_CHARS} characters`) }
|
|
48
|
+
}
|
|
49
|
+
return { ok: true, query: value, error: null, message: '' }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Cross-platform path key used only to resolve a session's workspace. */
|
|
53
|
+
function pathKey(value) {
|
|
54
|
+
let key = String(value == null ? '' : value).replace(/\\/g, '/').replace(/\/+/g, '/')
|
|
55
|
+
if (key.length > 1) key = key.replace(/\/+$/, '')
|
|
56
|
+
const windows = /^[A-Za-z]:\//.test(key) || String(value == null ? '' : value).includes('\\')
|
|
57
|
+
|| !!(root.navigator && /Windows/i.test(String(root.navigator.platform || root.navigator.userAgent || '')))
|
|
58
|
+
return windows ? key.toLowerCase() : key
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function baseName(value) {
|
|
62
|
+
const clean = String(value == null ? '' : value).replace(/[\\/]+$/, '')
|
|
63
|
+
return clean.split(/[\\/]/).pop() || clean
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function normalizeWorkspace(row) {
|
|
67
|
+
if (!row || typeof row !== 'object') return null
|
|
68
|
+
const workspaceId = typeof row.workspaceId === 'string' ? row.workspaceId : ''
|
|
69
|
+
if (!workspaceId) return null
|
|
70
|
+
const path = typeof row.path === 'string' ? row.path : ''
|
|
71
|
+
const title = typeof row.title === 'string' ? row.title.trim() : ''
|
|
72
|
+
return {
|
|
73
|
+
workspaceId,
|
|
74
|
+
path,
|
|
75
|
+
title,
|
|
76
|
+
name: title || baseName(path) || path,
|
|
77
|
+
sessionIds: Array.isArray(row.sessionIds) ? row.sessionIds.map(String) : [],
|
|
78
|
+
raw: row,
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function sessionTitle(session, titleOf) {
|
|
83
|
+
if (typeof titleOf === 'function') {
|
|
84
|
+
try {
|
|
85
|
+
const custom = titleOf(session)
|
|
86
|
+
if (typeof custom === 'string' && custom.trim()) return custom.trim()
|
|
87
|
+
} catch {}
|
|
88
|
+
}
|
|
89
|
+
const projected = session && session.projections && session.projections.values && session.projections.values.title
|
|
90
|
+
if (typeof projected === 'string' && projected.trim()) return projected.trim()
|
|
91
|
+
if (session && typeof session.title === 'string' && session.title.trim()) return session.title.trim()
|
|
92
|
+
const id = session && session.sessionId ? String(session.sessionId) : ''
|
|
93
|
+
return id ? text('未命名会话', 'Untitled conversation') + ' · ' + id.slice(-8) : text('未知会话', 'Unknown conversation')
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function workspaceForSession(session, workspaces) {
|
|
97
|
+
if (!session) return null
|
|
98
|
+
const sessionId = String(session.sessionId || '')
|
|
99
|
+
const explicit = typeof session.workspaceId === 'string' ? session.workspaceId : ''
|
|
100
|
+
if (explicit) {
|
|
101
|
+
const match = workspaces.find(workspace => workspace.workspaceId === explicit)
|
|
102
|
+
if (match) return match
|
|
103
|
+
}
|
|
104
|
+
if (sessionId) {
|
|
105
|
+
const member = workspaces.find(workspace => workspace.sessionIds.some(id => id === sessionId))
|
|
106
|
+
if (member) return member
|
|
107
|
+
}
|
|
108
|
+
const cwdKey = pathKey(session.cwd)
|
|
109
|
+
if (!cwdKey) return null
|
|
110
|
+
for (const workspace of workspaces) {
|
|
111
|
+
const workspaceKey = pathKey(workspace.path)
|
|
112
|
+
if (!workspaceKey) continue
|
|
113
|
+
if (cwdKey === workspaceKey || cwdKey.startsWith(workspaceKey.endsWith('/') ? workspaceKey : workspaceKey + '/')) return workspace
|
|
114
|
+
}
|
|
115
|
+
return null
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Fold Host session.list rows and workspace.list rows into one lookup.
|
|
120
|
+
* `archivedSessionIds`/`pinnedSessionIds` are registry-global Host sets.
|
|
121
|
+
*/
|
|
122
|
+
function normalizeCatalog(input = {}) {
|
|
123
|
+
const rawSessions = Array.isArray(input.sessions) ? input.sessions : []
|
|
124
|
+
const workspaces = (Array.isArray(input.workspaces) ? input.workspaces : []).map(normalizeWorkspace).filter(Boolean)
|
|
125
|
+
const archivedIds = new Set((Array.isArray(input.archivedSessionIds) ? input.archivedSessionIds : []).map(String))
|
|
126
|
+
const pinnedIds = new Set((Array.isArray(input.pinnedSessionIds) ? input.pinnedSessionIds : []).map(String))
|
|
127
|
+
const byId = new Map()
|
|
128
|
+
const sessions = []
|
|
129
|
+
for (const raw of rawSessions) {
|
|
130
|
+
if (!raw || typeof raw !== 'object' || !raw.sessionId) continue
|
|
131
|
+
const sessionId = String(raw.sessionId)
|
|
132
|
+
if (byId.has(sessionId)) continue
|
|
133
|
+
const workspace = workspaceForSession(raw, workspaces)
|
|
134
|
+
const entry = {
|
|
135
|
+
sessionId,
|
|
136
|
+
title: sessionTitle(raw, input.titleOf),
|
|
137
|
+
cwd: typeof raw.cwd === 'string' ? raw.cwd : '',
|
|
138
|
+
workspaceId: workspace ? workspace.workspaceId : '',
|
|
139
|
+
workspaceName: workspace ? workspace.name : '',
|
|
140
|
+
workspacePath: workspace ? workspace.path : (typeof raw.cwd === 'string' ? raw.cwd : ''),
|
|
141
|
+
archived: archivedIds.has(sessionId),
|
|
142
|
+
pinned: pinnedIds.has(sessionId),
|
|
143
|
+
origin: raw.origin,
|
|
144
|
+
blank: raw.blank === true,
|
|
145
|
+
raw,
|
|
146
|
+
}
|
|
147
|
+
sessions.push(entry)
|
|
148
|
+
byId.set(sessionId, entry)
|
|
149
|
+
}
|
|
150
|
+
return { sessions, byId, workspaces, archivedIds, pinnedIds }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** A session is visible in the normal list unless it is a subagent or a blank shell. */
|
|
154
|
+
function isVisibleCatalogSession(entry) {
|
|
155
|
+
return !!entry && entry.origin !== 'subagent' && !entry.blank
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function metadataMatchKinds(entry, query) {
|
|
159
|
+
const needle = String(query || '').toLowerCase()
|
|
160
|
+
if (!needle) return []
|
|
161
|
+
const kinds = []
|
|
162
|
+
if (String(entry.title || '').toLowerCase().includes(needle)) kinds.push('title')
|
|
163
|
+
if (String(entry.sessionId || '').toLowerCase().includes(needle)) kinds.push('sessionId')
|
|
164
|
+
return kinds
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function workspaceView(entry) {
|
|
168
|
+
if (!entry || !entry.workspaceId) return null
|
|
169
|
+
return {
|
|
170
|
+
workspaceId: entry.workspaceId,
|
|
171
|
+
name: entry.workspaceName,
|
|
172
|
+
path: entry.workspacePath,
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function entryMatchesFilters(entry, { workspaceId = '', includeArchived = false } = {}) {
|
|
177
|
+
if (!includeArchived && entry.archived) return false
|
|
178
|
+
if (workspaceId) {
|
|
179
|
+
if (workspaceId === UNGROUPED) return !entry.workspaceId
|
|
180
|
+
if (entry.workspaceId !== workspaceId) return false
|
|
181
|
+
}
|
|
182
|
+
return true
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function makeResult(entry, matchKinds, snippet, extra = {}) {
|
|
186
|
+
return {
|
|
187
|
+
sessionId: entry.sessionId,
|
|
188
|
+
title: entry.title,
|
|
189
|
+
workspace: workspaceView(entry),
|
|
190
|
+
snippet: snippet || '',
|
|
191
|
+
matchKinds,
|
|
192
|
+
archived: entry.archived,
|
|
193
|
+
pinned: entry.pinned,
|
|
194
|
+
unresolved: !!entry.unresolved,
|
|
195
|
+
...extra,
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Merge Host content hits with local title/session-ID matches.
|
|
201
|
+
* Host hits are content matches and are always labelled as such; metadata
|
|
202
|
+
* matches never pretend to be full-text hits.
|
|
203
|
+
*/
|
|
204
|
+
function mergeSearchResults(input = {}) {
|
|
205
|
+
const catalog = input.catalog || normalizeCatalog(input)
|
|
206
|
+
const query = String(input.query || '').trim()
|
|
207
|
+
const workspaceId = input.workspaceId || ''
|
|
208
|
+
const includeArchived = input.includeArchived === true
|
|
209
|
+
const hostItems = Array.isArray(input.hostItems) ? input.hostItems : []
|
|
210
|
+
const order = []
|
|
211
|
+
const merged = new Map()
|
|
212
|
+
const stats = { contentHits: 0, metadataHits: 0, filteredArchived: 0, filteredWorkspace: 0, unresolved: 0, hostItems: hostItems.length }
|
|
213
|
+
|
|
214
|
+
for (const hit of hostItems) {
|
|
215
|
+
if (!hit || typeof hit !== 'object' || typeof hit.sessionId !== 'string' || !hit.sessionId) continue
|
|
216
|
+
const sessionId = hit.sessionId
|
|
217
|
+
const known = catalog.byId.get(sessionId)
|
|
218
|
+
const isArchived = known ? known.archived : catalog.archivedIds.has(sessionId)
|
|
219
|
+
if (!includeArchived && isArchived) { stats.filteredArchived++; continue }
|
|
220
|
+
if (workspaceId && (!known || !entryMatchesFilters(known, { workspaceId, includeArchived }))) {
|
|
221
|
+
stats.filteredWorkspace++
|
|
222
|
+
continue
|
|
223
|
+
}
|
|
224
|
+
if (merged.has(sessionId)) continue
|
|
225
|
+
const snippet = clipCodePoints(typeof hit.snippet === 'string' ? hit.snippet : '')
|
|
226
|
+
const entry = known || {
|
|
227
|
+
sessionId,
|
|
228
|
+
title: text('未命名会话', 'Untitled conversation') + ' · ' + sessionId.slice(-8),
|
|
229
|
+
workspaceId: '',
|
|
230
|
+
workspaceName: '',
|
|
231
|
+
workspacePath: '',
|
|
232
|
+
archived: catalog.archivedIds.has(sessionId),
|
|
233
|
+
pinned: catalog.pinnedIds.has(sessionId),
|
|
234
|
+
unresolved: true,
|
|
235
|
+
}
|
|
236
|
+
if (!known) stats.unresolved++
|
|
237
|
+
const kinds = metadataMatchKinds(entry, query)
|
|
238
|
+
merged.set(sessionId, makeResult(entry, ['content', ...kinds], snippet, { unresolved: !known }))
|
|
239
|
+
order.push(sessionId)
|
|
240
|
+
stats.contentHits++
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
for (const entry of catalog.sessions) {
|
|
244
|
+
if (!isVisibleCatalogSession(entry)) continue
|
|
245
|
+
const kinds = metadataMatchKinds(entry, query)
|
|
246
|
+
if (!kinds.length) continue
|
|
247
|
+
if (!entryMatchesFilters(entry, { workspaceId, includeArchived })) continue
|
|
248
|
+
if (merged.has(entry.sessionId)) {
|
|
249
|
+
const existing = merged.get(entry.sessionId)
|
|
250
|
+
existing.matchKinds = [...new Set([...existing.matchKinds, ...kinds])]
|
|
251
|
+
continue
|
|
252
|
+
}
|
|
253
|
+
merged.set(entry.sessionId, makeResult(entry, kinds, ''))
|
|
254
|
+
order.push(entry.sessionId)
|
|
255
|
+
stats.metadataHits++
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const items = order.map(sessionId => merged.get(sessionId))
|
|
259
|
+
return {
|
|
260
|
+
items,
|
|
261
|
+
stats,
|
|
262
|
+
hasMore: input.hasMore === true,
|
|
263
|
+
contentEmpty: stats.contentHits === 0,
|
|
264
|
+
metadataOnly: stats.contentHits === 0 && stats.metadataHits > 0,
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Local title/session-ID matches shown only when the Host cannot search content. */
|
|
269
|
+
function localMetadataMatches(catalog, query, filters = {}) {
|
|
270
|
+
const items = []
|
|
271
|
+
for (const entry of catalog.sessions) {
|
|
272
|
+
if (!isVisibleCatalogSession(entry)) continue
|
|
273
|
+
const kinds = metadataMatchKinds(entry, String(query || '').trim())
|
|
274
|
+
if (!kinds.length) continue
|
|
275
|
+
if (!entryMatchesFilters(entry, filters)) continue
|
|
276
|
+
items.push(makeResult(entry, kinds, '', { localOnly: true }))
|
|
277
|
+
}
|
|
278
|
+
return items
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function errorCode(error) {
|
|
282
|
+
const code = error && (error.code || error.rpcCode || error.errorCode)
|
|
283
|
+
return code == null ? '' : String(code)
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function errorStatus(error) {
|
|
287
|
+
const status = Number(error && (error.status || error.httpStatus))
|
|
288
|
+
return Number.isFinite(status) ? status : 0
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function errorMessage(error) {
|
|
292
|
+
if (!error) return ''
|
|
293
|
+
if (typeof error === 'string') return error
|
|
294
|
+
return String(error.message || error.error || '')
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Classify a Host search failure. "No permission", "no results", "failed"
|
|
299
|
+
* and "this Host version does not support search" stay distinct.
|
|
300
|
+
*/
|
|
301
|
+
function classifySearchError(error) {
|
|
302
|
+
const code = errorCode(error).toLowerCase()
|
|
303
|
+
const status = errorStatus(error)
|
|
304
|
+
const message = errorMessage(error)
|
|
305
|
+
const lower = message.toLowerCase()
|
|
306
|
+
if (code === 'session/search-disabled' || (code === 'gateway/internal' && /session search is disabled:/i.test(message))) {
|
|
307
|
+
return {
|
|
308
|
+
status: STATUS.UNSUPPORTED,
|
|
309
|
+
kind: 'disabled',
|
|
310
|
+
code: 'session/search-disabled',
|
|
311
|
+
message: text('主机未启用全文会话搜索。可按本机已加载的标题或会话 ID 筛选。', 'Full-text search is disabled on the Host. Loaded titles and session IDs can still be filtered.'),
|
|
312
|
+
detail: '',
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
const unsupportedCode = [
|
|
316
|
+
'method-unavailable', 'not-found', 'unsupported-method', 'unsupported_endpoint',
|
|
317
|
+
'unsupported-method', 'no-generated-rpc-adapter', 'upstream-incompatible', 'gateway/not-found',
|
|
318
|
+
].includes(code)
|
|
319
|
+
const unsupported = unsupportedCode || [404, 405, 501].includes(status)
|
|
320
|
+
|| /does not mount|not available on this host|unsupported|no generated rpc adapter|method-unavailable/i.test(message)
|
|
321
|
+
if (unsupported) {
|
|
322
|
+
return {
|
|
323
|
+
status: STATUS.UNSUPPORTED,
|
|
324
|
+
kind: 'unsupported',
|
|
325
|
+
code: code || `http-${status || 'unknown'}`,
|
|
326
|
+
message: text('当前主机版本不支持全文会话搜索(session.search)。', 'This Host version does not support full-text session search (session.search).'),
|
|
327
|
+
detail: message,
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
if (code === 'auth' || code === 'unauthorized' || code === 'permission-denied' || status === 401 || status === 403) {
|
|
331
|
+
return {
|
|
332
|
+
status: STATUS.DENIED,
|
|
333
|
+
kind: 'auth',
|
|
334
|
+
code: code || `http-${status || 'auth'}`,
|
|
335
|
+
message: text('无权限或登录已失效,搜索未执行。', 'Permission denied or the session expired; no search was performed.'),
|
|
336
|
+
detail: message,
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
if (error && (error.name === 'AbortError' || error.name === 'TimeoutError' || /timeout/i.test(code))) {
|
|
340
|
+
return {
|
|
341
|
+
status: STATUS.ERROR,
|
|
342
|
+
kind: 'timeout',
|
|
343
|
+
code: code || 'timeout',
|
|
344
|
+
message: text('搜索超时,请重试。不会自动重试。', 'The search timed out. Retry manually; it is not retried automatically.'),
|
|
345
|
+
detail: message,
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
return {
|
|
349
|
+
status: STATUS.ERROR,
|
|
350
|
+
kind: 'failed',
|
|
351
|
+
code: code || 'search-failed',
|
|
352
|
+
message: text('搜索失败:主机未能完成本次搜索。', 'The search failed: the Host could not complete it.'),
|
|
353
|
+
detail: message,
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function statusMessage(status, stats) {
|
|
358
|
+
if (status === STATUS.EMPTY) return text('没有匹配的会话。可尝试更换关键词、包含归档或切换工作区。', 'No matching conversations. Try another query, include archived conversations, or switch workspace.')
|
|
359
|
+
if (status === STATUS.LOADING) return text('正在主机搜索会话正文…', 'Searching conversation content on the Host…')
|
|
360
|
+
if (status === STATUS.DENIED) return text('无权限或登录已失效,搜索未执行。', 'Permission denied or signed out; no search was performed.')
|
|
361
|
+
if (status === STATUS.ERROR) return text('搜索失败。未使用本地列表筛选代替全文搜索。', 'Search failed. Local list filtering was not used as a substitute.')
|
|
362
|
+
if (status === STATUS.UNSUPPORTED) return text('当前主机版本不支持全文会话搜索。', 'This Host version does not support full-text session search.')
|
|
363
|
+
if (status === STATUS.RESULTS) {
|
|
364
|
+
if (stats && stats.contentHits > 0) {
|
|
365
|
+
return text(`正文命中 ${stats.contentHits} 个会话${stats.metadataHits ? `,另有 ${stats.metadataHits} 个标题/ID 匹配` : ''}。`, `${stats.contentHits} conversation content ${stats.contentHits === 1 ? 'hit' : 'hits'}${stats.metadataHits ? `, plus ${stats.metadataHits} title/ID ${stats.metadataHits === 1 ? 'match' : 'matches'}` : ''}.`)
|
|
366
|
+
}
|
|
367
|
+
return text('正文搜索没有命中;以下仅为本地标题/会话 ID 匹配,未搜索历史正文。', 'No content hits. The rows below are local title/session-ID matches only; history content was not searched.')
|
|
368
|
+
}
|
|
369
|
+
return ''
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function matchLabel(kinds) {
|
|
373
|
+
const labels = []
|
|
374
|
+
if (kinds.includes('content')) labels.push(text('正文命中', 'Content hit'))
|
|
375
|
+
if (kinds.includes('title')) labels.push(text('标题匹配', 'Title match'))
|
|
376
|
+
if (kinds.includes('sessionId')) labels.push(text('会话 ID 匹配', 'Session ID match'))
|
|
377
|
+
return labels
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** Escape text, wrapping case-insensitive query occurrences in <mark>. */
|
|
381
|
+
function highlight(textValue, query) {
|
|
382
|
+
const source = String(textValue == null ? '' : textValue)
|
|
383
|
+
const needle = String(query == null ? '' : query).trim()
|
|
384
|
+
if (!needle) return esc(source)
|
|
385
|
+
const lowerSource = source.toLowerCase()
|
|
386
|
+
const lowerNeedle = needle.toLowerCase()
|
|
387
|
+
let index = 0
|
|
388
|
+
let from = 0
|
|
389
|
+
let html = ''
|
|
390
|
+
while (index < source.length) {
|
|
391
|
+
const found = lowerSource.indexOf(lowerNeedle, index)
|
|
392
|
+
if (found < 0) break
|
|
393
|
+
html += esc(source.slice(from, found))
|
|
394
|
+
html += '<mark>' + esc(source.slice(found, found + needle.length)) + '</mark>'
|
|
395
|
+
index = found + needle.length
|
|
396
|
+
from = index
|
|
397
|
+
if (!lowerNeedle.length) break
|
|
398
|
+
}
|
|
399
|
+
html += esc(source.slice(from))
|
|
400
|
+
return html
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function workspaceOptionRows(workspaces) {
|
|
404
|
+
const rows = [{ id: '', label: text('全部工作区', 'All workspaces') }]
|
|
405
|
+
for (const workspace of workspaces) {
|
|
406
|
+
rows.push({ id: workspace.workspaceId, label: workspace.path && workspace.path !== workspace.name ? `${workspace.name} — ${workspace.path}` : workspace.name })
|
|
407
|
+
}
|
|
408
|
+
rows.push({ id: UNGROUPED, label: text('未分组', 'Ungrouped') })
|
|
409
|
+
return rows
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function resultHtml(item, query) {
|
|
413
|
+
const labels = matchLabel(item.matchKinds)
|
|
414
|
+
const workspace = item.workspace
|
|
415
|
+
? `<span class="dr-search-result-workspace" title="${esc(item.workspace.path)}">⌂ ${esc(item.workspace.name)}</span>`
|
|
416
|
+
: `<span class="dr-search-result-workspace dr-search-result-workspace-unknown">⌂ ${esc(text('工作区未知', 'Workspace unknown'))}</span>`
|
|
417
|
+
const snippet = item.snippet
|
|
418
|
+
? `<p class="dr-search-snippet">${highlight(item.snippet, query)}</p>`
|
|
419
|
+
: `<p class="dr-search-snippet dr-search-snippet-empty">${esc(text('标题/会话 ID 匹配,主机未返回正文片段。', 'Title/session-ID match; the Host returned no content snippet.'))}</p>`
|
|
420
|
+
const badges = labels.map(label => `<span class="dr-search-badge">${esc(label)}</span>`).join('')
|
|
421
|
+
return `<li class="dr-search-result" data-dr-search-result data-session-id="${esc(item.sessionId)}">
|
|
422
|
+
<button type="button" class="dr-search-result-main" data-dr-search-open="${esc(item.sessionId)}" data-dr-search-snippet="${esc(item.snippet || '')}">
|
|
423
|
+
<span class="dr-search-result-head"><span class="dr-search-result-title">${esc(item.title)}</span>${badges}</span>
|
|
424
|
+
${workspace}
|
|
425
|
+
${snippet}
|
|
426
|
+
<span class="dr-search-result-id">${esc(String(item.sessionId).slice(-12))}</span>
|
|
427
|
+
</button>
|
|
428
|
+
</li>`
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function statusHtml(state) {
|
|
432
|
+
const status = state.status || STATUS.IDLE
|
|
433
|
+
if (status === STATUS.IDLE) {
|
|
434
|
+
return `<div class="dr-search-status dr-search-status-idle" data-dr-search-status>${esc(text('输入关键词后由主机搜索标题、会话 ID 与历史正文。仅返回当前设备有权的会话。', 'Search titles, session IDs and history content on the Host. Only conversations this device may access are returned.'))}</div>`
|
|
435
|
+
}
|
|
436
|
+
let extra = ''
|
|
437
|
+
if (status === STATUS.RESULTS && state.metadataOnly) {
|
|
438
|
+
extra = `<div class="dr-search-notice dr-search-notice-metadata" data-dr-search-mode="metadata">${esc(text('正文搜索没有命中;以下仅为本地标题/会话 ID 匹配,未搜索历史正文。', 'No content hits. The rows below are local title/session-ID matches only; history content was not searched.'))}</div>`
|
|
439
|
+
}
|
|
440
|
+
if (status === STATUS.UNSUPPORTED) {
|
|
441
|
+
extra = state.localMatches && state.localMatches.length
|
|
442
|
+
? `<div class="dr-search-notice dr-search-notice-local" data-dr-search-mode="local">${esc(text('以下仅为本地标题/会话 ID 匹配,未搜索历史正文;不能视为全文搜索结果。', 'The rows below are local title/session-ID matches only, not full-text results; history content was not searched.'))}</div>`
|
|
443
|
+
: `<div class="dr-search-notice dr-search-notice-local" data-dr-search-mode="local">${esc(text('未执行正文搜索,本地列表也未冒充搜索结果。', 'Content search was not performed, and the local list was not presented as search results.'))}</div>`
|
|
444
|
+
}
|
|
445
|
+
if (status === STATUS.ERROR || status === STATUS.DENIED) {
|
|
446
|
+
const detail = state.error && state.error.detail ? ` <span class="dr-search-detail">${esc(clipCodePoints(state.error.detail, 200))}</span>` : ''
|
|
447
|
+
extra = `<div class="dr-search-error-text">${esc(state.error && state.error.message ? state.error.message : '')}${detail}</div>`
|
|
448
|
+
+ `<button type="button" class="dr-search-retry" data-dr-search-retry>${esc(text('重试', 'Retry'))}</button>`
|
|
449
|
+
}
|
|
450
|
+
const message = status === STATUS.RESULTS || status === STATUS.UNSUPPORTED
|
|
451
|
+
? statusMessage(status, state.stats)
|
|
452
|
+
: (state.error && state.error.message) || statusMessage(status)
|
|
453
|
+
return `<div class="dr-search-status dr-search-status-${esc(status)}" data-dr-search-status data-status="${esc(status)}" role="status" aria-live="polite">${esc(message)}${extra}</div>`
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function renderWorkspaceOptions(value) {
|
|
457
|
+
const workspaces = Array.isArray(value.workspaces) ? value.workspaces : []
|
|
458
|
+
return workspaceOptionRows(workspaces).map(row =>
|
|
459
|
+
`<option value="${esc(row.id)}"${String(row.id) === String(value.workspaceId || '') ? ' selected' : ''}>${esc(row.label)}</option>`).join('')
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function searchButtonText(status) {
|
|
463
|
+
return status === STATUS.LOADING ? text('搜索中…', 'Searching…') : text('搜索', 'Search')
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function renderSearchResults(value, status) {
|
|
467
|
+
const listItems = status === STATUS.UNSUPPORTED
|
|
468
|
+
? (value.localMatches || [])
|
|
469
|
+
: (value.items || [])
|
|
470
|
+
const listTitle = status === STATUS.UNSUPPORTED && listItems.length
|
|
471
|
+
? `<div class="dr-search-list-title">${esc(text('本地标题/会话 ID 匹配', 'Local title/session-ID matches'))}</div>`
|
|
472
|
+
: ''
|
|
473
|
+
const results = listItems.length
|
|
474
|
+
? `${listTitle}<ul class="dr-search-results" data-dr-search-results>${listItems.map(item => resultHtml(item, value.query || '')).join('')}</ul>`
|
|
475
|
+
: ''
|
|
476
|
+
const stats = value.stats || {}
|
|
477
|
+
let footer = ''
|
|
478
|
+
if (status === STATUS.RESULTS || (status === STATUS.UNSUPPORTED && listItems.length)) {
|
|
479
|
+
const parts = []
|
|
480
|
+
if (status === STATUS.RESULTS && stats.contentHits != null) parts.push(text(`主机正文命中 ${stats.contentHits} 条`, `${stats.contentHits} Host content ${stats.contentHits === 1 ? 'hit' : 'hits'}`))
|
|
481
|
+
if (status === STATUS.UNSUPPORTED) parts.push(text('主机未执行正文搜索', 'Host content search was not performed'))
|
|
482
|
+
if (stats.metadataHits) parts.push(text(`${stats.metadataHits} 条标题/ID 匹配`, `${stats.metadataHits} title/ID ${stats.metadataHits === 1 ? 'match' : 'matches'}`))
|
|
483
|
+
if (stats.filteredArchived) parts.push(text(`隐藏 ${stats.filteredArchived} 条归档会话`, `${stats.filteredArchived} archived hidden`))
|
|
484
|
+
if (stats.filteredWorkspace) parts.push(text(`工作区外 ${stats.filteredWorkspace} 条`, `${stats.filteredWorkspace} outside workspace`))
|
|
485
|
+
if (value.hasMore) parts.push(text(`主机仅返回前 ${HOST_RESULT_LIMIT} 条`, `Host returned the first ${HOST_RESULT_LIMIT} only`))
|
|
486
|
+
if (parts.length) footer = `<div class="dr-search-footer" data-dr-search-footer>${esc(parts.join(' · '))}</div>`
|
|
487
|
+
}
|
|
488
|
+
return `${statusHtml(value)}${results}${footer}`
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/** Pure markup for the whole search panel; safe to render with innerHTML. */
|
|
492
|
+
function renderSearchHtml(state = {}) {
|
|
493
|
+
const value = state || {}
|
|
494
|
+
const status = value.status || STATUS.IDLE
|
|
495
|
+
const archived = value.includeArchived === true
|
|
496
|
+
return `<section class="dr-search" data-dr-search data-status="${esc(status)}">
|
|
497
|
+
<form class="dr-search-form" data-dr-search-form role="search" autocomplete="off">
|
|
498
|
+
<label class="dr-search-field dr-search-query-field">
|
|
499
|
+
<span class="dr-search-label">${esc(text('搜索会话', 'Search conversations'))}</span>
|
|
500
|
+
<input class="dr-search-input" data-dr-search-input type="search" name="dr-search-query" maxlength="${MAX_QUERY_CHARS}" value="${esc(value.query || '')}" placeholder="${esc(text('标题、会话 ID 或历史正文', 'Title, session ID or history content'))}">
|
|
501
|
+
</label>
|
|
502
|
+
<div class="dr-search-field dr-search-workspace-field">
|
|
503
|
+
<label for="session-search-workspace" class="dr-search-label">${esc(text('工作区', 'Workspace'))}</label>
|
|
504
|
+
<select id="session-search-workspace" class="dr-search-workspace" data-dr-search-workspace>${renderWorkspaceOptions(value)}</select>
|
|
505
|
+
</div>
|
|
506
|
+
<label class="dr-search-check"><input type="checkbox" data-dr-search-archived${archived ? ' checked' : ''}> ${esc(text('包含归档', 'Include archived'))}</label>
|
|
507
|
+
<button type="submit" class="dr-search-submit" data-dr-search-submit${status === STATUS.LOADING ? ' disabled' : ''}>${esc(searchButtonText(status))}</button>
|
|
508
|
+
</form>
|
|
509
|
+
<div class="dr-search-hint">${esc(text('正文搜索由主机执行并按其可见范围过滤;结果不会用本地列表筛选冒充。', 'Content search runs on the Host and is filtered by its visibility rules; local list filtering is never presented as content results.'))}</div>
|
|
510
|
+
<div class="dr-search-feedback" data-dr-search-feedback>${renderSearchResults(value, status)}</div>
|
|
511
|
+
</section>`
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function normalizeSnippet(value) { return String(value == null ? '' : value).replace(/\s+/g, ' ').trim() }
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* Locate a Host snippet in already rendered history. The Host search contract
|
|
518
|
+
* returns only {sessionId, snippet}, so the turn is found by snippet text in
|
|
519
|
+
* the rendered history; when an ancestor carries data-seq, that seq is returned.
|
|
520
|
+
*/
|
|
521
|
+
function locateSnippet(historyRoot, snippet, options = {}) {
|
|
522
|
+
const needle = normalizeSnippet(snippet)
|
|
523
|
+
if (!historyRoot || !needle) return { found: false, element: null, turnSeq: null, reason: 'empty' }
|
|
524
|
+
const elements = []
|
|
525
|
+
if (typeof historyRoot.matches === 'function' && historyRoot.matches(options.resultSelector || '[data-seq]')) elements.push(historyRoot)
|
|
526
|
+
if (typeof historyRoot.querySelectorAll === 'function') {
|
|
527
|
+
try { for (const element of historyRoot.querySelectorAll(options.candidateSelector || '*')) elements.push(element) } catch {}
|
|
528
|
+
}
|
|
529
|
+
const target = needle.toLowerCase()
|
|
530
|
+
let best = null
|
|
531
|
+
let matchedBy = ''
|
|
532
|
+
for (const element of elements) {
|
|
533
|
+
const tag = String(element.tagName || '').toUpperCase()
|
|
534
|
+
if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'TEXTAREA' || tag === 'INPUT') continue
|
|
535
|
+
const content = String(element.textContent == null ? '' : element.textContent)
|
|
536
|
+
let hit = content.includes(needle) || content.toLowerCase().includes(target)
|
|
537
|
+
let by = hit ? (content.includes(needle) ? 'exact' : 'normalized') : ''
|
|
538
|
+
if (!hit) {
|
|
539
|
+
const collapsed = normalizeSnippet(content)
|
|
540
|
+
hit = collapsed.toLowerCase().includes(target)
|
|
541
|
+
by = hit ? 'collapsed' : ''
|
|
542
|
+
}
|
|
543
|
+
if (!hit) continue
|
|
544
|
+
if (!best || content.length < best.contentLength) {
|
|
545
|
+
best = { element, contentLength: content.length }
|
|
546
|
+
matchedBy = by
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
if (!best) return { found: false, element: null, turnSeq: null, reason: 'not-rendered' }
|
|
550
|
+
const element = best.element
|
|
551
|
+
try { element.classList && element.classList.add('dr-search-located') } catch {}
|
|
552
|
+
try { if (typeof element.scrollIntoView === 'function') element.scrollIntoView({ behavior: 'smooth', block: 'center' }) } catch {}
|
|
553
|
+
let turnSeq = null
|
|
554
|
+
try {
|
|
555
|
+
const holder = typeof element.closest === 'function' ? element.closest('[data-seq]') : null
|
|
556
|
+
const raw = holder && holder.dataset ? holder.dataset.seq : null
|
|
557
|
+
if (raw != null && Number.isFinite(Number(raw))) turnSeq = Number(raw)
|
|
558
|
+
} catch {}
|
|
559
|
+
return { found: true, element, turnSeq, matchedBy }
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/**
|
|
563
|
+
* Poll for a snippet while history renders asynchronously. The first argument
|
|
564
|
+
* may be an element or a getter that re-reads the current history root.
|
|
565
|
+
*/
|
|
566
|
+
function waitForSnippet(historyRoot, snippet, options = {}) {
|
|
567
|
+
const getRoot = typeof historyRoot === 'function' ? historyRoot : () => historyRoot
|
|
568
|
+
const timeoutMs = Number.isFinite(options.timeoutMs) ? Math.max(0, options.timeoutMs) : 4000
|
|
569
|
+
const intervalMs = Number.isFinite(options.intervalMs) ? Math.max(20, options.intervalMs) : 120
|
|
570
|
+
const attempt = () => {
|
|
571
|
+
const rootValue = getRoot()
|
|
572
|
+
if (!rootValue) return { found: false, element: null, turnSeq: null, reason: 'no-root' }
|
|
573
|
+
return locateSnippet(rootValue, snippet, options)
|
|
574
|
+
}
|
|
575
|
+
const immediate = attempt()
|
|
576
|
+
if (immediate.found || timeoutMs === 0) return Promise.resolve(immediate)
|
|
577
|
+
return new Promise(resolve => {
|
|
578
|
+
const startedAt = Date.now()
|
|
579
|
+
const tick = () => {
|
|
580
|
+
const result = attempt()
|
|
581
|
+
if (result.found) { resolve(result); return }
|
|
582
|
+
if (Date.now() - startedAt >= timeoutMs) { resolve({ ...result, reason: result.reason || 'timeout' }); return }
|
|
583
|
+
if (typeof root.setTimeout === 'function') root.setTimeout(tick, intervalMs)
|
|
584
|
+
else setTimeout(tick, intervalMs)
|
|
585
|
+
}
|
|
586
|
+
if (typeof root.setTimeout === 'function') root.setTimeout(tick, intervalMs)
|
|
587
|
+
else setTimeout(tick, intervalMs)
|
|
588
|
+
})
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
function adapterValue(adapter, method, fallback) {
|
|
592
|
+
if (!adapter || typeof adapter[method] !== 'function') return fallback
|
|
593
|
+
try { const value = adapter[method](); return value == null ? fallback : value } catch { return fallback }
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
function buildCatalog(adapter) {
|
|
597
|
+
return normalizeCatalog({
|
|
598
|
+
sessions: adapterValue(adapter, 'sessions', []),
|
|
599
|
+
workspaces: adapterValue(adapter, 'workspaces', []),
|
|
600
|
+
archivedSessionIds: adapterValue(adapter, 'archivedSessionIds', []),
|
|
601
|
+
pinnedSessionIds: adapterValue(adapter, 'pinnedSessionIds', []),
|
|
602
|
+
titleOf: typeof adapter.titleOf === 'function' ? adapter.titleOf : undefined,
|
|
603
|
+
})
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
function createController(adapter) {
|
|
607
|
+
if (!adapter || typeof adapter.rpc !== 'function') throw new TypeError('DshSessionSearch.init requires an adapter.rpc(method, payload, options) function')
|
|
608
|
+
let generation = 0
|
|
609
|
+
let controllerRef = null
|
|
610
|
+
let internalAbort = null
|
|
611
|
+
let last = { query: '', workspaceId: '', includeArchived: false }
|
|
612
|
+
let state = {
|
|
613
|
+
status: STATUS.IDLE,
|
|
614
|
+
query: '',
|
|
615
|
+
workspaceId: '',
|
|
616
|
+
includeArchived: false,
|
|
617
|
+
items: [],
|
|
618
|
+
localMatches: [],
|
|
619
|
+
workspaces: [],
|
|
620
|
+
stats: {},
|
|
621
|
+
hasMore: false,
|
|
622
|
+
metadataOnly: false,
|
|
623
|
+
error: null,
|
|
624
|
+
cancelled: false,
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
function snapshot() {
|
|
628
|
+
return {
|
|
629
|
+
...state,
|
|
630
|
+
items: state.items.slice(),
|
|
631
|
+
localMatches: state.localMatches.slice(),
|
|
632
|
+
workspaces: state.workspaces.slice(),
|
|
633
|
+
stats: { ...state.stats },
|
|
634
|
+
error: state.error ? { ...state.error } : null,
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
function publish() {
|
|
639
|
+
const value = snapshot()
|
|
640
|
+
try { if (typeof adapter.onState === 'function') adapter.onState(value) } catch {}
|
|
641
|
+
return value
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function resolveHistoryRoot() {
|
|
645
|
+
if (typeof adapter.historyRoot === 'function') {
|
|
646
|
+
try { const value = adapter.historyRoot(); if (value) return value } catch {}
|
|
647
|
+
}
|
|
648
|
+
const doc = adapter.document || root.document
|
|
649
|
+
if (doc && typeof doc.getElementById === 'function') return doc.getElementById(adapter.historyElementId || 'history')
|
|
650
|
+
return null
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
function localState(query, catalog, filters) {
|
|
654
|
+
return { matches: localMetadataMatches(catalog, query, filters) }
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
async function search(options = {}) {
|
|
658
|
+
const normalized = normalizeQuery(options.query == null ? state.query : options.query)
|
|
659
|
+
const workspaceId = options.workspaceId == null ? state.workspaceId : String(options.workspaceId)
|
|
660
|
+
const includeArchived = options.includeArchived == null ? state.includeArchived : options.includeArchived === true
|
|
661
|
+
last = { query: normalized.query || String(options.query == null ? state.query : options.query), workspaceId, includeArchived }
|
|
662
|
+
if (!normalized.ok) {
|
|
663
|
+
state = { ...state, status: STATUS.IDLE, query: last.query, workspaceId, includeArchived, items: [], localMatches: [], stats: {}, metadataOnly: false, error: null }
|
|
664
|
+
publish()
|
|
665
|
+
return { ...snapshot(), validationError: normalized.error, validationMessage: normalized.message }
|
|
666
|
+
}
|
|
667
|
+
if (options.signal && options.signal.aborted) return snapshot()
|
|
668
|
+
const catalog = buildCatalog(adapter)
|
|
669
|
+
const filters = { workspaceId, includeArchived }
|
|
670
|
+
state = {
|
|
671
|
+
...state,
|
|
672
|
+
status: STATUS.LOADING,
|
|
673
|
+
query: normalized.query,
|
|
674
|
+
workspaceId,
|
|
675
|
+
includeArchived,
|
|
676
|
+
workspaces: catalog.workspaces.map(workspace => ({ workspaceId: workspace.workspaceId, name: workspace.name, path: workspace.path })),
|
|
677
|
+
items: [],
|
|
678
|
+
localMatches: [],
|
|
679
|
+
stats: {},
|
|
680
|
+
hasMore: false,
|
|
681
|
+
metadataOnly: false,
|
|
682
|
+
error: null,
|
|
683
|
+
cancelled: false,
|
|
684
|
+
validationMessage: '',
|
|
685
|
+
}
|
|
686
|
+
publish()
|
|
687
|
+
|
|
688
|
+
const markUnsupported = classified => {
|
|
689
|
+
const local = localState(normalized.query, catalog, filters)
|
|
690
|
+
state = {
|
|
691
|
+
...state,
|
|
692
|
+
status: STATUS.UNSUPPORTED,
|
|
693
|
+
items: [],
|
|
694
|
+
localMatches: local.matches,
|
|
695
|
+
stats: { contentHits: 0, metadataHits: local.matches.length, filteredArchived: 0, filteredWorkspace: 0 },
|
|
696
|
+
hasMore: false,
|
|
697
|
+
metadataOnly: local.matches.length > 0,
|
|
698
|
+
error: classified,
|
|
699
|
+
}
|
|
700
|
+
return publish()
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
if (typeof adapter.searchSupported === 'function' && adapter.searchSupported() === false) {
|
|
704
|
+
return markUnsupported({
|
|
705
|
+
status: STATUS.UNSUPPORTED,
|
|
706
|
+
kind: 'unsupported',
|
|
707
|
+
code: 'capability-disabled',
|
|
708
|
+
message: text('当前主机版本不支持全文会话搜索(session.search)。', 'This Host version does not support full-text session search (session.search).'),
|
|
709
|
+
detail: '',
|
|
710
|
+
})
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
const requestId = ++generation
|
|
714
|
+
try {
|
|
715
|
+
if (internalAbort) { try { internalAbort.abort() } catch {} }
|
|
716
|
+
internalAbort = typeof AbortController === 'function' ? new AbortController() : null
|
|
717
|
+
const signal = options.signal || (internalAbort ? internalAbort.signal : undefined)
|
|
718
|
+
const value = await adapter.rpc('session.search', { query: normalized.query }, { signal, timeoutMs: options.timeoutMs })
|
|
719
|
+
if (requestId !== generation) return snapshot()
|
|
720
|
+
const hostItems = value && Array.isArray(value.items) ? value.items : null
|
|
721
|
+
if (!hostItems || hostItems.some(item => !item || typeof item.sessionId !== 'string')) {
|
|
722
|
+
const classified = { status: STATUS.ERROR, kind: 'invalid-response', code: 'invalid-response', message: text('搜索失败:主机返回了无法识别的结果。', 'Search failed: the Host returned an unrecognised result.'), detail: '' }
|
|
723
|
+
state = { ...state, status: STATUS.ERROR, items: [], localMatches: [], stats: {}, error: classified }
|
|
724
|
+
return publish()
|
|
725
|
+
}
|
|
726
|
+
const merged = mergeSearchResults({ catalog, query: normalized.query, hostItems, ...filters, hasMore: value.hasMore === true })
|
|
727
|
+
state = {
|
|
728
|
+
...state,
|
|
729
|
+
status: merged.items.length ? STATUS.RESULTS : STATUS.EMPTY,
|
|
730
|
+
items: merged.items,
|
|
731
|
+
localMatches: [],
|
|
732
|
+
stats: merged.stats,
|
|
733
|
+
hasMore: merged.hasMore,
|
|
734
|
+
metadataOnly: merged.metadataOnly,
|
|
735
|
+
error: null,
|
|
736
|
+
}
|
|
737
|
+
return publish()
|
|
738
|
+
} catch (error) {
|
|
739
|
+
if (requestId !== generation) return snapshot()
|
|
740
|
+
const aborted = !!(options.signal && options.signal.aborted)
|
|
741
|
+
|| (error && (error.name === 'AbortError' || /aborted/i.test(String(error.message || ''))))
|
|
742
|
+
if (aborted) {
|
|
743
|
+
state = { ...state, status: STATUS.IDLE, items: [], localMatches: [], stats: {}, metadataOnly: false, error: null, cancelled: true }
|
|
744
|
+
return publish()
|
|
745
|
+
}
|
|
746
|
+
const classified = classifySearchError(error)
|
|
747
|
+
if (classified.status === STATUS.UNSUPPORTED) return markUnsupported(classified)
|
|
748
|
+
state = { ...state, status: classified.status, items: [], localMatches: [], stats: {}, metadataOnly: false, error: classified }
|
|
749
|
+
return publish()
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
function cancelSearch() {
|
|
754
|
+
generation++
|
|
755
|
+
if (internalAbort) { try { internalAbort.abort() } catch {} internalAbort = null }
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
function retry() {
|
|
759
|
+
const query = last.query || state.query
|
|
760
|
+
return search({ query, workspaceId: last.workspaceId, includeArchived: last.includeArchived })
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
async function openResult(itemOrId) {
|
|
764
|
+
const sessionId = typeof itemOrId === 'string' ? itemOrId : itemOrId && itemOrId.sessionId
|
|
765
|
+
if (!sessionId) return { sessionId: '', opened: false, located: false, turnSeq: null, reason: 'missing-session' }
|
|
766
|
+
const fromList = state.items.find(item => item.sessionId === sessionId)
|
|
767
|
+
|| state.localMatches.find(item => item.sessionId === sessionId)
|
|
768
|
+
const item = typeof itemOrId === 'object' && itemOrId ? itemOrId : (fromList || { sessionId, snippet: '' })
|
|
769
|
+
const result = { sessionId, opened: false, located: false, turnSeq: null, reason: '' }
|
|
770
|
+
try {
|
|
771
|
+
if (typeof adapter.openSession !== 'function') throw new Error('adapter.openSession is unavailable')
|
|
772
|
+
await adapter.openSession(sessionId, { snippet: item.snippet || '', query: state.query })
|
|
773
|
+
result.opened = true
|
|
774
|
+
} catch (error) {
|
|
775
|
+
result.reason = 'open-failed'
|
|
776
|
+
result.error = classifySearchError(error)
|
|
777
|
+
try { if (typeof adapter.onOpen === 'function') adapter.onOpen(result) } catch {}
|
|
778
|
+
return result
|
|
779
|
+
}
|
|
780
|
+
if (!item.snippet) {
|
|
781
|
+
result.reason = 'no-snippet'
|
|
782
|
+
} else if (typeof adapter.locateSnippet === 'function') {
|
|
783
|
+
try {
|
|
784
|
+
const located = await adapter.locateSnippet({ sessionId, snippet: item.snippet, query: state.query })
|
|
785
|
+
result.located = !!(located && located.found)
|
|
786
|
+
result.turnSeq = located && Number.isFinite(Number(located.turnSeq)) ? Number(located.turnSeq) : null
|
|
787
|
+
if (!result.located) result.reason = (located && located.reason) || 'not-rendered'
|
|
788
|
+
} catch { result.reason = 'locate-failed' }
|
|
789
|
+
} else {
|
|
790
|
+
const located = await waitForSnippet(resolveHistoryRoot, item.snippet, {
|
|
791
|
+
timeoutMs: Number.isFinite(adapter.locateTimeoutMs) ? adapter.locateTimeoutMs : 4000,
|
|
792
|
+
})
|
|
793
|
+
result.located = !!located.found
|
|
794
|
+
result.turnSeq = located.turnSeq == null ? null : located.turnSeq
|
|
795
|
+
if (!located.found) result.reason = located.reason || 'not-rendered'
|
|
796
|
+
}
|
|
797
|
+
if (result.opened && !result.located) {
|
|
798
|
+
try { if (typeof adapter.notice === 'function') adapter.notice(text('会话已打开,但历史中暂未渲染命中片段,未能自动定位回合。', 'Conversation opened, but the matched snippet is not rendered in history yet; the turn could not be located automatically.')) } catch {}
|
|
799
|
+
}
|
|
800
|
+
try { if (typeof adapter.onOpen === 'function') adapter.onOpen(result) } catch {}
|
|
801
|
+
return result
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
function setWorkspace(workspaceId) { state = { ...state, workspaceId: String(workspaceId || '') }; return publish() }
|
|
805
|
+
function setIncludeArchived(value) { state = { ...state, includeArchived: value === true }; return publish() }
|
|
806
|
+
function reset() {
|
|
807
|
+
cancelSearch()
|
|
808
|
+
state = { ...state, status: STATUS.IDLE, items: [], localMatches: [], stats: {}, error: null, metadataOnly: false, cancelled: false }
|
|
809
|
+
return publish()
|
|
810
|
+
}
|
|
811
|
+
function syncCatalog() {
|
|
812
|
+
const catalog = buildCatalog(adapter)
|
|
813
|
+
state = { ...state, workspaces: catalog.workspaces.map(workspace => ({ workspaceId: workspace.workspaceId, name: workspace.name, path: workspace.path })) }
|
|
814
|
+
return publish()
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
controllerRef = {
|
|
818
|
+
search, cancelSearch, retry, openResult, snapshot, setWorkspace, setIncludeArchived, reset, syncCatalog,
|
|
819
|
+
get statuses() { return STATUS }, adapter,
|
|
820
|
+
}
|
|
821
|
+
return controllerRef
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
let instance = null
|
|
825
|
+
function init(adapter) {
|
|
826
|
+
instance = createController(adapter)
|
|
827
|
+
return instance
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* Mount the panel into a container. The caller owns placement; the module
|
|
832
|
+
* builds its own form/status/results markup and never requires HTML changes.
|
|
833
|
+
*/
|
|
834
|
+
function mount(container, controller, options = {}) {
|
|
835
|
+
const doc = options.document || root.document
|
|
836
|
+
if (!container || !doc || typeof doc.createElement !== 'function') return null
|
|
837
|
+
const element = doc.createElement('div')
|
|
838
|
+
element.className = 'dr-search-host'
|
|
839
|
+
container.appendChild(element)
|
|
840
|
+
let destroyed = false
|
|
841
|
+
let workspaceMarkup, english
|
|
842
|
+
const paint = () => {
|
|
843
|
+
if (destroyed) return
|
|
844
|
+
const state = controller.snapshot()
|
|
845
|
+
const workspace = element.querySelector?.('[data-dr-search-workspace]')
|
|
846
|
+
if (!options.enhanceWorkspaceSelect || !workspace || english !== isEnglish()) {
|
|
847
|
+
english = isEnglish()
|
|
848
|
+
element.innerHTML = renderSearchHtml(state)
|
|
849
|
+
workspaceMarkup = renderWorkspaceOptions(state)
|
|
850
|
+
const select = element.querySelector?.('[data-dr-search-workspace]')
|
|
851
|
+
if (select) options.enhanceWorkspaceSelect?.(select)
|
|
852
|
+
return
|
|
853
|
+
}
|
|
854
|
+
// Keep the form attached while results arrive, including when a workspace
|
|
855
|
+
// picker is open or the user has begun typing the next query.
|
|
856
|
+
const newWorkspaceMarkup = renderWorkspaceOptions(state)
|
|
857
|
+
if (workspaceMarkup !== newWorkspaceMarkup) {
|
|
858
|
+
workspaceMarkup = newWorkspaceMarkup
|
|
859
|
+
workspace.innerHTML = newWorkspaceMarkup
|
|
860
|
+
}
|
|
861
|
+
workspace.value = state.workspaceId || ''
|
|
862
|
+
const submit = element.querySelector('[data-dr-search-submit]')
|
|
863
|
+
submit.disabled = state.status === STATUS.LOADING
|
|
864
|
+
submit.textContent = searchButtonText(state.status)
|
|
865
|
+
element.querySelector('[data-dr-search]').dataset.status = state.status
|
|
866
|
+
element.querySelector('[data-dr-search-feedback]').innerHTML = renderSearchResults(state, state.status)
|
|
867
|
+
}
|
|
868
|
+
const unbind = bindPanel(element, controller, { ...options, render: paint })
|
|
869
|
+
paint()
|
|
870
|
+
return {
|
|
871
|
+
element,
|
|
872
|
+
refresh: paint,
|
|
873
|
+
destroy() { destroyed = true; unbind(); if (element.parentNode) element.parentNode.removeChild(element) },
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
function readForm(form) {
|
|
878
|
+
const queryInput = form.querySelector && form.querySelector('[data-dr-search-input]')
|
|
879
|
+
const workspaceSelect = form.querySelector && form.querySelector('[data-dr-search-workspace]')
|
|
880
|
+
const archivedInput = form.querySelector && form.querySelector('[data-dr-search-archived]')
|
|
881
|
+
return {
|
|
882
|
+
query: queryInput && 'value' in queryInput ? queryInput.value : '',
|
|
883
|
+
workspaceId: workspaceSelect && 'value' in workspaceSelect ? workspaceSelect.value : '',
|
|
884
|
+
includeArchived: !!(archivedInput && archivedInput.checked),
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
/**
|
|
889
|
+
* Delegated bindings for a panel/container. `render` is the caller's redraw
|
|
890
|
+
* hook; when absent the events still drive the controller.
|
|
891
|
+
*/
|
|
892
|
+
function bindPanel(panel, controller, options = {}) {
|
|
893
|
+
if (!panel || typeof panel.addEventListener !== 'function') return () => {}
|
|
894
|
+
const redraw = () => {
|
|
895
|
+
try { if (typeof options.render === 'function') options.render() } catch {}
|
|
896
|
+
try { if (typeof options.onState === 'function') options.onState(controller.snapshot()) } catch {}
|
|
897
|
+
}
|
|
898
|
+
const onSubmit = event => {
|
|
899
|
+
const form = event.target && event.target.closest ? event.target.closest('[data-dr-search-form]') : null
|
|
900
|
+
if (!form) return
|
|
901
|
+
if (typeof event.preventDefault === 'function') event.preventDefault()
|
|
902
|
+
const formValues = readForm(form)
|
|
903
|
+
void controller.search({ ...formValues, query: formValues.query }).then(redraw)
|
|
904
|
+
}
|
|
905
|
+
const onClick = event => {
|
|
906
|
+
const target = event.target && event.target.closest ? event.target : null
|
|
907
|
+
if (!target) return
|
|
908
|
+
const retry = target.closest('[data-dr-search-retry]')
|
|
909
|
+
if (retry) { void controller.retry().then(redraw); return }
|
|
910
|
+
const open = target.closest('[data-dr-search-open],[data-dr-search-result]')
|
|
911
|
+
if (!open) return
|
|
912
|
+
const sessionId = open.dataset ? open.dataset.drSearchOpen || open.dataset.sessionId : ''
|
|
913
|
+
const snippet = open.dataset ? open.dataset.drSearchSnippet || '' : ''
|
|
914
|
+
if (sessionId) void controller.openResult({ sessionId, snippet }).then(result => {
|
|
915
|
+
if (typeof options.onOpen === 'function') options.onOpen(result)
|
|
916
|
+
redraw()
|
|
917
|
+
})
|
|
918
|
+
}
|
|
919
|
+
const onChange = event => {
|
|
920
|
+
const target = event.target
|
|
921
|
+
if (!target || !target.closest) return
|
|
922
|
+
if (target.closest('[data-dr-search-workspace]') || target.closest('[data-dr-search-archived]')) {
|
|
923
|
+
const form = target.closest('[data-dr-search-form]')
|
|
924
|
+
if (form) {
|
|
925
|
+
const formValues = readForm(form)
|
|
926
|
+
controller.setWorkspace(formValues.workspaceId)
|
|
927
|
+
controller.setIncludeArchived(formValues.includeArchived)
|
|
928
|
+
if (controller.snapshot().query && controller.snapshot().status !== STATUS.IDLE) {
|
|
929
|
+
void controller.search(formValues).then(redraw)
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
panel.addEventListener('submit', onSubmit)
|
|
935
|
+
panel.addEventListener('click', onClick)
|
|
936
|
+
panel.addEventListener('change', onChange)
|
|
937
|
+
return () => {
|
|
938
|
+
panel.removeEventListener('submit', onSubmit)
|
|
939
|
+
panel.removeEventListener('click', onClick)
|
|
940
|
+
panel.removeEventListener('change', onChange)
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
const api = {
|
|
945
|
+
statuses: STATUS,
|
|
946
|
+
MAX_QUERY_CHARS,
|
|
947
|
+
MAX_SNIPPET_CODE_POINTS,
|
|
948
|
+
HOST_RESULT_LIMIT,
|
|
949
|
+
UNGROUPED,
|
|
950
|
+
esc,
|
|
951
|
+
text,
|
|
952
|
+
clipCodePoints,
|
|
953
|
+
normalizeQuery,
|
|
954
|
+
pathKey,
|
|
955
|
+
normalizeWorkspace,
|
|
956
|
+
sessionTitle,
|
|
957
|
+
workspaceForSession,
|
|
958
|
+
normalizeCatalog,
|
|
959
|
+
isVisibleCatalogSession,
|
|
960
|
+
mergeSearchResults,
|
|
961
|
+
localMetadataMatches,
|
|
962
|
+
classifySearchError,
|
|
963
|
+
statusMessage,
|
|
964
|
+
highlight,
|
|
965
|
+
renderSearchHtml,
|
|
966
|
+
locateSnippet,
|
|
967
|
+
waitForSnippet,
|
|
968
|
+
createController,
|
|
969
|
+
init,
|
|
970
|
+
mount,
|
|
971
|
+
bindPanel,
|
|
972
|
+
get instance() { return instance },
|
|
973
|
+
}
|
|
974
|
+
Object.defineProperty(api, 'controller', { get: () => instance })
|
|
975
|
+
root.DshSessionSearch = api
|
|
976
|
+
if (typeof module !== 'undefined' && module.exports) module.exports = api
|
|
977
|
+
})(typeof window !== 'undefined' ? window : globalThis)
|