@wwwfz/dsh-agent-bridge 0.0.0-stage → 0.8.3

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/web/panel.js ADDED
@@ -0,0 +1,1559 @@
1
+ import { describeProjectContext } from './project-context.js'
2
+
3
+ const byId = id => document.getElementById(id)
4
+ const nonce = document.querySelector('meta[name=bridge-nonce]').content
5
+ const dialog = byId('dialog')
6
+ const importButton = byId('import')
7
+ const recoverDraftButton = byId('recover-draft')
8
+ const exportButton = byId('export')
9
+ const exportDownload = byId('export-download')
10
+ const dialogClose = byId('dialog-close')
11
+ const dialogText = byId('dialog-text')
12
+ const sessionSelect = byId('session-select')
13
+ const historySearch = byId('history-search')
14
+ const historyResults = byId('history-results')
15
+ const historyImport = byId('history-import')
16
+ const refreshButton = byId('refresh')
17
+ const agentFilter = byId('agent-filter')
18
+ const agentPicker = byId('agent-picker')
19
+ const agentPopover = byId('agent-popover')
20
+ const agentOptions = byId('agent-options')
21
+ const themeOptions = [...document.querySelectorAll('[data-theme-choice]')]
22
+ const themeKey = 'dsh-agent-bridge.theme'
23
+ const projectSearch = byId('project-search')
24
+ const assetSearch = byId('asset-search')
25
+ const historyOption = byId('history')
26
+ const projectList = byId('project-list')
27
+ const projectManage = byId('project-manage')
28
+ const selectVisible = byId('project-select-visible')
29
+ const bulkArchive = byId('project-bulk-action')
30
+ const archiveAction = byId('project-archive-action')
31
+ const projectUndo = byId('project-undo')
32
+ const projectPin = byId('project-pin')
33
+ const draftWorkflow = byId('draft-workflow')
34
+ const projectMaterials = byId('project-materials')
35
+ const globalLibrary = byId('global-library')
36
+ const globalMaterials = byId('global-materials')
37
+ const queueList = byId('queue-list')
38
+ const recentList = byId('recent-conversations')
39
+ const recentStatus = byId('recent-status')
40
+ const browseHistory = byId('browse-history')
41
+ const projectFilters = [...document.querySelectorAll('[data-project-state]')]
42
+ const compactLayout = matchMedia('(max-width: 700px)')
43
+ const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)')
44
+ const parentOrigin = window.origin === 'null' ? '*' : window.origin
45
+ const agentNames = {
46
+ codex: 'Codex', claude: 'Claude Code', opencode: 'OpenCode', qoder: 'Qoder',
47
+ workbuddy: 'WorkBuddy', trae: 'TRAE', gemini: 'Gemini', antigravity: 'Antigravity',
48
+ copilot: 'Copilot', qwen: 'Qwen Code', dsh: 'DSH', workspacehub: '项目总账',
49
+ local: '手动目录', manual: '手动目录', export: '记忆导出', shared: '共享',
50
+ }
51
+ const agentInitials = { claude: 'CC', codex: 'CX', workbuddy: 'WB', trae: 'TR', antigravity: 'AG' }
52
+ const sourceStates = { ready: '可读取', partial: '部分可读', unavailable: '未找到', error: '读取失败' }
53
+ const materialGroups = [
54
+ ['progress', '上次做到哪', '交接记录、最新进度和待办。'],
55
+ ['guides', '项目约定', '开发规则、操作指引和偏好。'],
56
+ ['used', '会话中提及的 Skills', '在这个项目的近期对话中有记录。'],
57
+ ['notes', '其他项目笔记', '经验、决策和存档,可按需带入。'],
58
+ ['skills', '其他项目 Skills', '放在项目目录里,按任务选用。'],
59
+ ]
60
+ const globalGroups = [
61
+ ['guides', '通用指引'],
62
+ ['notes', '通用记忆'],
63
+ ['skills', '通用 Skills'],
64
+ ]
65
+ let catalog = []
66
+ let catalogLoaded = false
67
+ let agentIcons = {}
68
+ let availableAgents = ['']
69
+ let selectedAgent = ''
70
+ let projectQuery = ''
71
+ let activeAgentIndex = 0
72
+ let agentQuery = ''
73
+ let agentQueryAt = 0
74
+ let current
75
+ let detail
76
+ let context
77
+ let detailRevision = 0
78
+ let detailLoading = false
79
+ let projectState = 'all'
80
+ let archiveAvailable = false
81
+ let nativeSessionImport = false
82
+ let preferencesAvailable = false
83
+ let managingProjects = false
84
+ const selectedProjects = new Set()
85
+ const pinRequests = new Set()
86
+ const projectSelections = new Map()
87
+ const selectionSaves = new Map()
88
+ let archiveBusy = false
89
+ let undoArchive
90
+ let selected = new Set()
91
+ let includeHistory = false
92
+ let sourceRevision = null
93
+ let lastPinRevision = 0
94
+ let refreshing = false
95
+ let polling = false
96
+ let pollTimer
97
+ let ticket
98
+ let pending
99
+ let dialogMode
100
+ let dialogEpoch = 0
101
+ let dialogBusy = false
102
+ let nativeSessions = []
103
+ let recentRevision = 0
104
+ let recentKey = ''
105
+ let historyProject
106
+ let historySessions
107
+ let historyLimit = 30
108
+ let historyChosenId
109
+ let historyTicket
110
+ let importedSessionId
111
+ let draftRecovery
112
+ let historyPreview = 0
113
+ let downloadUrl
114
+ let requestNumber = 0
115
+
116
+ const clockFormat = new Intl.DateTimeFormat('zh-CN', { timeStyle: 'medium', hourCycle: 'h23' })
117
+ const historyDateFormat = new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium', timeStyle: 'short' })
118
+ const recentDateFormat = new Intl.DateTimeFormat('zh-CN', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' })
119
+ const shortClock = new Intl.DateTimeFormat('zh-CN', { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' })
120
+
121
+ const agentName = value => Object.hasOwn(agentNames, value) ? agentNames[value] : String(value ?? '')
122
+ const text = (tag, content, className) => {
123
+ const element = document.createElement(tag)
124
+ element.textContent = content
125
+ if (className) element.className = className
126
+ return element
127
+ }
128
+
129
+ function icon(name, className = '') {
130
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
131
+ svg.setAttribute('class', className ? `icon ${className}` : 'icon')
132
+ svg.setAttribute('aria-hidden', 'true')
133
+ const use = document.createElementNS(svg.namespaceURI, 'use')
134
+ use.setAttribute('href', `#icon-${name}`)
135
+ svg.append(use)
136
+ return svg
137
+ }
138
+
139
+ function agentMark(agent, label = agentName(agent)) {
140
+ const mark = text('span', '', 'agent-brand-mark')
141
+ mark.dataset.agent = agent
142
+ mark.setAttribute('aria-hidden', 'true')
143
+ const initial = () => {
144
+ mark.classList.remove('has-image')
145
+ mark.textContent = Object.hasOwn(agentInitials, agent) ? agentInitials[agent] : (Array.from(label)[0]?.toUpperCase() || '?')
146
+ }
147
+ const file = Object.hasOwn(agentIcons, agent) ? agentIcons[agent] : ''
148
+ if (!/^agent-icons\/[a-z][a-z0-9-]*\.(?:svg|png)$/.test(file)) {
149
+ initial()
150
+ return mark
151
+ }
152
+ const image = document.createElement('img')
153
+ image.alt = ''
154
+ image.decoding = 'async'
155
+ image.addEventListener('error', initial, { once: true })
156
+ image.src = `./${file}`
157
+ mark.classList.add('has-image')
158
+ mark.append(image)
159
+ return mark
160
+ }
161
+
162
+ function agentLabel(agent, className = '', label = agentName(agent)) {
163
+ const span = text('span', '', ['agent-label', className].filter(Boolean).join(' '))
164
+ span.append(agentMark(agent, label), text('span', label, 'agent-label-name'))
165
+ return span
166
+ }
167
+
168
+ function setTheme(value, remember = true) {
169
+ const theme = ['blue', 'white', 'black'].includes(value) ? value : 'blue'
170
+ document.documentElement.dataset.theme = theme
171
+ for (const button of themeOptions) {
172
+ button.setAttribute('aria-pressed', String(button.dataset.themeChoice === theme))
173
+ }
174
+ if (remember) {
175
+ try { localStorage.setItem(themeKey, theme) } catch { /* Theme is still applied to this panel. */ }
176
+ }
177
+ }
178
+
179
+ function renderAgentPicker(activeAgent = selectedAgent) {
180
+ const label = selectedAgent ? agentName(selectedAgent) : '全部 Agent'
181
+ byId('agent-trigger-mark').replaceChildren(selectedAgent ? agentMark(selectedAgent) : icon('filter'))
182
+ byId('agent-trigger-label').textContent = label
183
+ agentFilter.setAttribute('aria-label', `筛选 Agent,当前为${label}`)
184
+ agentOptions.replaceChildren(...availableAgents.map((agent, index) => {
185
+ const option = text('div', '', 'agent-option')
186
+ option.id = `agent-option-${index}`
187
+ option.dataset.agent = agent
188
+ option.setAttribute('role', 'option')
189
+ option.setAttribute('aria-selected', String(agent === selectedAgent))
190
+ option.append(agent ? agentMark(agent) : icon('layers', 'agent-option-mark'),
191
+ text('span', agent ? agentName(agent) : '全部 Agent', 'agent-option-label'), icon('check', 'agent-option-check'))
192
+ return option
193
+ }))
194
+ if (!agentPopover.hidden) {
195
+ positionAgentPicker()
196
+ activateAgentOption(availableAgents.indexOf(availableAgents.includes(activeAgent) ? activeAgent : selectedAgent))
197
+ }
198
+ }
199
+
200
+ function positionAgentPicker() {
201
+ if (agentPopover.hidden) return
202
+ const bounds = agentFilter.getBoundingClientRect()
203
+ const below = window.innerHeight - bounds.bottom
204
+ const above = bounds.top
205
+ agentPopover.dataset.placement = below < agentPopover.getBoundingClientRect().height + 6 && above > below ? 'above' : 'below'
206
+ }
207
+
208
+ function activateAgentOption(index, scroll = true) {
209
+ const previous = agentOptions.children[activeAgentIndex]
210
+ if (previous) delete previous.dataset.active
211
+ activeAgentIndex = Math.max(0, Math.min(index, availableAgents.length - 1))
212
+ const active = agentOptions.children[activeAgentIndex]
213
+ if (!active) return
214
+ active.dataset.active = 'true'
215
+ agentOptions.setAttribute('aria-activedescendant', active.id)
216
+ if (!scroll) return
217
+ const optionBounds = active.getBoundingClientRect()
218
+ const listBounds = agentOptions.getBoundingClientRect()
219
+ if (optionBounds.bottom > listBounds.bottom) agentOptions.scrollTop += optionBounds.bottom - listBounds.bottom
220
+ if (optionBounds.top < listBounds.top) agentOptions.scrollTop -= listBounds.top - optionBounds.top
221
+ }
222
+
223
+ function openAgentPicker() {
224
+ if (!agentPopover.hidden) return
225
+ agentPopover.hidden = false
226
+ agentFilter.setAttribute('aria-expanded', 'true')
227
+ agentQuery = ''
228
+ positionAgentPicker()
229
+ activateAgentOption(availableAgents.indexOf(selectedAgent))
230
+ agentOptions.focus({ preventScroll: true })
231
+ clearTimeout(pollTimer)
232
+ }
233
+
234
+ function closeAgentPicker(restoreFocus = false) {
235
+ if (agentPopover.hidden) return
236
+ agentPopover.hidden = true
237
+ agentOptions.removeAttribute('aria-activedescendant')
238
+ agentFilter.setAttribute('aria-expanded', 'false')
239
+ if (restoreFocus) agentFilter.focus({ preventScroll: true })
240
+ schedulePoll(0)
241
+ }
242
+
243
+ function chooseAgent(index) {
244
+ selectedAgent = availableAgents[index] ?? ''
245
+ closeAgentPicker(true)
246
+ renderAgentPicker()
247
+ projectList.scrollTop = 0
248
+ updateProjectView()
249
+ }
250
+
251
+ function navigateAgents(event) {
252
+ const { key } = event
253
+ if (key === 'Escape' || key === 'Tab') {
254
+ if (key === 'Escape') event.preventDefault()
255
+ closeAgentPicker(true)
256
+ return
257
+ }
258
+ if (key === 'Enter' || key === ' ') {
259
+ event.preventDefault()
260
+ chooseAgent(activeAgentIndex)
261
+ return
262
+ }
263
+ const destinations = { ArrowDown: activeAgentIndex + 1, ArrowUp: activeAgentIndex - 1,
264
+ Home: 0, End: availableAgents.length - 1 }
265
+ if (Object.hasOwn(destinations, key)) {
266
+ event.preventDefault()
267
+ activateAgentOption(destinations[key])
268
+ return
269
+ }
270
+ if (key.length !== 1 || event.ctrlKey || event.metaKey || event.altKey || event.isComposing) return
271
+ const now = Date.now()
272
+ agentQuery = (now - agentQueryAt < 650 ? agentQuery : '') + key.toLowerCase()
273
+ agentQueryAt = now
274
+ const match = availableAgents.findIndex(agent => agentName(agent).toLowerCase().startsWith(agentQuery))
275
+ if (match > 0) {
276
+ event.preventDefault()
277
+ activateAgentOption(match)
278
+ }
279
+ }
280
+
281
+ function shortPath(value) {
282
+ const separator = value.includes('\\') ? '\\' : '/'
283
+ const parts = value.split(/[\\/]+/).filter(Boolean)
284
+ return parts.length <= 3 ? value : `…${separator}${parts.slice(-2).join(separator)}`
285
+ }
286
+
287
+ function syncSearch(input) {
288
+ const clear = input.parentElement.querySelector('.clear-search')
289
+ const hint = input.parentElement.querySelector('.key-hint')
290
+ clear.hidden = !input.value
291
+ if (hint) hint.hidden = Boolean(input.value)
292
+ }
293
+
294
+ async function api(action, values = {}, { keepalive = false } = {}) {
295
+ const response = await fetch('./api', {
296
+ method: 'POST',
297
+ headers: { 'Content-Type': 'application/json', 'X-DSH-Agent-Bridge': nonce },
298
+ body: JSON.stringify({ action, ...values }),
299
+ keepalive,
300
+ })
301
+ const data = await response.json().catch(() => null)
302
+ if (!response.ok || !data) throw new Error(data?.error || '无法连接 DSH 插件。')
303
+ return data
304
+ }
305
+
306
+ function status(message, error = false, target = 'status') {
307
+ const element = byId(target)
308
+ element.textContent = message
309
+ element.classList.toggle('error', error)
310
+ }
311
+
312
+ function renderSources(sources) {
313
+ byId('sources-heading').textContent = `本机来源 · ${sources.length}`
314
+ byId('sources-list').replaceChildren(...sources.map(source => {
315
+ const row = document.createElement('div')
316
+ row.className = 'source-row'
317
+ const state = text('span', sourceStates[source.status] ?? source.status, 'chip source-state')
318
+ state.dataset.state = source.status
319
+ const name = text('strong', '', 'source-name')
320
+ name.append(agentLabel(source.id, '', source.label))
321
+ row.append(name, state)
322
+ if (source.detail) row.append(text('span', source.detail, 'source-detail'))
323
+ return row
324
+ }))
325
+ }
326
+
327
+ function projectMatches() {
328
+ return catalog.filter(project => (!selectedAgent || project.agents.includes(selectedAgent))
329
+ && [project.name, project.cwd, ...project.projectIds, ...project.agents.map(agentName)]
330
+ .some(value => value.toLowerCase().includes(projectQuery)))
331
+ }
332
+
333
+ function filteredProjects(matches = projectMatches()) {
334
+ if (projectState === 'archived') return matches.filter(project => project.archived)
335
+ return matches.filter(project => !project.archived && (projectState === 'all' || project.online === (projectState === 'online')))
336
+ }
337
+
338
+ function projectGroups(matches) {
339
+ if (!preferencesAvailable || projectState === 'archived') return [['', matches]]
340
+ const pinned = matches.filter(project => project.pinned)
341
+ const recent = matches.filter(project => !project.pinned && project.continuedAt != null)
342
+ .sort((a, b) => b.continuedAt - a.continuedAt).slice(0, 5)
343
+ if (!pinned.length && !recent.length) return [['', matches]]
344
+ const featured = new Set([...pinned, ...recent].map(project => project.id))
345
+ return [['置顶', pinned], ['最近接续', recent], ['其他项目', matches.filter(project => !featured.has(project.id))]]
346
+ }
347
+
348
+ function renderPin() {
349
+ const pinned = Boolean(current?.pinned)
350
+ projectPin.hidden = !preferencesAvailable || !current || current.archived
351
+ projectPin.disabled = !detail || pinRequests.has(current?.id)
352
+ projectPin.setAttribute('aria-pressed', String(pinned))
353
+ byId('project-pin-label').textContent = pinned ? '取消置顶' : '置顶'
354
+ byId('project-pin-icon').setAttribute('href', pinned ? '#icon-unpin' : '#icon-pin')
355
+ }
356
+
357
+ async function toggleProjectPin() {
358
+ if (!preferencesAvailable || !current || current.archived || !detail) return
359
+ const projectId = current.id
360
+ if (pinRequests.has(projectId)) return
361
+ const pinned = !current.pinned
362
+ pinRequests.add(projectId)
363
+ renderPin()
364
+ try {
365
+ const result = await api('set-project-pin', { projectId, pinned })
366
+ lastPinRevision = Math.max(lastPinRevision, result.revision)
367
+ const project = catalog.find(item => item.id === projectId)
368
+ if (project) project.pinned = pinned
369
+ if (current?.id === projectId) current.pinned = pinned
370
+ status('')
371
+ renderProjects()
372
+ } catch (error) {
373
+ status(error.message, true)
374
+ } finally {
375
+ pinRequests.delete(projectId)
376
+ renderPin()
377
+ schedulePoll(0)
378
+ }
379
+ }
380
+
381
+ function renderArchiveControls(matches) {
382
+ const visibleIds = new Set(matches.map(project => project.id))
383
+ for (const id of selectedProjects) {
384
+ if (!visibleIds.has(id)) selectedProjects.delete(id)
385
+ }
386
+ const size = selectedProjects.size
387
+ const action = projectState === 'archived' ? '恢复所选' : '归档所选'
388
+ projectManage.setAttribute('aria-pressed', String(managingProjects))
389
+ projectManage.hidden = !archiveAvailable
390
+ projectManage.disabled = archiveBusy || catalog.length === 0
391
+ byId('project-bulk').hidden = !managingProjects
392
+ selectVisible.checked = size > 0 && size === matches.length
393
+ selectVisible.indeterminate = size > 0 && size < matches.length
394
+ selectVisible.disabled = archiveBusy || matches.length === 0
395
+ bulkArchive.textContent = size ? `${action} · ${size}` : action
396
+ bulkArchive.disabled = archiveBusy || size === 0
397
+ projectUndo.disabled = archiveBusy
398
+ archiveAction.hidden = !archiveAvailable
399
+ archiveAction.disabled = archiveBusy || detailLoading || !current
400
+ }
401
+
402
+ function projectRow(project, matches) {
403
+ const button = document.createElement('button')
404
+ button.type = 'button'
405
+ button.className = 'project'
406
+ button.id = `project-${project.id}`
407
+ button.setAttribute('aria-pressed', String(current?.id === project.id))
408
+ button.title = project.cwd
409
+ const mark = text('span', '', 'project-icon')
410
+ mark.dataset.agent = project.agents[0] || 'local'
411
+ mark.append(icon('folder'))
412
+ const main = text('span', '', 'project-main')
413
+ main.append(text('span', project.name, 'project-title'), text('span', shortPath(project.cwd), 'project-path'))
414
+ const source = text('span', '', 'project-source')
415
+ for (const agent of project.agents.slice(0, 2)) source.append(agentLabel(agent))
416
+ if (project.agents.length > 2) {
417
+ const rest = text('span', `+${project.agents.length - 2}`, 'project-more-agents')
418
+ rest.title = project.agents.slice(2).map(agentName).join('、')
419
+ source.append(rest)
420
+ }
421
+ if (!project.agents.length) source.textContent = '本地项目'
422
+ const indicator = text('span', '', 'project-state')
423
+ indicator.dataset.state = project.online ? 'online' : 'offline'
424
+ indicator.setAttribute('aria-label', project.online ? '原目录可用' : '原目录不可访问')
425
+ main.append(source)
426
+ button.append(mark, main, indicator)
427
+ button.addEventListener('click', () => selectProject(project, true))
428
+ if (!managingProjects) return button
429
+ const row = text('div', '', 'project-row')
430
+ const check = document.createElement('input')
431
+ check.id = `check-project-${project.id}`
432
+ check.className = 'project-check'
433
+ check.type = 'checkbox'
434
+ check.checked = selectedProjects.has(project.id)
435
+ check.disabled = archiveBusy
436
+ check.setAttribute('aria-label', `选择 ${project.name}`)
437
+ check.addEventListener('change', () => {
438
+ if (check.checked) selectedProjects.add(project.id)
439
+ else selectedProjects.delete(project.id)
440
+ renderArchiveControls(matches)
441
+ })
442
+ row.append(check, button)
443
+ return row
444
+ }
445
+
446
+ function renderProjects() {
447
+ syncSearch(projectSearch)
448
+ const base = projectMatches()
449
+ const matches = filteredProjects(base)
450
+ const active = base.filter(project => !project.archived)
451
+ const online = active.filter(project => project.online).length
452
+ const counts = { all: active.length, online, offline: active.length - online, archived: base.length - active.length }
453
+ const labels = { all: '未归档', online: '可接续', offline: '离线', archived: '已归档' }
454
+ for (const button of projectFilters) {
455
+ const state = button.dataset.projectState
456
+ button.hidden = state === 'archived' && !archiveAvailable
457
+ button.setAttribute('aria-pressed', String(projectState === state))
458
+ button.replaceChildren(document.createTextNode(labels[state]), text('span', counts[state], 'filter-count'))
459
+ }
460
+ const total = catalog.filter(project => Boolean(project.archived) === (projectState === 'archived')).length
461
+ byId('project-count').textContent = matches.length === total ? `${total} 项` : `${matches.length} / ${total}`
462
+ renderArchiveControls(matches)
463
+ const items = []
464
+ for (const [label, group] of projectGroups(matches)) {
465
+ if (!group.length) continue
466
+ if (label) items.push(text('h3', label, 'project-group-heading'))
467
+ for (const project of group) items.push(projectRow(project, matches))
468
+ }
469
+ const focused = projectList.contains(document.activeElement) ? document.activeElement.id : ''
470
+ const scroll = projectList.scrollTop
471
+ const emptyMessage = projectState === 'archived' ? '没有匹配的归档项目。' : '没有匹配的项目。'
472
+ projectList.replaceChildren(...(items.length ? items : [text('p', emptyMessage, 'asset-empty')]))
473
+ projectList.scrollTop = scroll
474
+ if (focused) byId(focused)?.focus({ preventScroll: true })
475
+ }
476
+
477
+ function archiveFeedback(message, error = false) {
478
+ const feedback = byId('project-feedback')
479
+ feedback.hidden = !message
480
+ feedback.classList.toggle('error', error)
481
+ byId('project-feedback-text').textContent = message
482
+ projectUndo.hidden = !undoArchive
483
+ }
484
+
485
+ function emptyProjectDetail(message) {
486
+ current = undefined
487
+ detail = undefined
488
+ context = undefined
489
+ detailLoading = false
490
+ ++detailRevision
491
+ byId('empty').textContent = message
492
+ byId('empty').hidden = false
493
+ byId('project-detail').hidden = true
494
+ byId('preview').disabled = true
495
+ }
496
+
497
+ function reconcileProject(matches, selectFirst = false) {
498
+ if (current && matches.some(project => project.id === current.id)) return
499
+ if (selectFirst && matches.length) {
500
+ const [, firstGroup] = projectGroups(matches).find(([, group]) => group.length)
501
+ void selectProject(firstGroup[0])
502
+ } else if (matches.length) emptyProjectDetail('从项目列表选择要接续的项目。')
503
+ else if (catalog.length) emptyProjectDetail('当前筛选下没有项目。')
504
+ else if (catalogLoaded) emptyProjectDetail('未找到可浏览的项目。请展开本机来源查看读取状态。')
505
+ }
506
+
507
+ function updateProjectView() {
508
+ reconcileProject(filteredProjects())
509
+ renderProjects()
510
+ }
511
+
512
+ function updateProjectSearch() {
513
+ projectQuery = projectSearch.value.trim().toLowerCase()
514
+ updateProjectView()
515
+ }
516
+
517
+ async function updateProjectArchive(projectIds, archived, undo = false) {
518
+ if (!projectIds.length || archiveBusy) return
519
+ if (refreshing) {
520
+ archiveFeedback('正在刷新项目,请稍后重试。', true)
521
+ return
522
+ }
523
+ const origin = document.activeElement
524
+ archiveBusy = true
525
+ renderProjects()
526
+ try {
527
+ const result = await api('set-project-archive', { projectIds, archived })
528
+ const updated = new Set(result.projectIds)
529
+ for (const project of catalog) {
530
+ if (updated.has(project.id)) project.archived = archived
531
+ }
532
+ if (updated.has(current?.id)) current.archived = archived
533
+ reconcileProject(filteredProjects(), true)
534
+ selectedProjects.clear()
535
+ const changed = result.changedProjectIds
536
+ undoArchive = !undo && changed.length ? { projectIds: changed, archived: !archived } : undefined
537
+ archiveFeedback(changed.length ? `已${archived ? '归档' : '恢复'} ${changed.length} 个项目` : '项目已处于所选状态。')
538
+ } catch (error) {
539
+ archiveFeedback(error.message, true)
540
+ } finally {
541
+ archiveBusy = false
542
+ renderProjects()
543
+ if (document.activeElement === document.body && [archiveAction, bulkArchive, projectUndo].includes(origin)) {
544
+ if (origin === bulkArchive && !selectVisible.disabled) selectVisible.focus({ preventScroll: true })
545
+ else projectFilters.find(button => button.dataset.projectState === projectState)?.focus({ preventScroll: true })
546
+ }
547
+ schedulePoll(0)
548
+ }
549
+ }
550
+
551
+ function renderSelection() {
552
+ if (!context) return
553
+ const entries = context.entries.filter(item => selected.has(item.id))
554
+ const skillCount = entries.filter(item => item.kind === 'skill').length
555
+ const memoryCount = entries.length - skillCount
556
+ const parts = [memoryCount ? `${memoryCount} 份记忆` : '', skillCount ? `${skillCount} 个 Skills` : ''].filter(Boolean)
557
+ const summary = parts.join('、') || '未选资料'
558
+ byId('selection-summary').textContent = `接续清单 · ${summary}${historyOption.checked ? ' + 摘录' : ''}`
559
+ const globalCount = entries.filter(item => item.global).length
560
+ byId('selection-global').textContent = `${globalCount} 项全局`
561
+ byId('selection-global').hidden = globalCount === 0
562
+ renderGlobalCount()
563
+ const focused = queueList.contains(document.activeElement) ? document.activeElement.id : ''
564
+ const scroll = queueList.scrollTop
565
+ queueList.replaceChildren(...(entries.length ? entries.map(item => {
566
+ const row = text('div', '', 'queue-item')
567
+ const title = materialName(item)
568
+ const name = text('span', title, 'queue-title')
569
+ name.title = title
570
+ const kindLabel = text('span', `${item.global ? '全局 ' : ''}${item.kind === 'memory' ? '记忆' : 'Skill'}`, 'queue-kind')
571
+ const remove = text('button', '', 'queue-remove icon-button')
572
+ remove.type = 'button'
573
+ remove.id = `queue-remove-${item.id}`
574
+ remove.setAttribute('aria-label', `移除 ${title}`)
575
+ remove.append(icon('close'))
576
+ remove.addEventListener('click', () => {
577
+ const next = row.nextElementSibling ?? row.previousElementSibling
578
+ const focusId = next?.querySelector('.queue-remove')?.id
579
+ selected.delete(item.id)
580
+ void saveProjectSelection()
581
+ renderAssets()
582
+ const focusTarget = byId(focusId) ?? byId('handoff').querySelector('summary')
583
+ focusTarget.focus({ preventScroll: true })
584
+ })
585
+ row.append(icon(item.kind, 'queue-icon'), name, kindLabel, remove)
586
+ return row
587
+ }) : [text('p', '尚未选择记忆或 Skills。', 'queue-empty')]))
588
+ queueList.scrollTop = scroll
589
+ if (focused) byId(focused)?.focus({ preventScroll: true })
590
+ }
591
+
592
+ function saveProjectSelection() {
593
+ if (!current || !detail) return
594
+ const projectId = current.id
595
+ projectSelections.set(projectId, { assetIds: [...selected], history: includeHistory })
596
+ if (!preferencesAvailable || selectionSaves.has(projectId)) return
597
+ selectionSaves.set(projectId, flushProjectSelection(projectId))
598
+ }
599
+
600
+ async function flushProjectSelection(projectId) {
601
+ try {
602
+ while (projectSelections.has(projectId)) {
603
+ const selection = projectSelections.get(projectId)
604
+ try {
605
+ await api('set-project-selection', { projectId, ...selection }, { keepalive: true })
606
+ if (projectSelections.get(projectId) === selection) projectSelections.delete(projectId)
607
+ } catch (error) {
608
+ if (projectSelections.get(projectId) !== selection) continue
609
+ if (current?.id === projectId) status(`勾选已保留在当前面板。${error.message}`, true)
610
+ return
611
+ }
612
+ }
613
+ } finally {
614
+ selectionSaves.delete(projectId)
615
+ }
616
+ }
617
+
618
+ function materialName(asset) {
619
+ if (asset.kind === 'skill') return asset.name
620
+ if (/^memory[-_]summary$/i.test(asset.name)) return '记忆摘要'
621
+ if (/^memory$/i.test(asset.name)) return asset.global ? '长期记忆' : '项目记忆'
622
+ if (asset.group === 'guides' && /^(?:AGENTS|CLAUDE|GEMINI|QWEN|USER|SOUL)$/i.test(asset.name)) {
623
+ const label = asset.agent === 'shared' ? '' : `${agentName(asset.agent)} `
624
+ return label + (asset.global ? '全局指引' : '项目指引')
625
+ }
626
+ if (/^current[- _]state$/i.test(asset.name)) return '当前状态'
627
+ if (/^latest[- _]handoff$/i.test(asset.name)) return '最新交接'
628
+ return asset.name
629
+ }
630
+
631
+ function matchesMaterial(asset, query) {
632
+ return [materialName(asset), asset.name, agentName(asset.agent), asset.file, asset.detail]
633
+ .some(value => value?.toLowerCase().includes(query))
634
+ }
635
+
636
+ function renderGlobalCount() {
637
+ const assets = context.entries.filter(asset => asset.global)
638
+ const query = assetSearch.value.trim().toLowerCase()
639
+ const count = query ? assets.filter(asset => matchesMaterial(asset, query)).length : assets.length
640
+ const checked = assets.filter(asset => selected.has(asset.id)).length
641
+ globalLibrary.hidden = assets.length === 0
642
+ byId('global-count').textContent = `${count} ${query ? '项匹配' : '项'}${checked ? ` · ${checked} 已选` : ''}`
643
+ }
644
+
645
+ function makeMaterialRow(asset) {
646
+ const name = materialName(asset)
647
+ const row = text('div', '', 'asset-row')
648
+ const checkbox = document.createElement('input')
649
+ checkbox.type = 'checkbox'
650
+ checkbox.className = 'asset-check'
651
+ checkbox.id = `asset-${asset.id}`
652
+ checkbox.checked = selected.has(asset.id)
653
+ row.dataset.selected = String(checkbox.checked)
654
+ checkbox.addEventListener('change', () => {
655
+ if (checkbox.checked && selected.size >= 24) {
656
+ checkbox.checked = false
657
+ status('每次最多选择 24 项资料。', true, 'selection-feedback')
658
+ return
659
+ }
660
+ if (checkbox.checked) selected.add(asset.id)
661
+ else selected.delete(asset.id)
662
+ row.dataset.selected = String(checkbox.checked)
663
+ status('', false, 'selection-feedback')
664
+ renderSelection()
665
+ void saveProjectSelection()
666
+ })
667
+ const label = text('label', '', 'asset-label')
668
+ label.htmlFor = checkbox.id
669
+ label.title = name === asset.name ? asset.file : `${asset.name}\n${asset.file}`
670
+ const title = text('span', name, 'asset-title')
671
+ const meta = text('span', '', 'asset-meta')
672
+ if (asset.agent) meta.append(agentLabel(asset.agent))
673
+ if (!asset.global && context.suggestedIds.includes(asset.id)) {
674
+ meta.append(text('span', '建议带入', 'material-suggestion'))
675
+ } else if (asset.global && asset.used) {
676
+ meta.append(text('span', '近期会话提及', 'material-suggestion'))
677
+ }
678
+ label.append(title, meta)
679
+ const button = text('button', '', 'asset-view')
680
+ button.append(document.createTextNode('查看'), icon('chevron'))
681
+ button.type = 'button'
682
+ button.id = `asset-view-${asset.id}`
683
+ button.setAttribute('aria-label', `查看 ${name}`)
684
+ button.addEventListener('click', () => viewAsset(asset))
685
+ const marker = text('span', '', 'asset-icon')
686
+ marker.append(icon(asset.kind))
687
+ row.append(checkbox, marker, label, button)
688
+ return row
689
+ }
690
+
691
+ function fillMaterials(target, groups, assets, emptyMessage) {
692
+ const scroll = target.scrollTop
693
+ const focused = target.contains(document.activeElement) ? document.activeElement.id : ''
694
+ const sections = groups.flatMap(([key, title, note]) => {
695
+ const members = assets.filter(item => item.group === key)
696
+ if (!members.length) return []
697
+ const group = text('section', '', 'asset-group')
698
+ const heading = text('h4', title, 'asset-group-heading')
699
+ heading.append(text('span', String(members.length), 'disclosure-count'))
700
+ group.append(heading)
701
+ if (note) group.append(text('p', note, 'asset-group-note'))
702
+ group.append(...members.map(makeMaterialRow))
703
+ return [group]
704
+ })
705
+ target.replaceChildren(...(sections.length ? sections : [text('p', emptyMessage, 'asset-empty')]))
706
+ target.scrollTop = scroll
707
+ if (focused) byId(focused)?.focus({ preventScroll: true })
708
+ }
709
+
710
+ function renderGlobalMaterials() {
711
+ if (!context || !globalLibrary.open) return
712
+ const query = assetSearch.value.trim().toLowerCase()
713
+ fillMaterials(globalMaterials, globalGroups, context.entries.filter(item => item.global && matchesMaterial(item, query)), '没有匹配的全局资料。')
714
+ }
715
+
716
+ function renderAssets() {
717
+ if (!context || !draftWorkflow.open) return
718
+ const query = assetSearch.value.trim().toLowerCase()
719
+ syncSearch(assetSearch)
720
+ fillMaterials(projectMaterials, materialGroups, context.entries.filter(item => !item.global && matchesMaterial(item, query)),
721
+ query ? '没有匹配的项目资料。' : '没有找到项目专用资料。你也可以直接预览草稿。')
722
+ renderGlobalMaterials()
723
+ renderSelection()
724
+ }
725
+
726
+ function applyDetail(project, loaded, preserve) {
727
+ showProject(loaded.project ?? project)
728
+ detail = loaded
729
+ context = describeProjectContext(loaded)
730
+ if (!preserve) {
731
+ const saved = projectSelections.get(project.id) ?? loaded.selection
732
+ if (saved) {
733
+ selected = new Set(saved.assetIds)
734
+ includeHistory = saved.history
735
+ } else {
736
+ selected = new Set(context.suggestedIds)
737
+ includeHistory = false
738
+ }
739
+ }
740
+ const available = new Set(context.entries.map(item => item.id))
741
+ selected = new Set([...selected].filter(id => available.has(id)))
742
+ historyOption.checked = includeHistory && detail.historyCount > 0
743
+ historyOption.disabled = detail.historyCount === 0
744
+ byId('history-option').hidden = detail.historyCount === 0
745
+ byId('history-label').textContent = `带入近期对话摘录(最多 ${Math.min(8, detail.historyCount)} 条消息)`
746
+ byId('preview').disabled = false
747
+ assetSearch.disabled = false
748
+ renderAssets()
749
+ }
750
+
751
+ function showProject(project) {
752
+ const latest = catalog.find(item => item.id === project.id) ?? project
753
+ current = { ...project, archived: Boolean(latest.archived), pinned: Boolean(latest.pinned) }
754
+ byId('project-name').textContent = current.name
755
+ byId('project-path').textContent = current.cwd
756
+ byId('project-path').title = current.cwd
757
+ const availability = text('span', current.online ? '原目录可用' : '原目录不可访问', 'chip availability')
758
+ availability.dataset.state = current.online ? 'online' : 'offline'
759
+ byId('project-meta').replaceChildren(...current.projectIds.map(value => text('span', value, 'chip')),
760
+ ...current.agents.map(agent => agentLabel(agent, 'chip')), availability)
761
+ if (current.archived) {
762
+ const archived = text('span', '已归档', 'chip')
763
+ archived.dataset.state = 'archived'
764
+ byId('project-meta').append(archived)
765
+ }
766
+ byId('project-archive-action-label').textContent = current.archived ? '恢复项目' : '归档项目'
767
+ byId('project-archive-action-icon').setAttribute('href', current.archived ? '#icon-restore' : '#icon-archive')
768
+ archiveAction.disabled = archiveBusy
769
+ renderPin()
770
+ byId('empty').hidden = true
771
+ byId('project-detail').hidden = false
772
+ }
773
+
774
+ function revealProjectDetail() {
775
+ if (!compactLayout.matches) return
776
+ const heading = byId('project-name')
777
+ heading.focus({ preventScroll: true })
778
+ heading.closest('.detail').scrollIntoView({ block: 'start', behavior: reducedMotion.matches ? 'instant' : 'smooth' })
779
+ }
780
+
781
+ function makeConversationRow(session, open) {
782
+ const row = text('li', '', 'conversation-item')
783
+ const button = text('button', '', 'conversation-row')
784
+ button.type = 'button'
785
+ button.dataset.session = session.id
786
+ const title = session.title || '未命名对话'
787
+ button.title = title
788
+ const info = text('span', '', 'conversation-info')
789
+ const meta = text('span', agentName(session.agent), 'conversation-meta')
790
+ if (session.archivedSource) meta.append(text('span', ' · 本地存档'))
791
+ const date = new Date(session.date)
792
+ if (session.date > 0 && Number.isFinite(date.getTime())) {
793
+ const today = new Date()
794
+ const yesterday = new Date(today)
795
+ yesterday.setDate(today.getDate() - 1)
796
+ const day = date.toDateString()
797
+ const display = day === today.toDateString() ? `今天 ${shortClock.format(date)}`
798
+ : day === yesterday.toDateString() ? `昨天 ${shortClock.format(date)}`
799
+ : date.getFullYear() === today.getFullYear() ? recentDateFormat.format(date) : historyDateFormat.format(date)
800
+ const timestamp = text('time', display)
801
+ timestamp.dateTime = date.toISOString()
802
+ timestamp.title = historyDateFormat.format(date)
803
+ meta.append(text('span', ' · '), timestamp)
804
+ }
805
+ info.append(text('span', title, 'conversation-title'), meta)
806
+ const action = text('span', '', 'conversation-action')
807
+ action.append(text('span', '预览'), icon('chevron'))
808
+ button.append(agentMark(session.agent), info, action)
809
+ button.addEventListener('click', () => open(session))
810
+ row.append(button)
811
+ return row
812
+ }
813
+
814
+ function resetRecentConversations() {
815
+ recentRevision++
816
+ recentKey = ''
817
+ recentList.replaceChildren()
818
+ browseHistory.hidden = true
819
+ }
820
+
821
+ async function loadRecentConversations(project) {
822
+ const revision = ++recentRevision
823
+ const isCurrent = () => current?.id === project.id && recentRevision === revision
824
+ if (!nativeSessionImport || !project.hasConversations) {
825
+ resetRecentConversations()
826
+ recentStatus.textContent = nativeSessionImport
827
+ ? '这个项目还没有可迁入的对话。可以用项目资料开新对话。'
828
+ : '当前 DSH 不支持迁入旧对话。可以用项目资料开新对话。'
829
+ return
830
+ }
831
+ if (!recentKey) recentStatus.textContent = '正在查找最近对话…'
832
+ try {
833
+ const { sessions, total } = await api('list-conversations', { projectId: project.id, recent: true })
834
+ if (!isCurrent()) return
835
+ const key = JSON.stringify(sessions)
836
+ if (key !== recentKey) {
837
+ const active = recentList.contains(document.activeElement) ? document.activeElement.dataset.session : ''
838
+ recentList.replaceChildren(...sessions.map(session => makeConversationRow(session, item => openSourceConversation(item))))
839
+ if (active) ([...recentList.querySelectorAll('button')].find(button => button.dataset.session === active)
840
+ ?? byId('continue-heading')).focus({ preventScroll: true })
841
+ recentKey = key
842
+ }
843
+ recentStatus.textContent = sessions.length
844
+ ? (current.online ? '' : '原工作目录不可访问,暂时只能预览。')
845
+ : '这个项目还没有可迁入的对话。可以用项目资料开新对话。'
846
+ byId('browse-history-label').textContent = `查看全部 ${total ?? sessions.length} 条对话`
847
+ browseHistory.hidden = (total ?? sessions.length) <= sessions.length
848
+ } catch {
849
+ if (!isCurrent()) return
850
+ recentStatus.textContent = recentList.childElementCount
851
+ ? '暂时无法刷新对话列表,可稍后重试。'
852
+ : '暂时读不到对话列表。可以刷新来源,或用项目资料开新对话。'
853
+ }
854
+ }
855
+
856
+ async function selectProject(project, reveal = false) {
857
+ if (!filteredProjects().some(item => item.id === project.id)) return
858
+ if (current?.id === project.id && (detail || detailLoading)) {
859
+ if (reveal) revealProjectDetail()
860
+ return
861
+ }
862
+ const revision = ++detailRevision
863
+ detail = undefined
864
+ context = undefined
865
+ detailLoading = true
866
+ selected = new Set()
867
+ assetSearch.value = ''
868
+ syncSearch(assetSearch)
869
+ draftWorkflow.open = false
870
+ globalLibrary.open = false
871
+ globalLibrary.hidden = true
872
+ byId('handoff').open = false
873
+ byId('history-option').hidden = true
874
+ byId('selection-global').hidden = true
875
+ byId('selection-summary').textContent = '接续清单'
876
+ byId('preview').disabled = true
877
+ assetSearch.disabled = true
878
+ status('', false, 'selection-feedback')
879
+ projectMaterials.replaceChildren(text('p', '正在读取项目资料…', 'asset-empty'))
880
+ globalMaterials.replaceChildren()
881
+ queueList.replaceChildren()
882
+ resetRecentConversations()
883
+ showProject(project)
884
+ renderProjects()
885
+ if (reveal) revealProjectDetail()
886
+ void loadRecentConversations(project)
887
+ try {
888
+ const pendingSelection = selectionSaves.get(project.id)
889
+ if (pendingSelection) await pendingSelection
890
+ if (revision !== detailRevision) return
891
+ const loaded = await api('detail', { projectId: project.id })
892
+ if (revision !== detailRevision) return
893
+ applyDetail(project, loaded, false)
894
+ } catch (error) {
895
+ if (revision === detailRevision) projectMaterials.replaceChildren(text('p', error.message, 'asset-empty error'))
896
+ } finally {
897
+ if (revision === detailRevision) detailLoading = false
898
+ }
899
+ }
900
+
901
+ function canAutoRefresh() {
902
+ return document.visibilityState === 'visible' && !dialog.open && agentPopover.hidden && !detailLoading && !archiveBusy
903
+ }
904
+
905
+ function liveState(label, scannedAt, error) {
906
+ const indicator = byId('live-state')
907
+ indicator.textContent = label
908
+ indicator.dataset.state = error ? 'error' : label.includes('暂停') ? 'paused' : scannedAt ? 'active' : 'loading'
909
+ indicator.title = error ?? ''
910
+ if (scannedAt) {
911
+ const timestamp = new Date(scannedAt)
912
+ if (Number.isNaN(timestamp.getTime())) return
913
+ const lastScan = byId('last-scan')
914
+ lastScan.dateTime = timestamp.toISOString()
915
+ lastScan.textContent = `上次扫描 ${clockFormat.format(timestamp)}`
916
+ lastScan.hidden = false
917
+ }
918
+ }
919
+
920
+ async function refresh(force, automatic = false) {
921
+ if (refreshing || archiveBusy || (automatic && !canAutoRefresh())) return false
922
+ refreshing = true
923
+ refreshButton.disabled = true
924
+ refreshButton.dataset.loading = 'true'
925
+ if (!automatic) status(force ? '正在重新扫描本机来源…' : '正在扫描本机来源…')
926
+ try {
927
+ const result = await api('catalog', { refresh: force })
928
+ if (dialog.open || (automatic && !canAutoRefresh())) return false
929
+ if (result.revision < lastPinRevision) return false
930
+ const firstLoad = !catalogLoaded
931
+ catalogLoaded = true
932
+ catalog = result.projects
933
+ archiveAvailable = catalog.every(project => typeof project.archived === 'boolean')
934
+ nativeSessionImport = result.nativeSessionImport === true
935
+ preferencesAvailable = catalog.every(project => typeof project.pinned === 'boolean')
936
+ agentIcons = result.agentIcons ?? {}
937
+ const activeAgent = availableAgents[activeAgentIndex]
938
+ availableAgents = ['', ...[...new Set([selectedAgent, ...catalog.flatMap(project => project.agents)])]
939
+ .filter(Boolean).sort((left, right) => agentName(left).localeCompare(agentName(right), 'zh-CN'))]
940
+ renderAgentPicker(activeAgent)
941
+ renderSources(result.sources)
942
+ if (!archiveAvailable || !preferencesAvailable) status('请完全退出 DSH 并重新打开,加载新版插件。')
943
+ else if (!automatic) status('')
944
+ const matches = filteredProjects()
945
+ reconcileProject(matches, firstLoad)
946
+ renderProjects()
947
+ const previous = matches.find(project => project.id === current?.id)
948
+ const revision = detailRevision
949
+ if (previous && !detailLoading) {
950
+ if (!detail) {
951
+ void selectProject(previous)
952
+ } else {
953
+ showProject(previous)
954
+ void loadRecentConversations(previous)
955
+ const loaded = await api('detail', { projectId: previous.id })
956
+ if (revision === detailRevision && !dialog.open) applyDetail(previous, loaded, true)
957
+ }
958
+ }
959
+ sourceRevision = result.revision ?? sourceRevision
960
+ liveState('实时扫描已开启', result.scannedAt)
961
+ return true
962
+ } catch (error) {
963
+ liveState('实时扫描暂不可用', undefined, error.message)
964
+ if (!automatic) {
965
+ status(error.message, true)
966
+ byId('empty').textContent = '项目列表暂不可用。'
967
+ }
968
+ return false
969
+ } finally {
970
+ refreshing = false
971
+ refreshButton.disabled = false
972
+ delete refreshButton.dataset.loading
973
+ }
974
+ }
975
+
976
+ function schedulePoll(delay = 250) {
977
+ clearTimeout(pollTimer)
978
+ if (document.visibilityState === 'visible' && !dialog.open && agentPopover.hidden) pollTimer = setTimeout(pollSources, delay)
979
+ }
980
+
981
+ async function pollSources() {
982
+ if (polling) return
983
+ if (refreshing || !canAutoRefresh()) {
984
+ schedulePoll()
985
+ return
986
+ }
987
+ polling = true
988
+ const baseline = sourceRevision
989
+ let delay = 250
990
+ try {
991
+ const result = await api('changes', { revision: baseline, projectId: current?.id, wait: true })
992
+ if (sourceRevision !== baseline || refreshing || !canAutoRefresh()) return
993
+ if (result.changed) {
994
+ if (!await refresh(false, true)) delay = 1000
995
+ else if (sourceRevision === baseline) sourceRevision = result.revision ?? sourceRevision
996
+ return
997
+ }
998
+ sourceRevision = result.revision ?? sourceRevision
999
+ liveState('实时扫描已开启', result.scannedAt)
1000
+ } catch (error) {
1001
+ if (canAutoRefresh()) liveState('实时扫描暂不可用', undefined, error.message)
1002
+ delay = 5000
1003
+ } finally {
1004
+ polling = false
1005
+ schedulePoll(delay)
1006
+ }
1007
+ }
1008
+
1009
+ function clearDownload() {
1010
+ if (downloadUrl) {
1011
+ const previousUrl = downloadUrl
1012
+ setTimeout(() => URL.revokeObjectURL(previousUrl), 30_000)
1013
+ }
1014
+ downloadUrl = undefined
1015
+ exportDownload.removeAttribute('href')
1016
+ exportDownload.hidden = true
1017
+ byId('export-output').hidden = true
1018
+ byId('export-output').open = false
1019
+ byId('export-text').textContent = ''
1020
+ }
1021
+
1022
+ function setDialogBusy(busy) {
1023
+ dialogBusy = busy
1024
+ dialogClose.disabled = busy
1025
+ importButton.disabled = busy
1026
+ recoverDraftButton.disabled = busy
1027
+ exportButton.disabled = busy
1028
+ sessionSelect.disabled = busy
1029
+ byId('history-back-button').disabled = busy
1030
+ historyImport.disabled = busy
1031
+ }
1032
+
1033
+ function showDialog(mode, title, note, body, assetKind = 'memory') {
1034
+ dialogMode = mode
1035
+ dialog.dataset.mode = mode
1036
+ ticket = undefined
1037
+ nativeSessions = []
1038
+ historyProject = undefined
1039
+ historySessions = undefined
1040
+ historyChosenId = undefined
1041
+ historyTicket = undefined
1042
+ importedSessionId = undefined
1043
+ draftRecovery = undefined
1044
+ clearDownload()
1045
+ byId('dialog-title').textContent = title
1046
+ byId('dialog-note').textContent = note
1047
+ byId('dialog-mark').replaceChildren(icon(mode === 'session' ? 'download' : mode === 'asset' ? assetKind : mode === 'history' ? 'history' : 'bridge'))
1048
+ dialogText.hidden = false
1049
+ dialogText.dataset.format = 'plain'
1050
+ dialogText.textContent = body
1051
+ dialogText.closest('.dialog-content').scrollTop = 0
1052
+ byId('session-choice').hidden = true
1053
+ byId('history-choice').hidden = true
1054
+ byId('history-back').hidden = true
1055
+ status('', false, 'dialog-status')
1056
+ importButton.hidden = true
1057
+ recoverDraftButton.hidden = true
1058
+ exportButton.hidden = true
1059
+ historyImport.hidden = true
1060
+ setDialogBusy(false)
1061
+ if (!dialog.open) dialog.showModal()
1062
+ clearTimeout(pollTimer)
1063
+ liveState('实时扫描已暂停')
1064
+ return ++dialogEpoch
1065
+ }
1066
+
1067
+ function startHistoryDialog(title, note, body) {
1068
+ const project = current
1069
+ if (dialog.open || !project || !nativeSessionImport || !filteredProjects().some(item => item.id === project.id)) return
1070
+ const epoch = showDialog('history', title, note, body)
1071
+ historyProject = project
1072
+ return epoch
1073
+ }
1074
+
1075
+ const historyNote = '迁入用户与助手的文字消息。工具记录、附件和运行状态留在来源 Agent。'
1076
+
1077
+ function openSourceConversation(session) {
1078
+ if (startHistoryDialog('继续旧对话', historyNote, '正在读取这条对话…') === undefined) return
1079
+ void previewSourceConversation(session)
1080
+ }
1081
+
1082
+ async function chooseSourceConversation() {
1083
+ const epoch = startHistoryDialog('查看全部对话', '选择一条对话以预览历史消息。', '正在读取对话列表…')
1084
+ if (epoch === undefined) return
1085
+ try {
1086
+ const { sessions } = await api('list-conversations', { projectId: historyProject.id })
1087
+ if (!dialog.open || dialogEpoch !== epoch) return
1088
+ historySessions = sessions
1089
+ historySearch.value = ''
1090
+ historyLimit = 30
1091
+ showHistoryResults()
1092
+ } catch (error) {
1093
+ if (dialog.open && dialogEpoch === epoch) dialogText.textContent = error.message
1094
+ }
1095
+ }
1096
+
1097
+ function renderHistoryResults() {
1098
+ const query = historySearch.value.trim().toLowerCase()
1099
+ syncSearch(historySearch)
1100
+ const matches = historySessions.filter(session => [session.title, agentName(session.agent)]
1101
+ .some(value => value?.toLowerCase().includes(query)))
1102
+ historyResults.replaceChildren(...matches.slice(0, historyLimit).map(session => makeConversationRow(session, previewSourceConversation)))
1103
+ byId('history-empty').textContent = matches.length ? '' : (query ? '没有找到匹配的对话。' : '这个项目暂无可迁入的对话。')
1104
+ byId('history-more').hidden = matches.length <= historyLimit
1105
+ }
1106
+
1107
+ function showHistoryResults() {
1108
+ if (!historySessions) return
1109
+ historyPreview++
1110
+ historyTicket = undefined
1111
+ importedSessionId = undefined
1112
+ historyImport.hidden = true
1113
+ byId('history-back').hidden = true
1114
+ byId('dialog-title').textContent = '查看全部对话'
1115
+ byId('dialog-note').textContent = '选择一条对话以预览历史消息。'
1116
+ dialogText.hidden = true
1117
+ byId('history-choice').hidden = false
1118
+ status('', false, 'dialog-status')
1119
+ renderHistoryResults()
1120
+ dialogText.closest('.dialog-content').scrollTop = 0
1121
+ const previous = historyChosenId && [...historyResults.querySelectorAll('button')].find(button => button.dataset.session === historyChosenId)
1122
+ ;(previous || historySearch).focus()
1123
+ }
1124
+
1125
+ async function previewSourceConversation(session) {
1126
+ const epoch = dialogEpoch
1127
+ const revision = ++historyPreview
1128
+ historyChosenId = session.id
1129
+ historyTicket = undefined
1130
+ importedSessionId = undefined
1131
+ historyImport.hidden = true
1132
+ byId('history-import-label').textContent = '迁入并继续'
1133
+ byId('history-choice').hidden = true
1134
+ byId('history-back').hidden = !historySessions
1135
+ byId('dialog-title').textContent = '继续旧对话'
1136
+ byId('dialog-note').textContent = historyNote
1137
+ dialogText.hidden = false
1138
+ dialogText.dataset.format = 'plain'
1139
+ dialogText.textContent = '正在读取这条对话…'
1140
+ dialogText.closest('.dialog-content').scrollTop = 0
1141
+ if (historySessions) byId('history-back-button').focus()
1142
+ else dialogText.focus({ preventScroll: true })
1143
+ status('', false, 'dialog-status')
1144
+ try {
1145
+ const result = await api('preview-conversation', { projectId: historyProject.id, sessionId: session.id })
1146
+ if (!dialog.open || dialogEpoch !== epoch || revision !== historyPreview) return
1147
+ historyTicket = result.ticket
1148
+ const title = text('h3', result.title, 'preview-lead')
1149
+ const source = text('p', '', 'preview-context history-source')
1150
+ source.append(agentLabel(session.agent), text('code', result.cwd || historyProject.cwd, 'preview-source'))
1151
+ const summary = text('p', [
1152
+ result.messages.length + ' 条文字消息',
1153
+ result.truncated ? '源记录或读取范围有限,部分历史未带入' : '',
1154
+ result.canImport ? '' : '原工作目录不可访问,当前可预览',
1155
+ ].filter(Boolean).join(' · '), 'preview-context')
1156
+ dialogText.dataset.format = 'history'
1157
+ dialogText.replaceChildren(title, source, summary, ...result.messages.map(message => {
1158
+ const row = text('section', '', 'history-message')
1159
+ row.dataset.role = message.role
1160
+ row.append(text('h3', message.role === 'user' ? '用户' : '助手'), text('p', message.text, 'preview-body'))
1161
+ return row
1162
+ }))
1163
+ historyImport.hidden = !result.canImport
1164
+ } catch (error) {
1165
+ if (dialog.open && dialogEpoch === epoch && revision === historyPreview) dialogText.textContent = error.message
1166
+ }
1167
+ }
1168
+
1169
+ async function importSourceConversation() {
1170
+ if (!historyTicket || dialogBusy) return
1171
+ setDialogBusy(true)
1172
+ status(importedSessionId ? '正在打开已迁入的会话…' : '正在迁入会话…', false, 'dialog-status')
1173
+ try {
1174
+ if (!importedSessionId) {
1175
+ const result = await api('import-conversation', { ticket: historyTicket })
1176
+ importedSessionId = result.sessionId
1177
+ }
1178
+ await requestParent('open-imported', { sessionId: importedSessionId })
1179
+ dialog.close()
1180
+ status('历史已迁入。打开会话即可继续。')
1181
+ } catch (error) {
1182
+ if (importedSessionId) byId('history-import-label').textContent = '打开已迁入会话'
1183
+ status(error.message, true, 'dialog-status')
1184
+ } finally {
1185
+ setDialogBusy(false)
1186
+ }
1187
+ }
1188
+
1189
+ function renderHandoff({ intro, sections, footer }) {
1190
+ const lead = text('div', '', 'preview-intro')
1191
+ const [heading, ...introLines] = intro.split('\n')
1192
+ lead.append(text('p', heading, 'preview-lead'))
1193
+ for (const line of introLines.slice(0, 2)) {
1194
+ const metadata = /^(工作目录|来源):(.+)$/.exec(line)
1195
+ if (metadata) {
1196
+ const row = text('div', '', 'preview-meta')
1197
+ row.append(text('span', metadata[1]), text('code', metadata[2]))
1198
+ lead.append(row)
1199
+ } else if (line) lead.append(text('p', line, 'preview-context'))
1200
+ }
1201
+ const context = introLines.slice(2).join('\n').trim()
1202
+ if (context) lead.append(text('p', context, 'preview-context'))
1203
+ const content = sections.map(section => {
1204
+ const block = text('section', '', 'preview-section')
1205
+ block.append(text('h3', section.label))
1206
+ if (section.file) block.append(text('code', section.file, 'preview-source'))
1207
+ block.append(text('p', section.text.trim(), 'preview-body'))
1208
+ return block
1209
+ })
1210
+ dialogText.dataset.format = 'handoff'
1211
+ dialogText.replaceChildren(lead, ...content)
1212
+ if (footer) dialogText.append(text('p', footer, 'preview-context'))
1213
+ }
1214
+
1215
+ async function viewAsset(asset) {
1216
+ const project = current
1217
+ const epoch = showDialog('asset', materialName(asset), asset.file, '正在读取…', asset.kind)
1218
+ try {
1219
+ const result = await api('asset', { projectId: project.id, assetId: asset.id })
1220
+ if (!dialog.open || dialogEpoch !== epoch) return
1221
+ dialogText.textContent = result.text + (result.truncated ? '\n\n[预览已截取]' : '')
1222
+ } catch (error) {
1223
+ if (dialog.open && dialogEpoch === epoch) status(error.message, true, 'dialog-status')
1224
+ }
1225
+ }
1226
+
1227
+ async function preview() {
1228
+ const project = current
1229
+ if (!project || !detail || !filteredProjects().some(item => item.id === project.id)) return
1230
+ const note = project.online
1231
+ ? '可导出 Markdown,或在原工作目录打开 DSH 会话并继续编辑草稿。'
1232
+ : '原工作目录不可访问。可将现有交接资料导出为 Markdown。'
1233
+ const epoch = showDialog('handoff', `草稿预览 · ${project.name}`, note, '正在准备…')
1234
+ try {
1235
+ const result = await api('preview', { projectId: project.id, assetIds: [...selected], history: historyOption.checked })
1236
+ if (!dialog.open || dialogEpoch !== epoch) return
1237
+ ticket = result.ticket
1238
+ if (result.preview) renderHandoff(result.preview)
1239
+ else dialogText.textContent = result.prompt
1240
+ importButton.hidden = result.canImport === false || !project.online
1241
+ exportButton.hidden = false
1242
+ if (result.truncated) status('部分资料已截取。完整内容可在来源文件查看。', false, 'dialog-status')
1243
+ } catch (error) {
1244
+ if (dialog.open && dialogEpoch === epoch) status(error.message, true, 'dialog-status')
1245
+ }
1246
+ }
1247
+
1248
+ function requestParent(type, values, requestId = `bridge-${Date.now()}-${++requestNumber}`) {
1249
+ if (window.parent === window) {
1250
+ return Promise.reject(new Error('请在 DSH 侧栏打开 Agent 接续后使用此操作。'))
1251
+ }
1252
+ return new Promise((resolve, reject) => {
1253
+ const timer = setTimeout(() => {
1254
+ pending = undefined
1255
+ reject(new Error('DSH 暂未响应。请重试。'))
1256
+ }, 25_000)
1257
+ pending = { requestId, timer, resolve, reject }
1258
+ try {
1259
+ window.parent.postMessage({ type: `dsh-agent-bridge:${type}`, requestId, ...values }, parentOrigin)
1260
+ } catch (error) {
1261
+ clearTimeout(timer)
1262
+ pending = undefined
1263
+ reject(error)
1264
+ }
1265
+ })
1266
+ }
1267
+
1268
+ async function importSession() {
1269
+ if (!ticket || dialogBusy || importButton.hidden) return
1270
+ setDialogBusy(true)
1271
+ status(draftRecovery ? '正在重试填入草稿…' : '正在创建 DSH 会话…', false, 'dialog-status')
1272
+ try {
1273
+ const { path, prompt } = await api('open', { ticket })
1274
+ await requestParent('open', { path, prompt, bridgeNonce: nonce }, ticket)
1275
+ ticket = undefined
1276
+ dialog.close()
1277
+ status('DSH 会话已打开。交接草稿已填入输入框。')
1278
+ } catch (error) {
1279
+ if (Object.hasOwn(error, 'recoverySessionId')) draftRecovery = error.recoverySessionId
1280
+ recoverDraftButton.hidden = !draftRecovery
1281
+ status(error.message, true, 'dialog-status')
1282
+ } finally {
1283
+ setDialogBusy(false)
1284
+ }
1285
+ }
1286
+
1287
+ async function recoverDraftSession() {
1288
+ if (!ticket || !draftRecovery || dialogBusy) return
1289
+ setDialogBusy(true)
1290
+ try {
1291
+ await requestParent('recover-draft', { sessionId: draftRecovery }, ticket)
1292
+ dialog.close()
1293
+ } catch (error) {
1294
+ status(error.message, true, 'dialog-status')
1295
+ } finally {
1296
+ setDialogBusy(false)
1297
+ }
1298
+ }
1299
+
1300
+ function showDownload({ filename, markdown }) {
1301
+ if (typeof filename !== 'string' || typeof markdown !== 'string') throw new Error('未收到可导出的 Markdown。')
1302
+ clearDownload()
1303
+ byId('export-text').textContent = markdown
1304
+ byId('export-output').hidden = false
1305
+ try {
1306
+ downloadUrl = URL.createObjectURL(new Blob([markdown], { type: 'text/markdown;charset=utf-8' }))
1307
+ exportDownload.href = downloadUrl
1308
+ exportDownload.download = filename
1309
+ exportDownload.hidden = false
1310
+ exportDownload.click()
1311
+ status(`已生成 ${filename}。`, false, 'dialog-status')
1312
+ } catch {
1313
+ byId('export-output').open = true
1314
+ status(`已生成 ${filename}。可复制下方 Markdown。`, false, 'dialog-status')
1315
+ }
1316
+ }
1317
+
1318
+ function selectedNativeSession() {
1319
+ return nativeSessions.find(session => session.id === sessionSelect.value)
1320
+ }
1321
+
1322
+ function renderSessionPath() {
1323
+ const session = selectedNativeSession()
1324
+ byId('session-path').textContent = session?.path ?? ''
1325
+ }
1326
+
1327
+ async function chooseNativeSession() {
1328
+ showDialog('session', '导出 DSH 会话', '将会话中的用户与助手消息保存为 Markdown。', '正在读取 DSH 会话…')
1329
+ setDialogBusy(true)
1330
+ try {
1331
+ const result = await requestParent('sessions', {})
1332
+ nativeSessions = result.sessions
1333
+ if (!nativeSessions.length) {
1334
+ dialogText.textContent = '暂无可导出的 DSH 会话。'
1335
+ return
1336
+ }
1337
+ const titles = new Map()
1338
+ for (const { title } of nativeSessions) titles.set(title, (titles.get(title) ?? 0) + 1)
1339
+ sessionSelect.replaceChildren(...nativeSessions.map(session => {
1340
+ const title = session.title || '未命名会话'
1341
+ const suffix = titles.get(session.title) > 1 && session.path ? ` · ${shortPath(session.path)}` : ''
1342
+ return new Option(title + suffix, session.id)
1343
+ }))
1344
+ renderSessionPath()
1345
+ dialogText.hidden = true
1346
+ byId('session-choice').hidden = false
1347
+ exportButton.hidden = false
1348
+ } catch (error) {
1349
+ dialogText.hidden = true
1350
+ status(error.message, true, 'dialog-status')
1351
+ } finally {
1352
+ setDialogBusy(false)
1353
+ }
1354
+ }
1355
+
1356
+ async function exportMarkdown() {
1357
+ if (dialogBusy || exportButton.hidden) return
1358
+ setDialogBusy(true)
1359
+ status('正在生成 Markdown…', false, 'dialog-status')
1360
+ try {
1361
+ if (dialogMode === 'session') {
1362
+ const session = selectedNativeSession()
1363
+ if (!session) throw new Error('请选择要导出的 DSH 会话。')
1364
+ const result = await requestParent('session-export', { sessionId: session.id, path: session.path })
1365
+ showDownload(await api('export-session', { conversation: result.conversation }))
1366
+ } else if (ticket) {
1367
+ showDownload(await api('export', { ticket }))
1368
+ }
1369
+ } catch (error) {
1370
+ status(error.message, true, 'dialog-status')
1371
+ } finally {
1372
+ setDialogBusy(false)
1373
+ }
1374
+ }
1375
+
1376
+ async function copyProjectPath() {
1377
+ if (!current) return
1378
+ const button = byId('copy-path')
1379
+ try {
1380
+ await navigator.clipboard.writeText(current.cwd)
1381
+ button.dataset.state = 'copied'
1382
+ button.replaceChildren(icon('check'))
1383
+ button.setAttribute('aria-label', '已复制工作目录')
1384
+ setTimeout(() => {
1385
+ delete button.dataset.state
1386
+ button.replaceChildren(icon('copy'))
1387
+ button.setAttribute('aria-label', '复制工作目录')
1388
+ }, 1600)
1389
+ } catch {
1390
+ const selection = window.getSelection()
1391
+ if (!selection) return
1392
+ const range = document.createRange()
1393
+ range.selectNodeContents(byId('project-path'))
1394
+ selection.removeAllRanges()
1395
+ selection.addRange(range)
1396
+ status('已选中工作目录,按 Ctrl+C 或 ⌘C 复制。')
1397
+ }
1398
+ }
1399
+
1400
+ function wireClear(input, action) {
1401
+ input.parentElement.querySelector('.clear-search').addEventListener('click', () => {
1402
+ input.value = ''
1403
+ action()
1404
+ input.focus()
1405
+ })
1406
+ }
1407
+
1408
+ window.addEventListener('message', event => {
1409
+ if (event.source !== window.parent || (parentOrigin !== '*' && event.origin !== parentOrigin)) return
1410
+ const data = event.data
1411
+ if (!pending || data?.type !== 'dsh-agent-bridge:result' || pending.requestId !== data.requestId) return
1412
+ const request = pending
1413
+ pending = undefined
1414
+ clearTimeout(request.timer)
1415
+ if (data.ok) request.resolve(data)
1416
+ else request.reject(Object.assign(new Error(data.error || 'DSH 暂无法完成此操作。'), {
1417
+ recoverySessionId: typeof data.recoverySessionId === 'string' ? data.recoverySessionId : undefined,
1418
+ }))
1419
+ })
1420
+ refreshButton.addEventListener('click', () => refresh(true))
1421
+ projectSearch.addEventListener('input', event => {
1422
+ if (!event.isComposing) updateProjectSearch()
1423
+ })
1424
+ projectSearch.addEventListener('compositionend', updateProjectSearch)
1425
+ projectSearch.addEventListener('keydown', event => {
1426
+ if (event.isComposing || event.keyCode === 229 || !['ArrowDown', 'Enter'].includes(event.key)) return
1427
+ const first = projectList.querySelector('.project')
1428
+ if (!first) return
1429
+ event.preventDefault()
1430
+ first.focus()
1431
+ if (event.key === 'Enter') first.click()
1432
+ })
1433
+ agentFilter.addEventListener('click', () => {
1434
+ if (agentPopover.hidden) openAgentPicker()
1435
+ else closeAgentPicker(true)
1436
+ })
1437
+ agentFilter.addEventListener('keydown', event => {
1438
+ if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return
1439
+ event.preventDefault()
1440
+ openAgentPicker()
1441
+ })
1442
+ agentOptions.addEventListener('keydown', navigateAgents)
1443
+ agentOptions.addEventListener('pointermove', event => {
1444
+ const option = event.target.closest('.agent-option')
1445
+ if (option) activateAgentOption(availableAgents.indexOf(option.dataset.agent), false)
1446
+ })
1447
+ agentOptions.addEventListener('click', event => {
1448
+ const option = event.target.closest('.agent-option')
1449
+ if (option) chooseAgent(availableAgents.indexOf(option.dataset.agent))
1450
+ })
1451
+ document.addEventListener('pointerdown', event => {
1452
+ if (!agentPicker.contains(event.target)) closeAgentPicker()
1453
+ })
1454
+ document.addEventListener('focusin', event => {
1455
+ if (!agentPicker.contains(event.target)) closeAgentPicker()
1456
+ })
1457
+ window.addEventListener('resize', positionAgentPicker)
1458
+ window.addEventListener('scroll', positionAgentPicker, { passive: true })
1459
+ assetSearch.addEventListener('input', renderAssets)
1460
+ wireClear(projectSearch, updateProjectSearch)
1461
+ wireClear(assetSearch, renderAssets)
1462
+ draftWorkflow.addEventListener('toggle', renderAssets)
1463
+ globalLibrary.addEventListener('toggle', renderGlobalMaterials)
1464
+ projectManage.addEventListener('click', () => {
1465
+ managingProjects = !managingProjects
1466
+ selectedProjects.clear()
1467
+ renderProjects()
1468
+ })
1469
+ selectVisible.addEventListener('change', () => {
1470
+ selectedProjects.clear()
1471
+ if (selectVisible.checked) {
1472
+ for (const project of filteredProjects()) selectedProjects.add(project.id)
1473
+ }
1474
+ renderProjects()
1475
+ })
1476
+ bulkArchive.addEventListener('click', () => updateProjectArchive([...selectedProjects], projectState !== 'archived'))
1477
+ archiveAction.addEventListener('click', () => {
1478
+ if (current) void updateProjectArchive([current.id], !current.archived)
1479
+ })
1480
+ projectPin.addEventListener('click', toggleProjectPin)
1481
+ projectUndo.addEventListener('click', () => {
1482
+ if (undoArchive) void updateProjectArchive(undoArchive.projectIds, undoArchive.archived, true)
1483
+ })
1484
+ for (const button of projectFilters) {
1485
+ button.addEventListener('click', () => {
1486
+ projectState = button.dataset.projectState
1487
+ projectList.scrollTop = 0
1488
+ updateProjectView()
1489
+ })
1490
+ }
1491
+ document.addEventListener('keydown', event => {
1492
+ if (event.key !== '/' || event.ctrlKey || event.metaKey || event.altKey || dialog.open || !agentPopover.hidden
1493
+ || event.target.matches?.('input, select, textarea, [contenteditable]')) return
1494
+ event.preventDefault()
1495
+ projectSearch.focus()
1496
+ })
1497
+ projectList.addEventListener('keydown', event => {
1498
+ const buttons = [...projectList.querySelectorAll('.project')]
1499
+ const currentIndex = buttons.indexOf(event.target)
1500
+ if (currentIndex < 0) return
1501
+ let nextIndex
1502
+ if (event.key === 'ArrowDown') nextIndex = Math.min(buttons.length - 1, currentIndex + 1)
1503
+ if (event.key === 'ArrowUp') nextIndex = Math.max(0, currentIndex - 1)
1504
+ if (event.key === 'Home') nextIndex = 0
1505
+ if (event.key === 'End') nextIndex = buttons.length - 1
1506
+ if (nextIndex === undefined) return
1507
+ event.preventDefault()
1508
+ buttons[nextIndex].focus()
1509
+ })
1510
+ historyOption.addEventListener('change', () => {
1511
+ includeHistory = historyOption.checked
1512
+ renderSelection()
1513
+ void saveProjectSelection()
1514
+ })
1515
+ byId('copy-path').addEventListener('click', copyProjectPath)
1516
+ byId('preview').addEventListener('click', preview)
1517
+ byId('native-export').addEventListener('click', chooseNativeSession)
1518
+ browseHistory.addEventListener('click', chooseSourceConversation)
1519
+ byId('history-back-button').addEventListener('click', showHistoryResults)
1520
+ function searchHistory() {
1521
+ historyChosenId = undefined
1522
+ historyLimit = 30
1523
+ renderHistoryResults()
1524
+ }
1525
+ historySearch.addEventListener('input', searchHistory)
1526
+ wireClear(historySearch, searchHistory)
1527
+ byId('history-more').addEventListener('click', () => {
1528
+ const index = historyResults.childElementCount
1529
+ historyLimit += 30
1530
+ renderHistoryResults()
1531
+ historyResults.children[index]?.querySelector('button')?.focus()
1532
+ })
1533
+ historyImport.addEventListener('click', importSourceConversation)
1534
+ sessionSelect.addEventListener('change', clearDownload)
1535
+ sessionSelect.addEventListener('change', renderSessionPath)
1536
+ dialogClose.addEventListener('click', () => dialog.close())
1537
+ dialog.addEventListener('click', event => {
1538
+ if (event.target !== dialog || dialogBusy) return
1539
+ const bounds = dialog.getBoundingClientRect()
1540
+ if (event.clientX < bounds.left || event.clientX > bounds.right
1541
+ || event.clientY < bounds.top || event.clientY > bounds.bottom) dialog.close()
1542
+ })
1543
+ dialog.addEventListener('cancel', event => { if (dialogBusy) event.preventDefault() })
1544
+ dialog.addEventListener('close', () => {
1545
+ ++dialogEpoch
1546
+ clearDownload()
1547
+ liveState('正在恢复实时扫描')
1548
+ schedulePoll(0)
1549
+ })
1550
+ importButton.addEventListener('click', importSession)
1551
+ recoverDraftButton.addEventListener('click', recoverDraftSession)
1552
+ exportButton.addEventListener('click', exportMarkdown)
1553
+ document.addEventListener('visibilitychange', () => schedulePoll(0))
1554
+ for (const button of themeOptions) button.addEventListener('click', () => setTheme(button.dataset.themeChoice))
1555
+ let savedTheme
1556
+ try { savedTheme = localStorage.getItem(themeKey) } catch { /* Use the default theme. */ }
1557
+ setTheme(savedTheme, false)
1558
+ renderAgentPicker()
1559
+ void refresh(false).finally(() => schedulePoll(0))