@wwwfz/dsh-agent-bridge 0.8.3 → 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.
Files changed (40) hide show
  1. package/README.md +198 -194
  2. package/THIRD_PARTY_NOTICES.md +67 -0
  3. package/cordis.patch.yml +4 -4
  4. package/package.json +40 -40
  5. package/src/assets.js +405 -348
  6. package/src/catalog.js +906 -605
  7. package/src/client.js +623 -310
  8. package/src/config.js +88 -88
  9. package/src/export.js +241 -12
  10. package/src/index.js +160 -136
  11. package/src/project-archive.js +145 -145
  12. package/src/projects.js +1189 -980
  13. package/src/session-import.js +107 -93
  14. package/src/session-trace.js +121 -0
  15. package/src/skill-handoff.js +1327 -0
  16. package/src/skill-package.js +417 -0
  17. package/src/skill-provider.js +249 -0
  18. package/src/watch.js +309 -309
  19. package/web/Geist-OFL.txt +93 -93
  20. package/web/agent-icons/NOTICE.md +19 -19
  21. package/web/agent-icons/antigravity.svg +76 -76
  22. package/web/agent-icons/claude.svg +3 -3
  23. package/web/agent-icons/dsh.svg +58 -58
  24. package/web/agent-icons/licenses/copilot.txt +21 -21
  25. package/web/agent-icons/licenses/dsh.txt +21 -21
  26. package/web/agent-icons/licenses/gemini.txt +201 -201
  27. package/web/agent-icons/licenses/opencode.txt +21 -21
  28. package/web/agent-icons/licenses/qoder-notice.txt +18 -18
  29. package/web/agent-icons/licenses/qoder.txt +22 -22
  30. package/web/agent-icons/licenses/qwen.txt +202 -202
  31. package/web/agent-icons/qoder.svg +4 -4
  32. package/web/agent-icons/qwen.svg +5 -5
  33. package/web/agent-icons/workbuddy.svg +29 -29
  34. package/web/markdown.js +225 -0
  35. package/web/panel.css +607 -502
  36. package/web/panel.html +277 -246
  37. package/web/panel.js +2334 -1559
  38. package/web/project-context.js +25 -25
  39. package/web/vendor/markdown-it-LICENSE.txt +156 -0
  40. package/web/vendor/markdown-it.mjs +3064 -0
package/web/panel.js CHANGED
@@ -1,1559 +1,2334 @@
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))
1
+ import { describeProjectContext } from './project-context.js'
2
+ import { isMarkdownFile, renderMarkdown } from './markdown.js'
3
+
4
+ const byId = id => document.getElementById(id)
5
+ const nonce = document.querySelector('meta[name=bridge-nonce]').content
6
+ const dialog = byId('dialog')
7
+ const activateDialog = byId('activate-dialog')
8
+ const activateBody = byId('activate-body')
9
+ const activateStatus = byId('activate-status')
10
+ const activateConfirm = byId('activate-confirm')
11
+ const activateText = byId('activate-text')
12
+ const activateClose = byId('activate-close')
13
+ const importButton = byId('import')
14
+ const recoverDraftButton = byId('recover-draft')
15
+ const exportButton = byId('export')
16
+ const exportShareButton = byId('export-share')
17
+ const exportTraceOption = byId('export-trace-option')
18
+ const exportTrace = byId('export-trace')
19
+ const exportDownload = byId('export-download')
20
+ const skillUndo = byId('skill-undo')
21
+ const skillDeactivate = byId('skill-deactivate')
22
+ const skillApply = byId('skill-apply')
23
+ const dialogClose = byId('dialog-close')
24
+ const dialogText = byId('dialog-text')
25
+ const sessionSelect = byId('session-select')
26
+ const sessionSourceRecord = byId('session-source-record')
27
+ const historySearch = byId('history-search')
28
+ const historyResults = byId('history-results')
29
+ const historyImport = byId('history-import')
30
+ const refreshButton = byId('refresh')
31
+ const agentFilter = byId('agent-filter')
32
+ const agentPicker = byId('agent-picker')
33
+ const agentPopover = byId('agent-popover')
34
+ const agentOptions = byId('agent-options')
35
+ const themeOptions = [...document.querySelectorAll('[data-theme-choice]')]
36
+ const themeKey = 'dsh-agent-bridge.theme'
37
+ const projectSearch = byId('project-search')
38
+ const assetSearch = byId('asset-search')
39
+ const historyOption = byId('history')
40
+ const projectList = byId('project-list')
41
+ const projectManage = byId('project-manage')
42
+ const selectVisible = byId('project-select-visible')
43
+ const bulkArchive = byId('project-bulk-action')
44
+ const archiveAction = byId('project-archive-action')
45
+ const projectUndo = byId('project-undo')
46
+ const projectPin = byId('project-pin')
47
+ const draftWorkflow = byId('draft-workflow')
48
+ const projectMaterials = byId('project-materials')
49
+ const globalLibrary = byId('global-library')
50
+ const globalMaterials = byId('global-materials')
51
+ const queueList = byId('queue-list')
52
+ const recentList = byId('recent-conversations')
53
+ const recentStatus = byId('recent-status')
54
+ const browseHistory = byId('browse-history')
55
+ const projectFilters = [...document.querySelectorAll('[data-project-state]')]
56
+ const compactLayout = matchMedia('(max-width: 700px)')
57
+ const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)')
58
+ const parentOrigin = window.origin === 'null' ? '*' : window.origin
59
+ const agentNames = {
60
+ codex: 'Codex', claude: 'Claude Code', opencode: 'OpenCode', qoder: 'Qoder',
61
+ workbuddy: 'WorkBuddy', trae: 'TRAE', gemini: 'Gemini', antigravity: 'Antigravity',
62
+ copilot: 'Copilot', qwen: 'Qwen Code', dsh: 'DSH', workspacehub: '项目总账',
63
+ local: '手动目录', manual: '手动目录', export: '记忆导出', shared: '共享',
64
+ }
65
+ const agentInitials = { claude: 'CC', codex: 'CX', workbuddy: 'WB', trae: 'TR', antigravity: 'AG' }
66
+ const sourceStates = { ready: '可读取', partial: '部分可读', unavailable: '未找到', error: '读取失败' }
67
+ const materialGroups = [
68
+ ['progress', '上次做到哪', '交接记录、最新进度和待办。'],
69
+ ['guides', '项目约定', '开发规则、操作指引和偏好。'],
70
+ ['used', '会话中提及的 Skills', '在这个项目的近期对话中有记录。'],
71
+ ['notes', '其他项目笔记', '经验、决策和存档,可按需带入。'],
72
+ ['skills', '其他项目 Skills', '放在项目目录里,按任务选用。'],
73
+ ['managed', '已启用的项目 Skills', '来源不可再扫描时,私有快照仍可管理和停用。'],
74
+ ]
75
+ const globalGroups = [
76
+ ['guides', '通用指引'],
77
+ ['notes', '通用记忆'],
78
+ ['skills', '通用 Skills'],
79
+ ]
80
+ let catalog = []
81
+ let catalogLoaded = false
82
+ let agentIcons = {}
83
+ let availableAgents = ['']
84
+ let selectedAgent = ''
85
+ let projectQuery = ''
86
+ let activeAgentIndex = 0
87
+ let agentQuery = ''
88
+ let agentQueryAt = 0
89
+ let current
90
+ let detail
91
+ let context
92
+ let detailRevision = 0
93
+ let detailLoading = false
94
+ let projectState = 'all'
95
+ let archiveAvailable = false
96
+ let nativeSessionImport = false
97
+ let preferencesAvailable = false
98
+ let managingProjects = false
99
+ const selectedProjects = new Set()
100
+ const pinRequests = new Set()
101
+ const projectSelections = new Map()
102
+ const selectionSaves = new Map()
103
+ let archiveBusy = false
104
+ let undoArchive
105
+ let selected = new Set()
106
+ let includeHistory = false
107
+ let sourceRevision = null
108
+ let lastPinRevision = 0
109
+ let refreshing = false
110
+ let polling = false
111
+ let pollTimer
112
+ let ticket
113
+ let pending
114
+ let dialogMode
115
+ let dialogEpoch = 0
116
+ let dialogBusy = false
117
+ let nativeSessions = []
118
+ let sessionTraceRequest
119
+ let recentRevision = 0
120
+ let recentKey = ''
121
+ let historyProject
122
+ let historySessions
123
+ let historyLimit = 30
124
+ let historyChosenId
125
+ let historyTicket
126
+ let importedSessionId
127
+ let draftRecovery
128
+ let historyPreview = 0
129
+ let downloadUrl
130
+ let requestNumber = 0
131
+ let dialogSkillCandidates = []
132
+ let dialogSkillIds = new Set()
133
+ let skillPreviewTicket
134
+ let skillManagerAsset
135
+ let skillManagerProject
136
+ let previewInput
137
+ let activationReview
138
+ let activationSummary = ''
139
+ let exportHasTrace = false
140
+
141
+ const clockFormat = new Intl.DateTimeFormat('zh-CN', { timeStyle: 'medium', hourCycle: 'h23' })
142
+ const historyDateFormat = new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium', timeStyle: 'short' })
143
+ const recentDateFormat = new Intl.DateTimeFormat('zh-CN', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' })
144
+ const shortClock = new Intl.DateTimeFormat('zh-CN', { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' })
145
+
146
+ const agentName = value => Object.hasOwn(agentNames, value) ? agentNames[value] : String(value ?? '')
147
+ const text = (tag, content, className) => {
148
+ const element = document.createElement(tag)
149
+ element.textContent = content
150
+ if (className) element.className = className
151
+ return element
152
+ }
153
+
154
+ function renderProjectMarkdown(source, projectId, references = []) {
155
+ const links = new Map(references.map(reference => [reference.href, reference]))
156
+ return renderMarkdown(source, document, href => {
157
+ const reference = links.get(href)
158
+ if (!reference) return undefined
159
+ const container = text('span', '', 'md-reference')
160
+ const label = text('button', '', 'md-link md-reference-open')
161
+ label.type = 'button'
162
+ label.title = reference.path
163
+ label.addEventListener('click', () => {
164
+ if (reference.id) void openPath({ projectId, label: label.textContent, referenceId: reference.id })
165
+ else status(reference.error, true, 'dialog-status')
166
+ })
167
+ const copy = text('button', '', 'path-copy')
168
+ copy.type = 'button'
169
+ copy.append(icon('copy'))
170
+ copy.title = '复制链接路径'
171
+ copy.setAttribute('aria-label', `复制链接路径 ${reference.path}`)
172
+ copy.addEventListener('click', async () => {
173
+ try {
174
+ await navigator.clipboard.writeText(reference.path)
175
+ status('链接路径已复制。', false, 'dialog-status')
176
+ } catch {
177
+ const path = text('code', reference.path, 'preview-source')
178
+ const selection = window.getSelection()
179
+ status('请手动复制链接路径。', true, 'dialog-status')
180
+ byId('dialog-status').append(' ', path)
181
+ const range = document.createRange()
182
+ range.selectNodeContents(path)
183
+ selection?.removeAllRanges()
184
+ selection?.addRange(range)
185
+ }
186
+ })
187
+ container.append(label, copy)
188
+ return { container, label }
189
+ })
190
+ }
191
+
192
+ function markdownBody(source, className, projectId, references) {
193
+ const body = document.createElement('div')
194
+ body.className = className
195
+ body.dataset.format = 'markdown'
196
+ body.append(renderProjectMarkdown(source, projectId, references))
197
+ return body
198
+ }
199
+
200
+ function icon(name, className = '') {
201
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
202
+ svg.setAttribute('class', className ? `icon ${className}` : 'icon')
203
+ svg.setAttribute('aria-hidden', 'true')
204
+ const use = document.createElementNS(svg.namespaceURI, 'use')
205
+ use.setAttribute('href', `#icon-${name}`)
206
+ svg.append(use)
207
+ return svg
208
+ }
209
+
210
+ function agentMark(agent, label = agentName(agent)) {
211
+ const mark = text('span', '', 'agent-brand-mark')
212
+ mark.dataset.agent = agent
213
+ mark.setAttribute('aria-hidden', 'true')
214
+ const initial = () => {
215
+ mark.classList.remove('has-image')
216
+ mark.textContent = Object.hasOwn(agentInitials, agent) ? agentInitials[agent] : (Array.from(label)[0]?.toUpperCase() || '?')
217
+ }
218
+ const file = Object.hasOwn(agentIcons, agent) ? agentIcons[agent] : ''
219
+ if (!/^agent-icons\/[a-z][a-z0-9-]*\.(?:svg|png)$/.test(file)) {
220
+ initial()
221
+ return mark
222
+ }
223
+ const image = document.createElement('img')
224
+ image.alt = ''
225
+ image.decoding = 'async'
226
+ image.addEventListener('error', initial, { once: true })
227
+ image.src = `./${file}`
228
+ mark.classList.add('has-image')
229
+ mark.append(image)
230
+ return mark
231
+ }
232
+
233
+ function agentLabel(agent, className = '', label = agentName(agent)) {
234
+ const span = text('span', '', ['agent-label', className].filter(Boolean).join(' '))
235
+ span.append(agentMark(agent, label), text('span', label, 'agent-label-name'))
236
+ return span
237
+ }
238
+
239
+ function setTheme(value, remember = true) {
240
+ const theme = ['blue', 'white', 'black'].includes(value) ? value : 'blue'
241
+ document.documentElement.dataset.theme = theme
242
+ for (const button of themeOptions) {
243
+ button.setAttribute('aria-pressed', String(button.dataset.themeChoice === theme))
244
+ }
245
+ if (remember) {
246
+ try { localStorage.setItem(themeKey, theme) } catch { /* Theme is still applied to this panel. */ }
247
+ }
248
+ }
249
+
250
+ function renderAgentPicker(activeAgent = selectedAgent) {
251
+ const label = selectedAgent ? agentName(selectedAgent) : '全部 Agent'
252
+ byId('agent-trigger-mark').replaceChildren(selectedAgent ? agentMark(selectedAgent) : icon('filter'))
253
+ byId('agent-trigger-label').textContent = label
254
+ agentFilter.setAttribute('aria-label', `筛选 Agent,当前为${label}`)
255
+ agentOptions.replaceChildren(...availableAgents.map((agent, index) => {
256
+ const option = text('div', '', 'agent-option')
257
+ option.id = `agent-option-${index}`
258
+ option.dataset.agent = agent
259
+ option.setAttribute('role', 'option')
260
+ option.setAttribute('aria-selected', String(agent === selectedAgent))
261
+ option.append(agent ? agentMark(agent) : icon('layers', 'agent-option-mark'),
262
+ text('span', agent ? agentName(agent) : '全部 Agent', 'agent-option-label'), icon('check', 'agent-option-check'))
263
+ return option
264
+ }))
265
+ if (!agentPopover.hidden) {
266
+ positionAgentPicker()
267
+ activateAgentOption(availableAgents.indexOf(availableAgents.includes(activeAgent) ? activeAgent : selectedAgent))
268
+ }
269
+ }
270
+
271
+ function positionAgentPicker() {
272
+ if (agentPopover.hidden) return
273
+ const bounds = agentFilter.getBoundingClientRect()
274
+ const below = window.innerHeight - bounds.bottom
275
+ const above = bounds.top
276
+ agentPopover.dataset.placement = below < agentPopover.getBoundingClientRect().height + 6 && above > below ? 'above' : 'below'
277
+ }
278
+
279
+ function activateAgentOption(index, scroll = true) {
280
+ const previous = agentOptions.children[activeAgentIndex]
281
+ if (previous) delete previous.dataset.active
282
+ activeAgentIndex = Math.max(0, Math.min(index, availableAgents.length - 1))
283
+ const active = agentOptions.children[activeAgentIndex]
284
+ if (!active) return
285
+ active.dataset.active = 'true'
286
+ agentOptions.setAttribute('aria-activedescendant', active.id)
287
+ if (!scroll) return
288
+ const optionBounds = active.getBoundingClientRect()
289
+ const listBounds = agentOptions.getBoundingClientRect()
290
+ if (optionBounds.bottom > listBounds.bottom) agentOptions.scrollTop += optionBounds.bottom - listBounds.bottom
291
+ if (optionBounds.top < listBounds.top) agentOptions.scrollTop -= listBounds.top - optionBounds.top
292
+ }
293
+
294
+ function openAgentPicker() {
295
+ if (!agentPopover.hidden) return
296
+ agentPopover.hidden = false
297
+ agentFilter.setAttribute('aria-expanded', 'true')
298
+ agentQuery = ''
299
+ positionAgentPicker()
300
+ activateAgentOption(availableAgents.indexOf(selectedAgent))
301
+ agentOptions.focus({ preventScroll: true })
302
+ clearTimeout(pollTimer)
303
+ }
304
+
305
+ function closeAgentPicker(restoreFocus = false) {
306
+ if (agentPopover.hidden) return
307
+ agentPopover.hidden = true
308
+ agentOptions.removeAttribute('aria-activedescendant')
309
+ agentFilter.setAttribute('aria-expanded', 'false')
310
+ if (restoreFocus) agentFilter.focus({ preventScroll: true })
311
+ schedulePoll(0)
312
+ }
313
+
314
+ function chooseAgent(index) {
315
+ selectedAgent = availableAgents[index] ?? ''
316
+ closeAgentPicker(true)
317
+ renderAgentPicker()
318
+ projectList.scrollTop = 0
319
+ updateProjectView()
320
+ }
321
+
322
+ function navigateAgents(event) {
323
+ const { key } = event
324
+ if (key === 'Escape' || key === 'Tab') {
325
+ if (key === 'Escape') event.preventDefault()
326
+ closeAgentPicker(true)
327
+ return
328
+ }
329
+ if (key === 'Enter' || key === ' ') {
330
+ event.preventDefault()
331
+ chooseAgent(activeAgentIndex)
332
+ return
333
+ }
334
+ const destinations = { ArrowDown: activeAgentIndex + 1, ArrowUp: activeAgentIndex - 1,
335
+ Home: 0, End: availableAgents.length - 1 }
336
+ if (Object.hasOwn(destinations, key)) {
337
+ event.preventDefault()
338
+ activateAgentOption(destinations[key])
339
+ return
340
+ }
341
+ if (key.length !== 1 || event.ctrlKey || event.metaKey || event.altKey || event.isComposing) return
342
+ const now = Date.now()
343
+ agentQuery = (now - agentQueryAt < 650 ? agentQuery : '') + key.toLowerCase()
344
+ agentQueryAt = now
345
+ const match = availableAgents.findIndex(agent => agentName(agent).toLowerCase().startsWith(agentQuery))
346
+ if (match > 0) {
347
+ event.preventDefault()
348
+ activateAgentOption(match)
349
+ }
350
+ }
351
+
352
+ function shortPath(value) {
353
+ const separator = value.includes('\\') ? '\\' : '/'
354
+ const parts = value.split(/[\\/]+/).filter(Boolean)
355
+ return parts.length <= 3 ? value : `…${separator}${parts.slice(-2).join(separator)}`
356
+ }
357
+
358
+ function syncSearch(input) {
359
+ const clear = input.parentElement.querySelector('.clear-search')
360
+ const hint = input.parentElement.querySelector('.key-hint')
361
+ clear.hidden = !input.value
362
+ if (hint) hint.hidden = Boolean(input.value)
363
+ }
364
+
365
+ async function api(action, values = {}, { keepalive = false } = {}) {
366
+ const response = await fetch('./api', {
367
+ method: 'POST',
368
+ headers: { 'Content-Type': 'application/json', 'X-DSH-Agent-Bridge': nonce },
369
+ body: JSON.stringify({ action, ...values }),
370
+ keepalive,
371
+ })
372
+ const data = await response.json().catch(() => null)
373
+ if (!response.ok || !data) throw new Error(data?.error || '无法连接 DSH 插件。')
374
+ return data
375
+ }
376
+
377
+ function status(message, error = false, target = 'status') {
378
+ const element = byId(target)
379
+ element.textContent = message
380
+ element.classList.toggle('error', error)
381
+ }
382
+
383
+ function renderSources(sources) {
384
+ byId('sources-heading').textContent = `本机来源 · ${sources.length}`
385
+ byId('sources-list').replaceChildren(...sources.map(source => {
386
+ const row = document.createElement('div')
387
+ row.className = 'source-row'
388
+ const state = text('span', sourceStates[source.status] ?? source.status, 'chip source-state')
389
+ state.dataset.state = source.status
390
+ const name = text('strong', '', 'source-name')
391
+ name.append(agentLabel(source.id, '', source.label))
392
+ row.append(name, state)
393
+ if (source.detail) row.append(text('span', source.detail, 'source-detail'))
394
+ return row
395
+ }))
396
+ }
397
+
398
+ function projectMatches() {
399
+ return catalog.filter(project => (!selectedAgent || project.agents.includes(selectedAgent))
400
+ && [project.name, project.cwd, ...project.projectIds, ...project.agents.map(agentName)]
401
+ .some(value => value.toLowerCase().includes(projectQuery)))
402
+ }
403
+
404
+ function filteredProjects(matches = projectMatches()) {
405
+ if (projectState === 'archived') return matches.filter(project => project.archived)
406
+ return matches.filter(project => !project.archived && (projectState === 'all' || project.online === (projectState === 'online')))
407
+ }
408
+
409
+ function projectGroups(matches) {
410
+ if (!preferencesAvailable || projectState === 'archived') return [['', matches]]
411
+ const pinned = matches.filter(project => project.pinned)
412
+ const recent = matches.filter(project => !project.pinned && project.continuedAt != null)
413
+ .sort((a, b) => b.continuedAt - a.continuedAt).slice(0, 5)
414
+ if (!pinned.length && !recent.length) return [['', matches]]
415
+ const featured = new Set([...pinned, ...recent].map(project => project.id))
416
+ return [['置顶', pinned], ['最近接续', recent], ['其他项目', matches.filter(project => !featured.has(project.id))]]
417
+ }
418
+
419
+ function renderPin() {
420
+ const pinned = Boolean(current?.pinned)
421
+ projectPin.hidden = !preferencesAvailable || !current || current.archived
422
+ projectPin.disabled = !detail || pinRequests.has(current?.id)
423
+ projectPin.setAttribute('aria-pressed', String(pinned))
424
+ byId('project-pin-label').textContent = pinned ? '取消置顶' : '置顶'
425
+ byId('project-pin-icon').setAttribute('href', pinned ? '#icon-unpin' : '#icon-pin')
426
+ }
427
+
428
+ async function toggleProjectPin() {
429
+ if (!preferencesAvailable || !current || current.archived || !detail) return
430
+ const projectId = current.id
431
+ if (pinRequests.has(projectId)) return
432
+ const pinned = !current.pinned
433
+ pinRequests.add(projectId)
434
+ renderPin()
435
+ try {
436
+ const result = await api('set-project-pin', { projectId, pinned })
437
+ lastPinRevision = Math.max(lastPinRevision, result.revision)
438
+ const project = catalog.find(item => item.id === projectId)
439
+ if (project) project.pinned = pinned
440
+ if (current?.id === projectId) current.pinned = pinned
441
+ status('')
442
+ renderProjects()
443
+ } catch (error) {
444
+ status(error.message, true)
445
+ } finally {
446
+ pinRequests.delete(projectId)
447
+ renderPin()
448
+ schedulePoll(0)
449
+ }
450
+ }
451
+
452
+ function renderArchiveControls(matches) {
453
+ const visibleIds = new Set(matches.map(project => project.id))
454
+ for (const id of selectedProjects) {
455
+ if (!visibleIds.has(id)) selectedProjects.delete(id)
456
+ }
457
+ const size = selectedProjects.size
458
+ const action = projectState === 'archived' ? '恢复所选' : '归档所选'
459
+ projectManage.setAttribute('aria-pressed', String(managingProjects))
460
+ projectManage.hidden = !archiveAvailable
461
+ projectManage.disabled = archiveBusy || catalog.length === 0
462
+ byId('project-bulk').hidden = !managingProjects
463
+ selectVisible.checked = size > 0 && size === matches.length
464
+ selectVisible.indeterminate = size > 0 && size < matches.length
465
+ selectVisible.disabled = archiveBusy || matches.length === 0
466
+ bulkArchive.textContent = size ? `${action} · ${size}` : action
467
+ bulkArchive.disabled = archiveBusy || size === 0
468
+ projectUndo.disabled = archiveBusy
469
+ archiveAction.hidden = !archiveAvailable
470
+ archiveAction.disabled = archiveBusy || detailLoading || !current
471
+ }
472
+
473
+ function projectRow(project, matches) {
474
+ const button = document.createElement('button')
475
+ button.type = 'button'
476
+ button.className = 'project'
477
+ button.id = `project-${project.id}`
478
+ button.setAttribute('aria-pressed', String(current?.id === project.id))
479
+ button.title = project.cwd
480
+ const mark = text('span', '', 'project-icon')
481
+ mark.dataset.agent = project.agents[0] || 'local'
482
+ mark.append(icon('folder'))
483
+ const main = text('span', '', 'project-main')
484
+ main.append(text('span', project.name, 'project-title'), text('span', shortPath(project.cwd), 'project-path'))
485
+ const source = text('span', '', 'project-source')
486
+ for (const agent of project.agents.slice(0, 2)) source.append(agentLabel(agent))
487
+ if (project.agents.length > 2) {
488
+ const rest = text('span', `+${project.agents.length - 2}`, 'project-more-agents')
489
+ rest.title = project.agents.slice(2).map(agentName).join('、')
490
+ source.append(rest)
491
+ }
492
+ if (!project.agents.length) source.textContent = '本地项目'
493
+ const indicator = text('span', '', 'project-state')
494
+ indicator.dataset.state = project.online ? 'online' : 'offline'
495
+ indicator.setAttribute('aria-label', project.online ? '原目录可用' : '原目录不可访问')
496
+ main.append(source)
497
+ button.append(mark, main, indicator)
498
+ button.addEventListener('click', () => selectProject(project, true))
499
+ if (!managingProjects) return button
500
+ const row = text('div', '', 'project-row')
501
+ const check = document.createElement('input')
502
+ check.id = `check-project-${project.id}`
503
+ check.className = 'project-check'
504
+ check.type = 'checkbox'
505
+ check.checked = selectedProjects.has(project.id)
506
+ check.disabled = archiveBusy
507
+ check.setAttribute('aria-label', `选择 ${project.name}`)
508
+ check.addEventListener('change', () => {
509
+ if (check.checked) selectedProjects.add(project.id)
510
+ else selectedProjects.delete(project.id)
511
+ renderArchiveControls(matches)
512
+ })
513
+ row.append(check, button)
514
+ return row
515
+ }
516
+
517
+ function renderProjects() {
518
+ syncSearch(projectSearch)
519
+ const base = projectMatches()
520
+ const matches = filteredProjects(base)
521
+ const active = base.filter(project => !project.archived)
522
+ const online = active.filter(project => project.online).length
523
+ const counts = { all: active.length, online, offline: active.length - online, archived: base.length - active.length }
524
+ const labels = { all: '未归档', online: '可接续', offline: '离线', archived: '已归档' }
525
+ for (const button of projectFilters) {
526
+ const state = button.dataset.projectState
527
+ button.hidden = state === 'archived' && !archiveAvailable
528
+ button.setAttribute('aria-pressed', String(projectState === state))
529
+ button.replaceChildren(document.createTextNode(labels[state]), text('span', counts[state], 'filter-count'))
530
+ }
531
+ const total = catalog.filter(project => Boolean(project.archived) === (projectState === 'archived')).length
532
+ byId('project-count').textContent = matches.length === total ? `${total} 项` : `${matches.length} / ${total}`
533
+ renderArchiveControls(matches)
534
+ const items = []
535
+ for (const [label, group] of projectGroups(matches)) {
536
+ if (!group.length) continue
537
+ if (label) items.push(text('h3', label, 'project-group-heading'))
538
+ for (const project of group) items.push(projectRow(project, matches))
539
+ }
540
+ const focused = projectList.contains(document.activeElement) ? document.activeElement.id : ''
541
+ const scroll = projectList.scrollTop
542
+ const emptyMessage = projectState === 'archived' ? '没有匹配的归档项目。' : '没有匹配的项目。'
543
+ projectList.replaceChildren(...(items.length ? items : [text('p', emptyMessage, 'asset-empty')]))
544
+ projectList.scrollTop = scroll
545
+ if (focused) byId(focused)?.focus({ preventScroll: true })
546
+ }
547
+
548
+ function archiveFeedback(message, error = false) {
549
+ const feedback = byId('project-feedback')
550
+ feedback.hidden = !message
551
+ feedback.classList.toggle('error', error)
552
+ byId('project-feedback-text').textContent = message
553
+ projectUndo.hidden = !undoArchive
554
+ }
555
+
556
+ function emptyProjectDetail(message) {
557
+ current = undefined
558
+ detail = undefined
559
+ context = undefined
560
+ detailLoading = false
561
+ ++detailRevision
562
+ byId('empty').textContent = message
563
+ byId('empty').hidden = false
564
+ byId('project-detail').hidden = true
565
+ byId('preview').disabled = true
566
+ }
567
+
568
+ function reconcileProject(matches, selectFirst = false) {
569
+ if (current && matches.some(project => project.id === current.id)) return
570
+ if (selectFirst && matches.length) {
571
+ const [, firstGroup] = projectGroups(matches).find(([, group]) => group.length)
572
+ void selectProject(firstGroup[0])
573
+ } else if (matches.length) emptyProjectDetail('从项目列表选择要接续的项目。')
574
+ else if (catalog.length) emptyProjectDetail('当前筛选下没有项目。')
575
+ else if (catalogLoaded) emptyProjectDetail('未找到可浏览的项目。请展开本机来源查看读取状态。')
576
+ }
577
+
578
+ function updateProjectView() {
579
+ reconcileProject(filteredProjects())
580
+ renderProjects()
581
+ }
582
+
583
+ function updateProjectSearch() {
584
+ projectQuery = projectSearch.value.trim().toLowerCase()
585
+ updateProjectView()
586
+ }
587
+
588
+ async function updateProjectArchive(projectIds, archived, undo = false) {
589
+ if (!projectIds.length || archiveBusy) return
590
+ if (refreshing) {
591
+ archiveFeedback('正在刷新项目,请稍后重试。', true)
592
+ return
593
+ }
594
+ const origin = document.activeElement
595
+ archiveBusy = true
596
+ renderProjects()
597
+ try {
598
+ const result = await api('set-project-archive', { projectIds, archived })
599
+ const updated = new Set(result.projectIds)
600
+ for (const project of catalog) {
601
+ if (updated.has(project.id)) project.archived = archived
602
+ }
603
+ if (updated.has(current?.id)) current.archived = archived
604
+ reconcileProject(filteredProjects(), true)
605
+ selectedProjects.clear()
606
+ const changed = result.changedProjectIds
607
+ undoArchive = !undo && changed.length ? { projectIds: changed, archived: !archived } : undefined
608
+ archiveFeedback(changed.length ? `已${archived ? '归档' : '恢复'} ${changed.length} 个项目` : '项目已处于所选状态。')
609
+ } catch (error) {
610
+ archiveFeedback(error.message, true)
611
+ } finally {
612
+ archiveBusy = false
613
+ renderProjects()
614
+ if (document.activeElement === document.body && [archiveAction, bulkArchive, projectUndo].includes(origin)) {
615
+ if (origin === bulkArchive && !selectVisible.disabled) selectVisible.focus({ preventScroll: true })
616
+ else projectFilters.find(button => button.dataset.projectState === projectState)?.focus({ preventScroll: true })
617
+ }
618
+ schedulePoll(0)
619
+ }
620
+ }
621
+
622
+ function renderSelection() {
623
+ if (!context) return
624
+ const entries = context.entries.filter(item => selected.has(item.id))
625
+ const skillCount = entries.filter(item => item.kind === 'skill').length
626
+ const memoryCount = entries.length - skillCount
627
+ const parts = [memoryCount ? `${memoryCount} 份记忆` : '', skillCount ? `${skillCount} 个 Skills` : ''].filter(Boolean)
628
+ const summary = parts.join('、') || '未选资料'
629
+ byId('selection-summary').textContent = `接续清单 · ${summary}${historyOption.checked ? ' + 摘录' : ''}`
630
+ const globalCount = entries.filter(item => item.global).length
631
+ byId('selection-global').textContent = `${globalCount} 项全局`
632
+ byId('selection-global').hidden = globalCount === 0
633
+ renderGlobalCount()
634
+ const focused = queueList.contains(document.activeElement) ? document.activeElement.id : ''
635
+ const scroll = queueList.scrollTop
636
+ queueList.replaceChildren(...(entries.length ? entries.map(item => {
637
+ const row = text('div', '', 'queue-item')
638
+ const title = materialName(item)
639
+ const name = text('span', title, 'queue-title')
640
+ name.title = title
641
+ const kindLabel = text('span', `${item.global ? '全局 ' : ''}${item.kind === 'memory' ? '记忆' : 'Skill'}`, 'queue-kind')
642
+ const remove = text('button', '', 'queue-remove icon-button')
643
+ remove.type = 'button'
644
+ remove.id = `queue-remove-${item.id}`
645
+ remove.setAttribute('aria-label', `移除 ${title}`)
646
+ remove.append(icon('close'))
647
+ remove.addEventListener('click', () => {
648
+ const next = row.nextElementSibling ?? row.previousElementSibling
649
+ const focusId = next?.querySelector('.queue-remove')?.id
650
+ selected.delete(item.id)
651
+ void saveProjectSelection()
652
+ renderAssets()
653
+ const focusTarget = byId(focusId) ?? byId('handoff').querySelector('summary')
654
+ focusTarget.focus({ preventScroll: true })
655
+ })
656
+ row.append(icon(item.kind, 'queue-icon'), name, kindLabel, remove)
657
+ return row
658
+ }) : [text('p', '尚未选择记忆或 Skills。', 'queue-empty')]))
659
+ queueList.scrollTop = scroll
660
+ if (focused) byId(focused)?.focus({ preventScroll: true })
661
+ }
662
+
663
+ function saveProjectSelection() {
664
+ if (!current || !detail) return
665
+ const projectId = current.id
666
+ projectSelections.set(projectId, { assetIds: [...selected], history: includeHistory })
667
+ if (!preferencesAvailable || selectionSaves.has(projectId)) return
668
+ selectionSaves.set(projectId, flushProjectSelection(projectId))
669
+ }
670
+
671
+ async function flushProjectSelection(projectId) {
672
+ try {
673
+ while (projectSelections.has(projectId)) {
674
+ const selection = projectSelections.get(projectId)
675
+ try {
676
+ await api('set-project-selection', { projectId, ...selection }, { keepalive: true })
677
+ if (projectSelections.get(projectId) === selection) projectSelections.delete(projectId)
678
+ } catch (error) {
679
+ if (projectSelections.get(projectId) !== selection) continue
680
+ if (current?.id === projectId) status(`勾选已保留在当前面板。${error.message}`, true)
681
+ return
682
+ }
683
+ }
684
+ } finally {
685
+ selectionSaves.delete(projectId)
686
+ }
687
+ }
688
+
689
+ function materialName(asset) {
690
+ if (asset.kind === 'skill') return asset.name
691
+ if (/^memory[-_]summary$/i.test(asset.name)) return '记忆摘要'
692
+ if (/^memory$/i.test(asset.name)) return asset.global ? '长期记忆' : '项目记忆'
693
+ if (asset.group === 'guides' && /^(?:AGENTS|CLAUDE|GEMINI|QWEN|USER|SOUL)$/i.test(asset.name)) {
694
+ const label = asset.agent === 'shared' ? '' : `${agentName(asset.agent)} `
695
+ return label + (asset.global ? '全局指引' : '项目指引')
696
+ }
697
+ if (/^current[- _]state$/i.test(asset.name)) return '当前状态'
698
+ if (/^latest[- _]handoff$/i.test(asset.name)) return '最新交接'
699
+ return asset.name
700
+ }
701
+
702
+ function matchesMaterial(asset, query) {
703
+ return [materialName(asset), asset.name, agentName(asset.agent), asset.file, asset.detail]
704
+ .some(value => value?.toLowerCase().includes(query))
705
+ }
706
+
707
+ function actionableSkill(candidate) {
708
+ return Boolean(candidate?.allowed && ['enable', 'update', 'reuse-native'].includes(candidate.action))
709
+ }
710
+
711
+ function skillStatusNode(status) {
712
+ const node = text('span', status?.label || '仅可带入说明', 'skill-status')
713
+ node.dataset.state = status?.state || 'handoff'
714
+ node.title = status?.detail || status?.reason || ''
715
+ return node
716
+ }
717
+
718
+ function syncSkillChoiceButtons() {
719
+ const count = dialogSkillIds.size
720
+ if (historyImport.hidden === false) {
721
+ byId('history-import-label').textContent = importedSessionId
722
+ ? '打开已迁入会话'
723
+ : count ? `启用 ${count} 项并继续` : '迁入并继续'
724
+ }
725
+ if (importButton.hidden === false) {
726
+ importButton.replaceChildren(
727
+ document.createTextNode(count ? '启用并继续' : '打开新对话'),
728
+ icon('arrow'),
729
+ )
730
+ }
731
+ }
732
+
733
+ function renderSkillChoices(candidates, { history = false } = {}) {
734
+ dialogSkillCandidates = Array.isArray(candidates) ? candidates : []
735
+ dialogSkillIds = new Set()
736
+ if (!dialogSkillCandidates.length) return null
737
+ const panel = text('section', '', 'skill-choice-panel')
738
+ panel.setAttribute('aria-label', '沿用技能(可选)')
739
+ const heading = text('div', '', 'skill-choice-heading')
740
+ heading.append(
741
+ text('strong', '沿用技能(可选)'),
742
+ text('span', history ? '从历史记录匹配到本机技能;不会自动选择。' : '选中后由 DSH 原生技能目录调用。'),
743
+ )
744
+ const list = text('div', '', 'skill-choice-list')
745
+ for (const candidate of dialogSkillCandidates) {
746
+ const label = text('label', '', 'skill-choice')
747
+ const checkbox = document.createElement('input')
748
+ checkbox.type = 'checkbox'
749
+ checkbox.disabled = !actionableSkill(candidate)
750
+ checkbox.setAttribute('aria-label', `${candidate.name || candidate.dshName || '技能'}:${candidate.label}`)
751
+ checkbox.addEventListener('change', () => {
752
+ if (checkbox.checked) dialogSkillIds.add(candidate.assetId)
753
+ else dialogSkillIds.delete(candidate.assetId)
754
+ label.classList.toggle('selected', checkbox.checked)
755
+ syncSkillChoiceButtons()
756
+ })
757
+ const detail = text('span', '', 'skill-choice-text')
758
+ detail.append(
759
+ text('span', candidate.name || candidate.dshName || '技能', 'skill-choice-name'),
760
+ text('span', [candidate.label, candidate.detail || candidate.reason].filter(Boolean).join(' · '), 'skill-choice-note'),
761
+ )
762
+ label.append(checkbox, detail)
763
+ list.append(label)
764
+ }
765
+ panel.append(heading, list)
766
+ syncSkillChoiceButtons()
767
+ return panel
768
+ }
769
+
770
+ function renderGlobalCount() {
771
+ const assets = context.entries.filter(asset => asset.global)
772
+ const query = assetSearch.value.trim().toLowerCase()
773
+ const count = query ? assets.filter(asset => matchesMaterial(asset, query)).length : assets.length
774
+ const checked = assets.filter(asset => selected.has(asset.id)).length
775
+ globalLibrary.hidden = assets.length === 0
776
+ byId('global-count').textContent = `${count} ${query ? '项匹配' : '项'}${checked ? ` · ${checked} 已选` : ''}`
777
+ }
778
+
779
+ function makeMaterialRow(asset) {
780
+ const name = materialName(asset)
781
+ const row = text('div', '', 'asset-row')
782
+ const checkbox = document.createElement('input')
783
+ checkbox.type = 'checkbox'
784
+ checkbox.className = 'asset-check'
785
+ checkbox.id = `asset-${asset.id}`
786
+ checkbox.checked = selected.has(asset.id)
787
+ checkbox.disabled = Boolean(asset.managedOnly)
788
+ row.dataset.selected = String(checkbox.checked)
789
+ checkbox.addEventListener('change', () => {
790
+ if (checkbox.checked && selected.size >= 24) {
791
+ checkbox.checked = false
792
+ status('每次最多选择 24 项资料。', true, 'selection-feedback')
793
+ return
794
+ }
795
+ if (checkbox.checked) selected.add(asset.id)
796
+ else selected.delete(asset.id)
797
+ row.dataset.selected = String(checkbox.checked)
798
+ status('', false, 'selection-feedback')
799
+ renderSelection()
800
+ void saveProjectSelection()
801
+ })
802
+ const label = text('label', '', 'asset-label')
803
+ label.htmlFor = checkbox.id
804
+ label.title = name === asset.name ? asset.file : `${asset.name}\n${asset.file}`
805
+ const title = text('span', name, 'asset-title')
806
+ const meta = text('span', '', 'asset-meta')
807
+ if (asset.agent) meta.append(agentLabel(asset.agent))
808
+ if (asset.kind === 'skill' && asset.handoff) {
809
+ meta.append(skillStatusNode(asset.handoff))
810
+ const note = asset.handoff.reason || (asset.handoff.sourceChanged
811
+ || asset.handoff.state === 'pending' || asset.handoff.manualOnly ? asset.handoff.detail : '')
812
+ if (note) meta.append(text('span', note, 'asset-status-note'))
813
+ }
814
+ if (!asset.global && context.suggestedIds.includes(asset.id)) {
815
+ meta.append(text('span', '建议带入', 'material-suggestion'))
816
+ } else if (asset.global && asset.used) {
817
+ meta.append(text('span', '近期会话提及', 'material-suggestion'))
818
+ }
819
+ label.append(title, meta)
820
+ const button = text('button', '', 'asset-view')
821
+ const manageable = asset.kind === 'skill' && asset.handoff
822
+ && detail?.skillNativeAvailable && (asset.managedOnly || asset.handoff.state !== 'native')
823
+ const action = asset.handoff?.action
824
+ const actionLabel = !manageable ? '查看'
825
+ : asset.managedOnly || asset.handoff?.state === 'active' ? '管理'
826
+ : action === 'enable' ? '启用'
827
+ : action === 'preview-update' ? '更新'
828
+ : '详情'
829
+ button.append(document.createTextNode(actionLabel), icon('chevron'))
830
+ button.type = 'button'
831
+ button.id = `asset-view-${asset.id}`
832
+ button.setAttribute('aria-label', `${actionLabel} ${name}`)
833
+ button.addEventListener('click', () => {
834
+ if (!manageable) viewAsset(asset)
835
+ else if (asset.managedOnly) openManagedSkill(asset)
836
+ else openSkillManager(asset)
837
+ })
838
+ const marker = text('span', '', 'asset-icon')
839
+ marker.append(icon(asset.kind))
840
+ row.append(checkbox, marker, label)
841
+ // Global library entries are outside the selected project's asset list, so
842
+ // the Host cannot re-verify them for this project. Only project assets get
843
+ // an open action; every row keeps its checkbox and detail button.
844
+ if (!asset.global) {
845
+ const open = text('button', '', 'asset-open')
846
+ open.type = 'button'
847
+ open.append(icon('folder'))
848
+ open.id = `asset-open-${asset.id}`
849
+ open.setAttribute('aria-label', `在 DSH 中打开 ${name}`)
850
+ open.title = '在 DSH 中打开'
851
+ open.addEventListener('click', () => { void openPath({ label: name, assetId: asset.id }) })
852
+ row.append(open)
853
+ }
854
+ row.append(button)
855
+ return row
856
+ }
857
+
858
+ function fillMaterials(target, groups, assets, emptyMessage) {
859
+ const scroll = target.scrollTop
860
+ const focused = target.contains(document.activeElement) ? document.activeElement.id : ''
861
+ const sections = groups.flatMap(([key, title, note]) => {
862
+ const members = assets.filter(item => item.group === key)
863
+ if (!members.length) return []
864
+ const group = text('section', '', 'asset-group')
865
+ const heading = text('h4', title, 'asset-group-heading')
866
+ heading.append(text('span', String(members.length), 'disclosure-count'))
867
+ group.append(heading)
868
+ if (note) group.append(text('p', note, 'asset-group-note'))
869
+ group.append(...members.map(makeMaterialRow))
870
+ return [group]
871
+ })
872
+ target.replaceChildren(...(sections.length ? sections : [text('p', emptyMessage, 'asset-empty')]))
873
+ target.scrollTop = scroll
874
+ if (focused) byId(focused)?.focus({ preventScroll: true })
875
+ }
876
+
877
+ function renderGlobalMaterials() {
878
+ if (!context || !globalLibrary.open) return
879
+ const query = assetSearch.value.trim().toLowerCase()
880
+ fillMaterials(globalMaterials, globalGroups, context.entries.filter(item => item.global && matchesMaterial(item, query)), '没有匹配的全局资料。')
881
+ }
882
+
883
+ function renderAssets() {
884
+ if (!context || !draftWorkflow.open) return
885
+ const query = assetSearch.value.trim().toLowerCase()
886
+ syncSearch(assetSearch)
887
+ fillMaterials(projectMaterials, materialGroups, context.entries.filter(item => !item.global && matchesMaterial(item, query)),
888
+ query ? '没有匹配的项目资料。' : '没有找到项目专用资料。你也可以直接预览草稿。')
889
+ renderGlobalMaterials()
890
+ renderSelection()
891
+ }
892
+
893
+ function applyDetail(project, loaded, preserve) {
894
+ showProject(loaded.project ?? project)
895
+ const existingSkillIds = new Set(loaded.skills.map(skill => skill.id))
896
+ const managedOnly = (loaded.managedSkills ?? [])
897
+ .filter(item => !existingSkillIds.has(item.assetId))
898
+ .map(item => ({
899
+ id: item.assetId,
900
+ name: item.sourceName || item.dshName,
901
+ agent: 'dsh',
902
+ scope: 'project',
903
+ detail: 'Bridge 启用项',
904
+ file: item.sourceFile,
905
+ used: false,
906
+ managedOnly: true,
907
+ handoff: {
908
+ label: item.label,
909
+ state: item.state,
910
+ action: 'manage',
911
+ allowed: true,
912
+ current: item.state === 'active',
913
+ sourceChanged: item.sourceChanged,
914
+ sourceState: item.sourceState,
915
+ activationId: item.activationId,
916
+ dshName: item.dshName,
917
+ canUndo: item.canUndo,
918
+ registered: true,
919
+ discovered: item.discovered,
920
+ verified: item.verified,
921
+ invocation: item.invocation,
922
+ modelInvocable: item.modelInvocable,
923
+ userInvocable: item.userInvocable,
924
+ manualOnly: item.manualOnly,
925
+ disabled: item.disabled,
926
+ canOmitBody: item.canOmitBody,
927
+ detail: item.detail,
928
+ reason: item.detail,
929
+ },
930
+ }))
931
+ if (managedOnly.length) loaded = { ...loaded, skills: [...loaded.skills, ...managedOnly] }
932
+ detail = loaded
933
+ context = describeProjectContext(loaded)
934
+ for (const entry of context.entries) {
935
+ if (entry.managedOnly) entry.group = 'managed'
936
+ }
937
+ if (!preserve) {
938
+ const saved = projectSelections.get(project.id) ?? loaded.selection
939
+ if (saved) {
940
+ selected = new Set(saved.assetIds)
941
+ includeHistory = saved.history
942
+ } else {
943
+ selected = new Set(context.suggestedIds)
944
+ includeHistory = false
945
+ }
946
+ }
947
+ const available = new Set(context.entries.filter(item => !item.managedOnly).map(item => item.id))
948
+ selected = new Set([...selected].filter(id => available.has(id)))
949
+ historyOption.checked = includeHistory && detail.historyCount > 0
950
+ historyOption.disabled = detail.historyCount === 0
951
+ byId('history-option').hidden = detail.historyCount === 0
952
+ byId('history-label').textContent = `带入近期对话摘录(最多 ${Math.min(8, detail.historyCount)} 条消息)`
953
+ byId('preview').disabled = false
954
+ assetSearch.disabled = false
955
+ renderAssets()
956
+ }
957
+
958
+ function showProject(project) {
959
+ const latest = catalog.find(item => item.id === project.id) ?? project
960
+ current = { ...project, archived: Boolean(latest.archived), pinned: Boolean(latest.pinned) }
961
+ byId('project-name').textContent = current.name
962
+ byId('project-path').textContent = current.cwd
963
+ byId('project-path').title = current.cwd
964
+ const availability = text('span', current.online ? '原目录可用' : '原目录不可访问', 'chip availability')
965
+ availability.dataset.state = current.online ? 'online' : 'offline'
966
+ byId('project-meta').replaceChildren(...current.projectIds.map(value => text('span', value, 'chip')),
967
+ ...current.agents.map(agent => agentLabel(agent, 'chip')), availability)
968
+ if (current.archived) {
969
+ const archived = text('span', '已归档', 'chip')
970
+ archived.dataset.state = 'archived'
971
+ byId('project-meta').append(archived)
972
+ }
973
+ byId('project-archive-action-label').textContent = current.archived ? '恢复项目' : '归档项目'
974
+ byId('project-archive-action-icon').setAttribute('href', current.archived ? '#icon-restore' : '#icon-archive')
975
+ archiveAction.disabled = archiveBusy
976
+ renderPin()
977
+ byId('empty').hidden = true
978
+ byId('project-detail').hidden = false
979
+ }
980
+
981
+ function revealProjectDetail() {
982
+ if (!compactLayout.matches) return
983
+ const heading = byId('project-name')
984
+ heading.focus({ preventScroll: true })
985
+ heading.closest('.detail').scrollIntoView({ block: 'start', behavior: reducedMotion.matches ? 'instant' : 'smooth' })
986
+ }
987
+
988
+ function makeConversationRow(session, open) {
989
+ const row = text('li', '', 'conversation-item')
990
+ const button = text('button', '', 'conversation-row')
991
+ button.type = 'button'
992
+ button.dataset.session = session.id
993
+ const title = session.title || '未命名对话'
994
+ button.title = title
995
+ const info = text('span', '', 'conversation-info')
996
+ const meta = text('span', agentName(session.agent), 'conversation-meta')
997
+ if (session.archivedSource) meta.append(text('span', ' · 本地存档'))
998
+ const date = new Date(session.date)
999
+ if (session.date > 0 && Number.isFinite(date.getTime())) {
1000
+ const today = new Date()
1001
+ const yesterday = new Date(today)
1002
+ yesterday.setDate(today.getDate() - 1)
1003
+ const day = date.toDateString()
1004
+ const display = day === today.toDateString() ? `今天 ${shortClock.format(date)}`
1005
+ : day === yesterday.toDateString() ? `昨天 ${shortClock.format(date)}`
1006
+ : date.getFullYear() === today.getFullYear() ? recentDateFormat.format(date) : historyDateFormat.format(date)
1007
+ const timestamp = text('time', display)
1008
+ timestamp.dateTime = date.toISOString()
1009
+ timestamp.title = historyDateFormat.format(date)
1010
+ meta.append(text('span', ' · '), timestamp)
1011
+ }
1012
+ info.append(text('span', title, 'conversation-title'), meta)
1013
+ const action = text('span', '', 'conversation-action')
1014
+ action.append(text('span', '预览'), icon('chevron'))
1015
+ button.append(agentMark(session.agent), info, action)
1016
+ button.addEventListener('click', () => open(session))
1017
+ row.append(button)
1018
+ return row
1019
+ }
1020
+
1021
+ function resetRecentConversations() {
1022
+ recentRevision++
1023
+ recentKey = ''
1024
+ recentList.replaceChildren()
1025
+ browseHistory.hidden = true
1026
+ }
1027
+
1028
+ async function loadRecentConversations(project) {
1029
+ const revision = ++recentRevision
1030
+ const isCurrent = () => current?.id === project.id && recentRevision === revision
1031
+ if (!nativeSessionImport || !project.hasConversations) {
1032
+ resetRecentConversations()
1033
+ recentStatus.textContent = nativeSessionImport
1034
+ ? '这个项目还没有可迁入的对话。可以用项目资料开新对话。'
1035
+ : '当前 DSH 不支持迁入旧对话。可以用项目资料开新对话。'
1036
+ return
1037
+ }
1038
+ if (!recentKey) recentStatus.textContent = '正在查找最近对话…'
1039
+ try {
1040
+ const { sessions, total } = await api('list-conversations', { projectId: project.id, recent: true })
1041
+ if (!isCurrent()) return
1042
+ const key = JSON.stringify(sessions)
1043
+ if (key !== recentKey) {
1044
+ const active = recentList.contains(document.activeElement) ? document.activeElement.dataset.session : ''
1045
+ recentList.replaceChildren(...sessions.map(session => makeConversationRow(session, item => openSourceConversation(item))))
1046
+ if (active) ([...recentList.querySelectorAll('button')].find(button => button.dataset.session === active)
1047
+ ?? byId('continue-heading')).focus({ preventScroll: true })
1048
+ recentKey = key
1049
+ }
1050
+ recentStatus.textContent = sessions.length
1051
+ ? (current.online ? '' : '原工作目录不可访问,暂时只能预览。')
1052
+ : '这个项目还没有可迁入的对话。可以用项目资料开新对话。'
1053
+ byId('browse-history-label').textContent = `查看全部 ${total ?? sessions.length} 条对话`
1054
+ browseHistory.hidden = (total ?? sessions.length) <= sessions.length
1055
+ } catch {
1056
+ if (!isCurrent()) return
1057
+ recentStatus.textContent = recentList.childElementCount
1058
+ ? '暂时无法刷新对话列表,可稍后重试。'
1059
+ : '暂时读不到对话列表。可以刷新来源,或用项目资料开新对话。'
1060
+ }
1061
+ }
1062
+
1063
+ async function selectProject(project, reveal = false) {
1064
+ if (!filteredProjects().some(item => item.id === project.id)) return
1065
+ if (current?.id === project.id && (detail || detailLoading)) {
1066
+ if (reveal) revealProjectDetail()
1067
+ return
1068
+ }
1069
+ const revision = ++detailRevision
1070
+ detail = undefined
1071
+ context = undefined
1072
+ detailLoading = true
1073
+ selected = new Set()
1074
+ assetSearch.value = ''
1075
+ syncSearch(assetSearch)
1076
+ draftWorkflow.open = false
1077
+ globalLibrary.open = false
1078
+ globalLibrary.hidden = true
1079
+ byId('handoff').open = false
1080
+ byId('history-option').hidden = true
1081
+ byId('selection-global').hidden = true
1082
+ byId('selection-summary').textContent = '接续清单'
1083
+ byId('preview').disabled = true
1084
+ assetSearch.disabled = true
1085
+ status('', false, 'selection-feedback')
1086
+ projectMaterials.replaceChildren(text('p', '正在读取项目资料…', 'asset-empty'))
1087
+ globalMaterials.replaceChildren()
1088
+ queueList.replaceChildren()
1089
+ resetRecentConversations()
1090
+ showProject(project)
1091
+ renderProjects()
1092
+ if (reveal) revealProjectDetail()
1093
+ void loadRecentConversations(project)
1094
+ try {
1095
+ const pendingSelection = selectionSaves.get(project.id)
1096
+ if (pendingSelection) await pendingSelection
1097
+ if (revision !== detailRevision) return
1098
+ const loaded = await api('detail', { projectId: project.id })
1099
+ if (revision !== detailRevision) return
1100
+ applyDetail(project, loaded, false)
1101
+ } catch (error) {
1102
+ if (revision === detailRevision) projectMaterials.replaceChildren(text('p', error.message, 'asset-empty error'))
1103
+ } finally {
1104
+ if (revision === detailRevision) detailLoading = false
1105
+ }
1106
+ }
1107
+
1108
+ function canAutoRefresh() {
1109
+ return document.visibilityState === 'visible' && !dialog.open && agentPopover.hidden && !detailLoading && !archiveBusy
1110
+ }
1111
+
1112
+ function liveState(label, scannedAt, error) {
1113
+ const indicator = byId('live-state')
1114
+ indicator.textContent = label
1115
+ indicator.dataset.state = error ? 'error' : label.includes('暂停') ? 'paused' : scannedAt ? 'active' : 'loading'
1116
+ indicator.title = error ?? ''
1117
+ if (scannedAt) {
1118
+ const timestamp = new Date(scannedAt)
1119
+ if (Number.isNaN(timestamp.getTime())) return
1120
+ const lastScan = byId('last-scan')
1121
+ lastScan.dateTime = timestamp.toISOString()
1122
+ lastScan.textContent = `上次扫描 ${clockFormat.format(timestamp)}`
1123
+ lastScan.hidden = false
1124
+ }
1125
+ }
1126
+
1127
+ async function refresh(force, automatic = false) {
1128
+ if (refreshing || archiveBusy || (automatic && !canAutoRefresh())) return false
1129
+ refreshing = true
1130
+ refreshButton.disabled = true
1131
+ refreshButton.dataset.loading = 'true'
1132
+ if (!automatic) status(force ? '正在重新扫描本机来源…' : '正在扫描本机来源…')
1133
+ try {
1134
+ const result = await api('catalog', { refresh: force })
1135
+ if (dialog.open || (automatic && !canAutoRefresh())) return false
1136
+ if (result.revision < lastPinRevision) return false
1137
+ const firstLoad = !catalogLoaded
1138
+ catalogLoaded = true
1139
+ catalog = result.projects
1140
+ archiveAvailable = catalog.every(project => typeof project.archived === 'boolean')
1141
+ nativeSessionImport = result.nativeSessionImport === true
1142
+ preferencesAvailable = catalog.every(project => typeof project.pinned === 'boolean')
1143
+ agentIcons = result.agentIcons ?? {}
1144
+ const activeAgent = availableAgents[activeAgentIndex]
1145
+ availableAgents = ['', ...[...new Set([selectedAgent, ...catalog.flatMap(project => project.agents)])]
1146
+ .filter(Boolean).sort((left, right) => agentName(left).localeCompare(agentName(right), 'zh-CN'))]
1147
+ renderAgentPicker(activeAgent)
1148
+ renderSources(result.sources)
1149
+ if (!archiveAvailable || !preferencesAvailable) status('请完全退出 DSH 并重新打开,加载新版插件。')
1150
+ else if (!automatic) status('')
1151
+ const matches = filteredProjects()
1152
+ reconcileProject(matches, firstLoad)
1153
+ renderProjects()
1154
+ const previous = matches.find(project => project.id === current?.id)
1155
+ const revision = detailRevision
1156
+ if (previous && !detailLoading) {
1157
+ if (!detail) {
1158
+ void selectProject(previous)
1159
+ } else {
1160
+ showProject(previous)
1161
+ void loadRecentConversations(previous)
1162
+ const loaded = await api('detail', { projectId: previous.id })
1163
+ if (revision === detailRevision && !dialog.open) applyDetail(previous, loaded, true)
1164
+ }
1165
+ }
1166
+ sourceRevision = result.revision ?? sourceRevision
1167
+ liveState('实时扫描已开启', result.scannedAt)
1168
+ return true
1169
+ } catch (error) {
1170
+ liveState('实时扫描暂不可用', undefined, error.message)
1171
+ if (!automatic) {
1172
+ status(error.message, true)
1173
+ byId('empty').textContent = '项目列表暂不可用。'
1174
+ }
1175
+ return false
1176
+ } finally {
1177
+ refreshing = false
1178
+ refreshButton.disabled = false
1179
+ delete refreshButton.dataset.loading
1180
+ }
1181
+ }
1182
+
1183
+ function schedulePoll(delay = 250) {
1184
+ clearTimeout(pollTimer)
1185
+ if (document.visibilityState === 'visible' && !dialog.open && agentPopover.hidden) pollTimer = setTimeout(pollSources, delay)
1186
+ }
1187
+
1188
+ async function pollSources() {
1189
+ if (polling) return
1190
+ if (refreshing || !canAutoRefresh()) {
1191
+ schedulePoll()
1192
+ return
1193
+ }
1194
+ polling = true
1195
+ const baseline = sourceRevision
1196
+ let delay = 250
1197
+ try {
1198
+ const result = await api('changes', { revision: baseline, projectId: current?.id, wait: true })
1199
+ if (sourceRevision !== baseline || refreshing || !canAutoRefresh()) return
1200
+ if (result.changed) {
1201
+ if (!await refresh(false, true)) delay = 1000
1202
+ else if (sourceRevision === baseline) sourceRevision = result.revision ?? sourceRevision
1203
+ return
1204
+ }
1205
+ sourceRevision = result.revision ?? sourceRevision
1206
+ liveState('实时扫描已开启', result.scannedAt)
1207
+ } catch (error) {
1208
+ if (canAutoRefresh()) liveState('实时扫描暂不可用', undefined, error.message)
1209
+ delay = 5000
1210
+ } finally {
1211
+ polling = false
1212
+ schedulePoll(delay)
1213
+ }
1214
+ }
1215
+
1216
+ function clearDownload() {
1217
+ if (downloadUrl) {
1218
+ const previousUrl = downloadUrl
1219
+ setTimeout(() => URL.revokeObjectURL(previousUrl), 30_000)
1220
+ }
1221
+ downloadUrl = undefined
1222
+ exportDownload.removeAttribute('href')
1223
+ exportDownload.hidden = true
1224
+ byId('export-output').hidden = true
1225
+ byId('export-output').open = false
1226
+ byId('export-text').textContent = ''
1227
+ }
1228
+
1229
+ function setDialogBusy(busy) {
1230
+ dialogBusy = busy
1231
+ dialogClose.disabled = busy
1232
+ importButton.disabled = busy
1233
+ recoverDraftButton.disabled = busy
1234
+ exportButton.disabled = busy
1235
+ exportShareButton.disabled = busy
1236
+ exportTrace.disabled = busy
1237
+ sessionSelect.disabled = busy
1238
+ byId('history-back-button').disabled = busy
1239
+ historyImport.disabled = busy
1240
+ skillApply.disabled = busy
1241
+ skillUndo.disabled = busy
1242
+ skillDeactivate.disabled = busy
1243
+ }
1244
+
1245
+ function showDialog(mode, title, note, body, assetKind = 'memory') {
1246
+ dialogMode = mode
1247
+ dialog.dataset.mode = mode
1248
+ ticket = undefined
1249
+ nativeSessions = []
1250
+ sessionTraceRequest?.abort()
1251
+ sessionSourceRecord.replaceChildren()
1252
+ historyProject = undefined
1253
+ historySessions = undefined
1254
+ historyChosenId = undefined
1255
+ historyTicket = undefined
1256
+ importedSessionId = undefined
1257
+ draftRecovery = undefined
1258
+ dialogSkillCandidates = []
1259
+ dialogSkillIds = new Set()
1260
+ skillPreviewTicket = undefined
1261
+ skillManagerAsset = undefined
1262
+ skillManagerProject = undefined
1263
+ previewInput = undefined
1264
+ activationReview = undefined
1265
+ activationSummary = ''
1266
+ if (activateDialog.open) activateDialog.close()
1267
+ clearDownload()
1268
+ byId('dialog-title').textContent = title
1269
+ byId('dialog-note').textContent = note
1270
+ byId('dialog-mark').replaceChildren(icon(mode === 'session' ? 'download'
1271
+ : mode === 'asset' ? assetKind
1272
+ : mode === 'history' ? 'history'
1273
+ : mode === 'skill' ? 'skill' : 'bridge'))
1274
+ dialogText.hidden = false
1275
+ dialogText.dataset.format = 'plain'
1276
+ dialogText.textContent = body
1277
+ dialogText.closest('.dialog-content').scrollTop = 0
1278
+ byId('session-choice').hidden = true
1279
+ byId('history-choice').hidden = true
1280
+ byId('history-back').hidden = true
1281
+ status('', false, 'dialog-status')
1282
+ importButton.hidden = true
1283
+ recoverDraftButton.hidden = true
1284
+ exportButton.hidden = true
1285
+ exportShareButton.hidden = true
1286
+ exportTraceOption.hidden = true
1287
+ exportTrace.checked = false
1288
+ historyImport.hidden = true
1289
+ skillApply.hidden = true
1290
+ skillUndo.hidden = true
1291
+ skillDeactivate.hidden = true
1292
+ setDialogBusy(false)
1293
+ if (!dialog.open) dialog.showModal()
1294
+ clearTimeout(pollTimer)
1295
+ liveState('实时扫描已暂停')
1296
+ return ++dialogEpoch
1297
+ }
1298
+
1299
+ function startHistoryDialog(title, note, body) {
1300
+ const project = current
1301
+ if (dialog.open || !project || !nativeSessionImport || !filteredProjects().some(item => item.id === project.id)) return
1302
+ const epoch = showDialog('history', title, note, body)
1303
+ historyProject = project
1304
+ return epoch
1305
+ }
1306
+
1307
+ const historyNote = '迁入用户与助手的文字消息,并保留可读取的思考摘要与工具记录,只供查阅。'
1308
+
1309
+ function openSourceConversation(session) {
1310
+ if (startHistoryDialog('继续旧对话', historyNote, '正在读取这条对话…') === undefined) return
1311
+ void previewSourceConversation(session)
1312
+ }
1313
+
1314
+ async function chooseSourceConversation() {
1315
+ const epoch = startHistoryDialog('查看全部对话', '选择一条对话以预览历史消息。', '正在读取对话列表…')
1316
+ if (epoch === undefined) return
1317
+ try {
1318
+ const { sessions } = await api('list-conversations', { projectId: historyProject.id })
1319
+ if (!dialog.open || dialogEpoch !== epoch) return
1320
+ historySessions = sessions
1321
+ historySearch.value = ''
1322
+ historyLimit = 30
1323
+ showHistoryResults()
1324
+ } catch (error) {
1325
+ if (dialog.open && dialogEpoch === epoch) dialogText.textContent = error.message
1326
+ }
1327
+ }
1328
+
1329
+ function renderHistoryResults() {
1330
+ const query = historySearch.value.trim().toLowerCase()
1331
+ syncSearch(historySearch)
1332
+ const matches = historySessions.filter(session => [session.title, agentName(session.agent)]
1333
+ .some(value => value?.toLowerCase().includes(query)))
1334
+ historyResults.replaceChildren(...matches.slice(0, historyLimit).map(session => makeConversationRow(session, previewSourceConversation)))
1335
+ byId('history-empty').textContent = matches.length ? '' : (query ? '没有找到匹配的对话。' : '这个项目暂无可迁入的对话。')
1336
+ byId('history-more').hidden = matches.length <= historyLimit
1337
+ }
1338
+
1339
+ function showHistoryResults() {
1340
+ if (!historySessions) return
1341
+ historyPreview++
1342
+ historyTicket = undefined
1343
+ importedSessionId = undefined
1344
+ historyImport.hidden = true
1345
+ dialogSkillCandidates = []
1346
+ dialogSkillIds = new Set()
1347
+ byId('history-back').hidden = true
1348
+ byId('dialog-title').textContent = '查看全部对话'
1349
+ byId('dialog-note').textContent = '选择一条对话以预览历史消息。'
1350
+ dialogText.hidden = true
1351
+ byId('history-choice').hidden = false
1352
+ status('', false, 'dialog-status')
1353
+ renderHistoryResults()
1354
+ dialogText.closest('.dialog-content').scrollTop = 0
1355
+ const previous = historyChosenId && [...historyResults.querySelectorAll('button')].find(button => button.dataset.session === historyChosenId)
1356
+ ;(previous || historySearch).focus()
1357
+ }
1358
+
1359
+ const traceKindNames = { summary: '思考摘要', tool_call: '工具调用', tool_result: '工具结果' }
1360
+ const traceStateNames = { missing: '未记录结果', error: '失败', pending: '待确认', truncated: '已截取' }
1361
+
1362
+ function createTraceDisclosure(label, count) {
1363
+ const details = document.createElement('details')
1364
+ details.className = 'trace-disclosure'
1365
+ details.append(text('summary', `${label} · ${count} 项`))
1366
+ return details
1367
+ }
1368
+
1369
+ // Source trace is read-only: it is shown next to the question it belongs to and
1370
+ // never replayed into the new session as a tool event.
1371
+ function traceDisclosure(items, turnLabel) {
1372
+ const details = createTraceDisclosure(turnLabel ?? '来源记录', items.length)
1373
+ const list = text('div', '', 'trace-list')
1374
+ let turn
1375
+ for (const item of items) {
1376
+ if (!turnLabel && item.turn && item.turn !== turn) {
1377
+ turn = item.turn
1378
+ list.append(text('h4', `第 ${turn} 轮`, 'trace-turn'))
1379
+ }
1380
+ const row = text('article', '', 'trace-item')
1381
+ row.dataset.kind = item.kind
1382
+ const head = text('div', '', 'trace-head')
1383
+ head.append(text('span', traceKindNames[item.kind] ?? item.kind, 'trace-kind'))
1384
+ if (item.name) head.append(text('code', item.name, 'trace-name'))
1385
+ if (item.callId) head.append(text('code', `调用 ${item.callId}`, 'trace-name'))
1386
+ const state = traceStateNames[item.status]
1387
+ if (state) {
1388
+ const chip = text('span', state, 'trace-state')
1389
+ chip.dataset.state = item.status
1390
+ head.append(chip)
1391
+ }
1392
+ if (item.truncated && item.status !== 'truncated') head.append(text('span', '已截取', 'trace-state'))
1393
+ if (item.time) head.append(text('time', historyDateFormat.format(new Date(item.time)), 'trace-time'))
1394
+ row.append(head)
1395
+ if (item.text) row.append(text('p', item.text, 'trace-text'))
1396
+ else if (item.kind === 'tool_result') row.append(text('p', '未记录结果', 'trace-text trace-empty'))
1397
+ if (item.text && item.kind === 'tool_result') {
1398
+ const copy = text('button', '复制结果摘录', 'trace-copy')
1399
+ copy.type = 'button'
1400
+ copy.addEventListener('click', async () => {
1401
+ try {
1402
+ await navigator.clipboard.writeText(item.text)
1403
+ copy.textContent = '已复制'
1404
+ setTimeout(() => { copy.textContent = '复制结果摘录' }, 1600)
1405
+ } catch {
1406
+ status('无法访问剪贴板,请手动选择文字复制。', true, 'dialog-status')
1407
+ }
1408
+ })
1409
+ row.append(copy)
1410
+ }
1411
+ list.append(row)
1412
+ }
1413
+ details.append(list)
1414
+ return details
1415
+ }
1416
+
1417
+ function sessionTraceDisclosure(items) {
1418
+ const turns = new Map()
1419
+ for (const item of items) {
1420
+ const entries = turns.get(item.turn)
1421
+ if (entries) entries.push(item)
1422
+ else turns.set(item.turn, [item])
1423
+ }
1424
+ const details = createTraceDisclosure('来源记录', items.length)
1425
+ const list = text('div', '', 'trace-list trace-turn-list')
1426
+ for (const [turn, entries] of turns) {
1427
+ list.append(traceDisclosure(entries, turn ? `第 ${turn} 轮` : '未标记轮次'))
1428
+ }
1429
+ details.append(list)
1430
+ return details
1431
+ }
1432
+
1433
+ const formatStatNumber = new Intl.NumberFormat('zh-CN').format
1434
+
1435
+ function renderSourceStats(stats, counts = {}, { preview = false } = {}) {
1436
+ const section = text('section', '', 'source-stats')
1437
+ const title = '原对话统计'
1438
+ section.setAttribute('aria-label', title)
1439
+ section.append(text('h3', title))
1440
+ const metrics = text('dl', '', 'source-stats-grid')
1441
+ const notes = []
1442
+ function addMetric(label, value) {
1443
+ const metric = document.createElement('div')
1444
+ metric.append(text('dt', label), text('dd', typeof value === 'number' ? formatStatNumber(value) : value))
1445
+ metrics.append(metric)
1446
+ }
1447
+ if (stats) {
1448
+ const total = stats.userMessages + stats.assistantMessages
1449
+ addMetric('已读轮次', stats.userMessages)
1450
+ addMetric('已读消息', total)
1451
+ notes.push(`用户 ${formatStatNumber(stats.userMessages)} 条,助手 ${formatStatNumber(stats.assistantMessages)} 条`)
1452
+ if (stats.importedMessages !== total) {
1453
+ notes.push(`${preview ? '预览保留' : '已迁入'} ${formatStatNumber(stats.importedMessages)} 条消息`)
1454
+ }
1455
+ }
1456
+ addMetric(preview ? '可带入工具调用' : '已保存工具调用', counts.toolCall ?? 0)
1457
+ if (stats?.elapsedMs !== undefined) {
1458
+ const seconds = Math.floor(stats.elapsedMs / 1000)
1459
+ const hours = Math.floor(seconds / 3600)
1460
+ const minutes = Math.floor(seconds / 60) % 60
1461
+ const remainder = String(seconds % 60).padStart(2, '0')
1462
+ addMetric('消息时间跨度', hours ? `${hours}:${String(minutes).padStart(2, '0')}:${remainder}` : `${minutes}:${remainder}`)
1463
+ }
1464
+ if (stats?.tokens) {
1465
+ const { total, input, output } = stats.tokens
1466
+ addMetric('源记录 Token', total)
1467
+ if (input !== undefined && output !== undefined) notes.push(`输入 ${formatStatNumber(input)},输出 ${formatStatNumber(output)}`)
1468
+ }
1469
+ if (counts.failed) notes.push(`${formatStatNumber(counts.failed)} 次失败`)
1470
+ if (counts.missing) notes.push(`${formatStatNumber(counts.missing)} 次未记录结果`)
1471
+ if (counts.summary) notes.push(`${formatStatNumber(counts.summary)} 段思考摘要`)
1472
+ section.append(metrics)
1473
+ if (notes.length) section.append(text('p', notes.join(' · ')))
1474
+ if (stats?.partial) section.append(text('p', '消息与轮次仅统计已读取的部分原记录。'))
1475
+ if (!stats) section.append(text('p', '旧版迁入的会话,统计来自当时保存的来源记录。'))
1476
+ return section
1477
+ }
1478
+
1479
+ async function previewSourceConversation(session) {
1480
+ const epoch = dialogEpoch
1481
+ const revision = ++historyPreview
1482
+ historyChosenId = session.id
1483
+ historyTicket = undefined
1484
+ importedSessionId = undefined
1485
+ historyImport.hidden = true
1486
+ byId('history-import-label').textContent = '迁入并继续'
1487
+ byId('history-choice').hidden = true
1488
+ byId('history-back').hidden = !historySessions
1489
+ byId('dialog-title').textContent = '继续旧对话'
1490
+ byId('dialog-note').textContent = historyNote
1491
+ dialogText.hidden = false
1492
+ dialogText.dataset.format = 'plain'
1493
+ dialogText.textContent = '正在读取这条对话…'
1494
+ dialogText.closest('.dialog-content').scrollTop = 0
1495
+ if (historySessions) byId('history-back-button').focus()
1496
+ else dialogText.focus({ preventScroll: true })
1497
+ status('', false, 'dialog-status')
1498
+ try {
1499
+ const result = await api('preview-conversation', { projectId: historyProject.id, sessionId: session.id })
1500
+ if (!dialog.open || dialogEpoch !== epoch || revision !== historyPreview) return
1501
+ historyTicket = result.ticket
1502
+ const title = text('h3', result.title, 'preview-lead')
1503
+ const source = text('p', '', 'preview-context history-source')
1504
+ source.append(agentLabel(session.agent), text('code', result.cwd || historyProject.cwd, 'preview-source'))
1505
+ const skillChoices = renderSkillChoices(result.skillCandidates, { history: true })
1506
+ const stats = renderSourceStats(result.sourceStats, result.traceCounts, { preview: true })
1507
+ const traceByMessage = new Map()
1508
+ for (const item of result.trace ?? []) {
1509
+ if (!Number.isInteger(item.messageIndex)) continue
1510
+ traceByMessage.set(item.messageIndex, [...(traceByMessage.get(item.messageIndex) ?? []), item])
1511
+ }
1512
+ const summary = text('p', [
1513
+ result.truncated ? '源记录或读取范围有限,部分历史未带入' : '',
1514
+ result.canImport ? '' : '原工作目录不可访问,当前可预览',
1515
+ ].filter(Boolean).join(' · '), 'preview-context')
1516
+ dialogText.dataset.format = 'history'
1517
+ dialogText.replaceChildren(title, source, stats, ...(summary.textContent ? [summary] : []), ...(skillChoices ? [skillChoices] : []), ...result.messages.map((message, index) => {
1518
+ const row = text('section', '', 'history-message')
1519
+ row.dataset.role = message.role
1520
+ const body = message.role === 'assistant'
1521
+ ? markdownBody(message.text, 'preview-body')
1522
+ : text('p', message.text, 'preview-body')
1523
+ row.append(text('h3', message.role === 'user' ? '用户' : '助手'), body)
1524
+ const items = traceByMessage.get(index)
1525
+ if (items?.length) row.append(traceDisclosure(items))
1526
+ return row
1527
+ }))
1528
+ historyImport.hidden = !result.canImport
1529
+ syncSkillChoiceButtons()
1530
+ } catch (error) {
1531
+ if (dialog.open && dialogEpoch === epoch && revision === historyPreview) dialogText.textContent = error.message
1532
+ }
1533
+ }
1534
+
1535
+ async function importSourceConversation() {
1536
+ if (!historyTicket || dialogBusy) return
1537
+ if (!importedSessionId && dialogSkillIds.size) {
1538
+ await beginSkillActivation('history')
1539
+ return
1540
+ }
1541
+ await completeHandoff('history', [])
1542
+ }
1543
+
1544
+ function renderHandoff({ intro, sections, footer, cwd }, skillCandidates = []) {
1545
+ const lead = text('div', '', 'preview-intro')
1546
+ const [heading, ...introLines] = intro.split('\n')
1547
+ lead.append(text('p', heading, 'preview-lead'))
1548
+ for (const line of introLines.slice(0, 2)) {
1549
+ const metadata = /^(工作目录|来源):(.+)$/.exec(line)
1550
+ if (metadata) {
1551
+ const row = text('div', '', 'preview-meta')
1552
+ row.append(text('span', metadata[1]), text('code', metadata[2]))
1553
+ if (metadata[1] === '工作目录' && cwd) {
1554
+ row.append(pathActions({ label: '工作目录', path: cwd, directory: true }))
1555
+ }
1556
+ lead.append(row)
1557
+ } else if (line) lead.append(text('p', line, 'preview-context'))
1558
+ }
1559
+ const context = introLines.slice(2).join('\n').trim()
1560
+ if (context) lead.append(text('p', context, 'preview-context'))
1561
+ const content = sections.map(section => {
1562
+ const block = text('section', '', 'preview-section')
1563
+ block.append(text('h3', section.label))
1564
+ if (section.file) {
1565
+ const fileRow = text('div', '', 'preview-source-row')
1566
+ fileRow.append(
1567
+ text('code', section.file, 'preview-source'),
1568
+ section.assetId
1569
+ ? pathActions({ label: section.label, path: section.file, assetId: section.assetId })
1570
+ : pathActions({ label: section.label, path: section.file }),
1571
+ )
1572
+ block.append(fileRow)
1573
+ }
1574
+ const source = section.text
1575
+ const body = isMarkdownFile(section.file) || section.markdown
1576
+ ? markdownBody(source, 'preview-body', current?.id, section.references)
1577
+ : text('p', source, 'preview-body')
1578
+ block.append(body)
1579
+ return block
1580
+ })
1581
+ const skillChoices = renderSkillChoices(skillCandidates)
1582
+ dialogText.dataset.format = 'handoff'
1583
+ dialogText.replaceChildren(lead, ...(skillChoices ? [skillChoices] : []), ...content)
1584
+ if (footer) dialogText.append(text('p', footer, 'preview-context'))
1585
+ syncSkillChoiceButtons()
1586
+ }
1587
+
1588
+ async function viewAsset(asset) {
1589
+ const project = current
1590
+ const epoch = showDialog('asset', materialName(asset), asset.file, '正在读取…', asset.kind)
1591
+ try {
1592
+ const result = await api('asset', { projectId: project.id, assetId: asset.id })
1593
+ if (!dialog.open || dialogEpoch !== epoch) return
1594
+ if (isMarkdownFile(asset.file)) {
1595
+ dialogText.dataset.format = 'markdown'
1596
+ dialogText.replaceChildren(renderProjectMarkdown(result.text, project.id, result.references))
1597
+ if (result.truncated) dialogText.append(text('p', '[预览已截取,完整内容见来源文件。]', 'preview-context'))
1598
+ } else {
1599
+ dialogText.textContent = result.text + (result.truncated ? '\n\n[预览已截取]' : '')
1600
+ }
1601
+ } catch (error) {
1602
+ if (dialog.open && dialogEpoch === epoch) {
1603
+ dialogText.dataset.format = 'plain'
1604
+ dialogText.textContent = error.message
1605
+ }
1606
+ }
1607
+ }
1608
+
1609
+ async function preview() {
1610
+ const project = current
1611
+ if (!project || !detail || !filteredProjects().some(item => item.id === project.id)) return
1612
+ const note = project.online
1613
+ ? '可导出 Markdown,或在原工作目录打开 DSH 会话并继续编辑草稿。'
1614
+ : '原工作目录不可访问。可将现有交接资料导出为 Markdown。'
1615
+ const epoch = showDialog('handoff', `草稿预览 · ${project.name}`, note, '正在准备…')
1616
+ try {
1617
+ const input = { projectId: project.id, assetIds: [...selected], history: historyOption.checked }
1618
+ previewInput = input
1619
+ const result = await api('preview', input)
1620
+ if (!dialog.open || dialogEpoch !== epoch) return
1621
+ ticket = result.ticket
1622
+ if (result.preview) renderHandoff(result.preview, result.skillCandidates)
1623
+ else dialogText.textContent = result.prompt
1624
+ importButton.hidden = result.canImport === false || !project.online
1625
+ exportButton.hidden = false
1626
+ exportShareButton.hidden = false
1627
+ exportHasTrace = Boolean(result.preview?.trace?.length)
1628
+ exportTraceOption.hidden = !exportHasTrace
1629
+ exportTrace.checked = false
1630
+ syncSkillChoiceButtons()
1631
+ if (result.truncated) status('部分资料已截取。完整内容可在来源文件查看。', false, 'dialog-status')
1632
+ } catch (error) {
1633
+ if (dialog.open && dialogEpoch === epoch) status(error.message, true, 'dialog-status')
1634
+ }
1635
+ }
1636
+
1637
+ function requestParent(type, values, requestId = `bridge-${Date.now()}-${++requestNumber}`) {
1638
+ if (window.parent === window) {
1639
+ return Promise.reject(new Error('请在 DSH 侧栏打开 Agent 接续后使用此操作。'))
1640
+ }
1641
+ return new Promise((resolve, reject) => {
1642
+ const timer = setTimeout(() => {
1643
+ pending = undefined
1644
+ reject(new Error('DSH 暂未响应。请重试。'))
1645
+ }, 25_000)
1646
+ pending = { requestId, timer, resolve, reject }
1647
+ try {
1648
+ window.parent.postMessage({ type: `dsh-agent-bridge:${type}`, requestId, ...values }, parentOrigin)
1649
+ } catch (error) {
1650
+ clearTimeout(timer)
1651
+ pending = undefined
1652
+ reject(error)
1653
+ }
1654
+ })
1655
+ }
1656
+
1657
+ async function reloadCurrentDetail(preserve = true) {
1658
+ if (!current || !detail) return false
1659
+ const project = current
1660
+ const revision = detailRevision
1661
+ const loaded = await api('detail', { projectId: project.id })
1662
+ if (revision !== detailRevision || current?.id !== project.id) return false
1663
+ applyDetail(project, loaded, preserve)
1664
+ return true
1665
+ }
1666
+
1667
+ function appliedSkillSummary(result) {
1668
+ const confirmed = result.items.filter(item => item.applied && item.verified && item.canOmitBody).length
1669
+ const disabled = result.items.filter(item => item.applied && item.verified && item.disabled).length
1670
+ const pending = result.items.filter(item => item.applied && !item.verified).length
1671
+ const failed = result.items.filter(item => !item.applied).length
1672
+ const parts = [
1673
+ confirmed ? `已确认 ${confirmed} 项` : '',
1674
+ disabled ? `已登记但当前不可调用 ${disabled} 项` : '',
1675
+ pending ? `待 DSH 确认 ${pending} 项` : '',
1676
+ failed ? `未启用 ${failed} 项` : '',
1677
+ ].filter(Boolean)
1678
+ return parts.length ? `${parts.join(',')}。` : '没有技能被更改。'
1679
+ }
1680
+
1681
+ function setActivationBusy(busy) {
1682
+ activateConfirm.disabled = busy
1683
+ activateText.disabled = busy
1684
+ activateClose.disabled = busy
1685
+ }
1686
+
1687
+ function renderActivationReview(review) {
1688
+ const selectedNames = new Map(context?.entries.map(entry => [entry.id, entry]) ?? [])
1689
+ const panel = text('div', '', 'skill-manager')
1690
+ const lead = text('div', '', 'preview-intro')
1691
+ lead.append(text('p', `目标项目 · ${review.project.name}`, 'preview-lead'))
1692
+ const root = review.projectRoot || detail?.skillProjectRoot || review.project.cwd
1693
+ const rootRow = text('div', '', 'preview-meta')
1694
+ rootRow.append(text('span', '启用范围'), text('code', root))
1695
+ lead.append(rootRow, text('p', '确认后只登记允许的版本;冲突项和确认失败项仍保留文字摘录。', 'preview-context'))
1696
+ panel.append(lead)
1697
+ for (const item of review.items) {
1698
+ const source = selectedNames.get(item.assetId)
1699
+ const block = text('section', '', 'preview-section')
1700
+ block.append(text('h3', `${item.name || item.dshName} → ${item.dshName}`))
1701
+ const state = text('p', '', 'preview-context')
1702
+ state.append(skillStatusNode(item))
1703
+ block.append(state)
1704
+ if (source?.file) block.append(text('code', source.file, 'preview-source'))
1705
+ if (item.fileCount) {
1706
+ block.append(text('p',
1707
+ `${item.fileCount} 个文件 · ${item.resources?.scripts ?? 0} 个脚本 · ${item.resources?.references ?? 0} 个参考 · ${item.resources?.assets ?? 0} 个资源`,
1708
+ 'preview-context'))
1709
+ }
1710
+ if (item.scriptFiles?.length) block.append(text('p', `脚本:${item.scriptFiles.join('、')}`, 'preview-context'))
1711
+ if (item.detail || item.reason) block.append(text('p', item.detail || item.reason, 'preview-context'))
1712
+ panel.append(block)
1713
+ }
1714
+ activateBody.replaceChildren(panel)
1715
+ const confirmable = review.items.filter(actionableSkill).length
1716
+ const already = review.items.filter(item => item.verified && item.canOmitBody
1717
+ && ['reuse-active', 'native'].includes(item.action)).length
1718
+ activateConfirm.hidden = confirmable + already === 0
1719
+ activateConfirm.replaceChildren(
1720
+ document.createTextNode(confirmable ? `确认启用 ${confirmable} 项并继续`
1721
+ : already ? '沿用已发现技能并继续' : '没有可启用项'),
1722
+ icon('arrow'),
1723
+ )
1724
+ activateText.hidden = false
1725
+ activateText.textContent = '仅文字继续'
1726
+ activateStatus.textContent = ''
1727
+ }
1728
+
1729
+ async function beginSkillActivation(purpose) {
1730
+ const project = purpose === 'history' ? historyProject : current
1731
+ if (!project || !dialogSkillIds.size) {
1732
+ await completeHandoff(purpose, [])
1733
+ return
1734
+ }
1735
+ try {
1736
+ const preview = await api('preview-skill-activation', {
1737
+ projectId: project.id, assetIds: [...dialogSkillIds],
1738
+ })
1739
+ activationReview = { ...preview, project, purpose }
1740
+ activationSummary = ''
1741
+ renderActivationReview(activationReview)
1742
+ if (!activateDialog.open) activateDialog.showModal()
1743
+ } catch (error) {
1744
+ status(error.message, true, purpose === 'history' ? 'dialog-status' : 'dialog-status')
1745
+ }
1746
+ }
1747
+
1748
+ async function confirmSkillActivation() {
1749
+ if (!activationReview || activateConfirm.disabled) return
1750
+ setActivationBusy(true)
1751
+ activateStatus.textContent = '正在保存完整技能包…'
1752
+ try {
1753
+ const previewConfirmed = activationReview.items.filter(item => item.verified && item.canOmitBody
1754
+ && ['reuse-active', 'native'].includes(item.action)).map(item => item.assetId)
1755
+ const actionable = activationReview.items.filter(actionableSkill)
1756
+ let appliedItems = []
1757
+ if (actionable.length) {
1758
+ const applied = await api('apply-skill-activation', { ticket: activationReview.ticket })
1759
+ appliedItems = applied.items
1760
+ activationSummary = appliedSkillSummary(applied)
1761
+ } else {
1762
+ activationSummary = previewConfirmed.length ? '沿用已由 DSH 发现的技能。' : ''
1763
+ }
1764
+ const confirmedIds = [
1765
+ ...previewConfirmed,
1766
+ ...appliedItems.filter(item => item.applied && item.verified && item.canOmitBody).map(item => item.assetId),
1767
+ ]
1768
+ const purpose = activationReview.purpose
1769
+ activationReview = undefined
1770
+ activateDialog.close()
1771
+ await completeHandoff(purpose, [...new Set(confirmedIds)])
1772
+ } catch (error) {
1773
+ activateStatus.textContent = error.message
1774
+ } finally {
1775
+ setActivationBusy(false)
1776
+ }
1777
+ }
1778
+
1779
+ async function continueWithTextOnly() {
1780
+ if (!activationReview || activateText.disabled) return
1781
+ const purpose = activationReview.purpose
1782
+ activationReview = undefined
1783
+ activationSummary = '未启用技能,继续使用文字交接。'
1784
+ activateDialog.close()
1785
+ await completeHandoff(purpose, [])
1786
+ }
1787
+
1788
+ async function completeHandoff(purpose, confirmedSkillIds) {
1789
+ if (purpose === 'history') {
1790
+ if (!historyTicket || dialogBusy) return
1791
+ setDialogBusy(true)
1792
+ status(importedSessionId ? '正在打开已迁入的会话…' : '正在迁入会话…', false, 'dialog-status')
1793
+ try {
1794
+ if (!importedSessionId) {
1795
+ const result = await api('import-conversation', { ticket: historyTicket })
1796
+ importedSessionId = result.sessionId
1797
+ }
1798
+ await requestParent('open-imported', { sessionId: importedSessionId })
1799
+ dialog.close()
1800
+ status(`历史已迁入。打开会话即可继续。${activationSummary}`)
1801
+ } catch (error) {
1802
+ if (importedSessionId) byId('history-import-label').textContent = '打开已迁入会话'
1803
+ status(error.message, true, 'dialog-status')
1804
+ } finally {
1805
+ setDialogBusy(false)
1806
+ }
1807
+ return
1808
+ }
1809
+
1810
+ if (!ticket || dialogBusy || importButton.hidden) return
1811
+ setDialogBusy(true)
1812
+ status(draftRecovery ? '正在重试填入草稿…' : '正在创建 DSH 会话…', false, 'dialog-status')
1813
+ try {
1814
+ if (confirmedSkillIds.length && previewInput) {
1815
+ try {
1816
+ const revised = await api('preview', { ...previewInput, nativeSkillIds: confirmedSkillIds })
1817
+ ticket = revised.ticket
1818
+ } catch (error) {
1819
+ activationSummary += ` ${error.message} 已保留技能正文。`
1820
+ const revised = await api('preview', previewInput)
1821
+ ticket = revised.ticket
1822
+ }
1823
+ }
1824
+ const { path, prompt } = await api('open', { ticket })
1825
+ await requestParent('open', { path, prompt, bridgeNonce: nonce }, ticket)
1826
+ ticket = undefined
1827
+ dialog.close()
1828
+ status(`DSH 会话已打开。交接草稿已填入输入框。${activationSummary}`)
1829
+ } catch (error) {
1830
+ if (Object.hasOwn(error, 'recoverySessionId')) draftRecovery = error.recoverySessionId
1831
+ recoverDraftButton.hidden = !draftRecovery
1832
+ status(error.message, true, 'dialog-status')
1833
+ } finally {
1834
+ setDialogBusy(false)
1835
+ }
1836
+ }
1837
+
1838
+ function renderSkillManager(result, asset) {
1839
+ const item = result.items[0]
1840
+ skillPreviewTicket = result.ticket
1841
+ if (!item) {
1842
+ dialogText.textContent = '没有收到技能状态。'
1843
+ return
1844
+ }
1845
+ const panel = text('div', '', 'skill-manager')
1846
+ const lead = text('div', '', 'preview-intro')
1847
+ lead.append(text('p', item.name || asset.name, 'preview-lead'))
1848
+ const state = text('p', '', 'preview-context')
1849
+ state.append(skillStatusNode(item))
1850
+ lead.append(state)
1851
+ const meta = text('div', '', 'skill-manager-meta')
1852
+ const addMeta = (label, value, code = false) => {
1853
+ if (!value) return
1854
+ const row = text('div', '')
1855
+ row.append(text('span', label), code ? text('code', value) : document.createTextNode(value))
1856
+ meta.append(row)
1857
+ }
1858
+ addMeta('DSH 名称', item.dshName || asset.name, true)
1859
+ addMeta('启用范围', item.scopeRoot || detail?.skillProjectRoot)
1860
+ addMeta('来源', asset.file, true)
1861
+ if (item.fileCount) addMeta('包内容', `${item.fileCount} 个文件 · ${item.resources?.scripts ?? 0} 个脚本 · ${item.resources?.references ?? 0} 个参考 · ${item.resources?.assets ?? 0} 个资源`)
1862
+ lead.append(meta)
1863
+ if (item.detail || item.reason) lead.append(text('p', item.detail || item.reason, 'preview-context'))
1864
+ panel.append(lead)
1865
+ dialogText.dataset.format = 'handoff'
1866
+ dialogText.replaceChildren(panel)
1867
+
1868
+ const canApply = actionableSkill(item)
1869
+ skillApply.hidden = !canApply
1870
+ skillApply.dataset.action = item.action
1871
+ byId('skill-apply-label').textContent = item.action === 'update'
1872
+ ? '更新并切换'
1873
+ : item.action === 'reuse-native' ? '登记复用' : '启用技能'
1874
+ skillDeactivate.hidden = !asset.handoff?.activationId
1875
+ skillUndo.hidden = !(asset.handoff?.activationId && asset.handoff?.canUndo)
1876
+ }
1877
+
1878
+ async function openSkillManager(asset) {
1879
+ if (!current || dialog.open) return
1880
+ const project = current
1881
+ const epoch = showDialog('skill', `技能 · ${materialName(asset)}`, '核对 DSH 名称、启用范围和完整包内容。', '正在核对技能包…', 'skill')
1882
+ skillManagerAsset = asset
1883
+ skillManagerProject = project
1884
+ try {
1885
+ const result = await api('preview-skill-activation', { projectId: project.id, assetIds: [asset.id] })
1886
+ if (!dialog.open || dialogEpoch !== epoch) return
1887
+ renderSkillManager(result, asset)
1888
+ } catch (error) {
1889
+ if (dialog.open && dialogEpoch === epoch) dialogText.textContent = error.message
1890
+ }
1891
+ }
1892
+
1893
+ function openManagedSkill(asset) {
1894
+ if (!current || dialog.open) return
1895
+ const project = current
1896
+ showDialog('skill', `技能 · ${materialName(asset)}`, '核对已保存登记;来源不可扫描时仍可停用。', '', 'skill')
1897
+ skillManagerAsset = asset
1898
+ skillManagerProject = project
1899
+ renderSkillManager({
1900
+ ticket: undefined,
1901
+ items: [{
1902
+ assetId: asset.id,
1903
+ name: asset.name,
1904
+ dshName: asset.handoff.dshName,
1905
+ action: 'manage',
1906
+ label: asset.handoff.label,
1907
+ detail: asset.handoff.detail,
1908
+ reason: asset.handoff.reason,
1909
+ allowed: false,
1910
+ current: true,
1911
+ activationId: asset.handoff.activationId,
1912
+ scopeRoot: detail?.skillProjectRoot,
1913
+ }],
1914
+ }, asset)
1915
+ }
1916
+
1917
+ async function applyManagedSkill() {
1918
+ if (!skillPreviewTicket || dialogBusy) return
1919
+ setDialogBusy(true)
1920
+ status('正在保存完整技能包…', false, 'dialog-status')
1921
+ try {
1922
+ const applied = await api('apply-skill-activation', { ticket: skillPreviewTicket })
1923
+ const failed = applied.items.find(item => !item.applied)
1924
+ if (failed) throw new Error(failed.reason || `${failed.name || '技能'} 未启用。`)
1925
+ skillPreviewTicket = undefined
1926
+ dialog.close()
1927
+ await reloadCurrentDetail(true)
1928
+ status(appliedSkillSummary(applied))
1929
+ } catch (error) {
1930
+ status(error.message, true, 'dialog-status')
1931
+ } finally {
1932
+ setDialogBusy(false)
1933
+ }
1934
+ }
1935
+
1936
+ async function deactivateManagedSkill() {
1937
+ const asset = skillManagerAsset
1938
+ const project = skillManagerProject
1939
+ if (!asset?.handoff?.activationId || !project || dialogBusy) return
1940
+ setDialogBusy(true)
1941
+ try {
1942
+ await api('deactivate-skill-activation', {
1943
+ projectId: project.id, activationId: asset.handoff.activationId,
1944
+ })
1945
+ dialog.close()
1946
+ await reloadCurrentDetail(true)
1947
+ status('已停用当前项目的技能登记;来源文件和 DSH 其他目录未改动。')
1948
+ } catch (error) {
1949
+ status(error.message, true, 'dialog-status')
1950
+ } finally {
1951
+ setDialogBusy(false)
1952
+ }
1953
+ }
1954
+
1955
+ async function undoManagedSkill() {
1956
+ const asset = skillManagerAsset
1957
+ const project = skillManagerProject
1958
+ if (!asset?.handoff?.activationId || !project || dialogBusy) return
1959
+ setDialogBusy(true)
1960
+ try {
1961
+ await api('undo-skill-activation', {
1962
+ projectId: project.id, activationId: asset.handoff.activationId,
1963
+ })
1964
+ dialog.close()
1965
+ await reloadCurrentDetail(true)
1966
+ status('已恢复上一版技能快照。')
1967
+ } catch (error) {
1968
+ status(error.message, true, 'dialog-status')
1969
+ } finally {
1970
+ setDialogBusy(false)
1971
+ }
1972
+ }
1973
+
1974
+ async function importSession() {
1975
+ if (!ticket || dialogBusy || importButton.hidden) return
1976
+ if (dialogSkillIds.size) {
1977
+ await beginSkillActivation('draft')
1978
+ return
1979
+ }
1980
+ await completeHandoff('draft', [])
1981
+ }
1982
+
1983
+ async function recoverDraftSession() {
1984
+ if (!ticket || !draftRecovery || dialogBusy) return
1985
+ setDialogBusy(true)
1986
+ try {
1987
+ await requestParent('recover-draft', { sessionId: draftRecovery }, ticket)
1988
+ dialog.close()
1989
+ } catch (error) {
1990
+ status(error.message, true, 'dialog-status')
1991
+ } finally {
1992
+ setDialogBusy(false)
1993
+ }
1994
+ }
1995
+
1996
+ function showDownload({ filename, markdown }) {
1997
+ if (typeof filename !== 'string' || typeof markdown !== 'string') throw new Error('未收到可导出的 Markdown。')
1998
+ clearDownload()
1999
+ byId('export-text').textContent = markdown
2000
+ byId('export-output').hidden = false
2001
+ try {
2002
+ downloadUrl = URL.createObjectURL(new Blob([markdown], { type: 'text/markdown;charset=utf-8' }))
2003
+ exportDownload.href = downloadUrl
2004
+ exportDownload.download = filename
2005
+ exportDownload.hidden = false
2006
+ exportDownload.click()
2007
+ status(`已生成 ${filename}。`, false, 'dialog-status')
2008
+ } catch {
2009
+ byId('export-output').open = true
2010
+ status(`已生成 ${filename}。可复制下方 Markdown。`, false, 'dialog-status')
2011
+ }
2012
+ }
2013
+
2014
+ function selectedNativeSession() {
2015
+ return nativeSessions.find(session => session.id === sessionSelect.value)
2016
+ }
2017
+
2018
+ async function updateNativeSession() {
2019
+ sessionTraceRequest?.abort()
2020
+ sessionSourceRecord.replaceChildren()
2021
+ exportTrace.checked = false
2022
+ exportTraceOption.hidden = true
2023
+ const session = selectedNativeSession()
2024
+ byId('session-path').textContent = session?.path ?? ''
2025
+ if (!session) return
2026
+ const request = new AbortController()
2027
+ sessionTraceRequest = request
2028
+ const url = `./session-trace?${new URLSearchParams({ sessionId: session.id })}`
2029
+ try {
2030
+ const response = await fetch(url, { signal: request.signal, headers: { Accept: 'application/json' } })
2031
+ if (response.status === 404) return
2032
+ if (!response.ok) throw new Error('无法读取来源记录。')
2033
+ const { trace, sourceStats, traceCounts } = await response.json()
2034
+ if (request.signal.aborted || !Array.isArray(trace) || (!trace.length && !sourceStats)) return
2035
+ sessionSourceRecord.append(renderSourceStats(sourceStats, traceCounts))
2036
+ if (trace.length) {
2037
+ sessionSourceRecord.append(sessionTraceDisclosure(trace))
2038
+ exportTraceOption.hidden = false
2039
+ }
2040
+ } catch {
2041
+ if (!request.signal.aborted) sessionSourceRecord.append(text('p', '暂时无法读取来源记录。', 'muted'))
2042
+ }
2043
+ }
2044
+
2045
+ async function chooseNativeSession() {
2046
+ showDialog('session', '导出 DSH 会话', '可查阅已保存的来源记录,或将会话保存为 Markdown。', '正在读取 DSH 会话…')
2047
+ setDialogBusy(true)
2048
+ try {
2049
+ const result = await requestParent('sessions', {})
2050
+ nativeSessions = result.sessions
2051
+ if (!nativeSessions.length) {
2052
+ dialogText.textContent = '暂无可导出的 DSH 会话。'
2053
+ return
2054
+ }
2055
+ const titles = new Map()
2056
+ for (const { title } of nativeSessions) titles.set(title, (titles.get(title) ?? 0) + 1)
2057
+ sessionSelect.replaceChildren(...nativeSessions.map(session => {
2058
+ const title = session.title || '未命名会话'
2059
+ const suffix = titles.get(session.title) > 1 && session.path ? ` · ${shortPath(session.path)}` : ''
2060
+ return new Option(title + suffix, session.id)
2061
+ }))
2062
+ void updateNativeSession()
2063
+ dialogText.hidden = true
2064
+ byId('session-choice').hidden = false
2065
+ exportButton.hidden = false
2066
+ exportShareButton.hidden = false
2067
+ } catch (error) {
2068
+ dialogText.hidden = true
2069
+ status(error.message, true, 'dialog-status')
2070
+ } finally {
2071
+ setDialogBusy(false)
2072
+ }
2073
+ }
2074
+
2075
+ async function exportMarkdown(format = 'local') {
2076
+ if (dialogBusy || exportButton.hidden) return
2077
+ setDialogBusy(true)
2078
+ status(`正在生成${format === 'share' ? '分享版' : '本机版'} Markdown…`, false, 'dialog-status')
2079
+ const includeTrace = exportTraceOption.hidden ? false : exportTrace.checked
2080
+ try {
2081
+ if (dialogMode === 'session') {
2082
+ const session = selectedNativeSession()
2083
+ if (!session) throw new Error('请选择要导出的 DSH 会话。')
2084
+ const result = await requestParent('session-export', { sessionId: session.id, path: session.path })
2085
+ showDownload(await api('export-session', { sessionId: session.id, conversation: result.conversation, format, includeTrace }))
2086
+ } else if (ticket) {
2087
+ showDownload(await api('export', { ticket, format, includeTrace }))
2088
+ }
2089
+ } catch (error) {
2090
+ status(error.message, true, 'dialog-status')
2091
+ } finally {
2092
+ setDialogBusy(false)
2093
+ }
2094
+ }
2095
+
2096
+ // Paths are only opened after the Host re-checks them against the current
2097
+ // project. The panel never passes a raw path to the shell by itself.
2098
+ async function openPath({ projectId = current?.id, label, assetId, referenceId, directory = false }) {
2099
+ if (!projectId) return
2100
+ const statusId = dialog.open ? 'dialog-status' : 'status'
2101
+ try {
2102
+ const result = await requestParent('open-path', { projectId, directory, assetId, referenceId, bridgeNonce: nonce })
2103
+ status(`已在 DSH 中${result.revealed ? '定位' : '打开'}${label ? `「${label}」` : ''}。`, false, statusId)
2104
+ } catch (error) {
2105
+ status(`${error.message} 可复制路径后手动打开。`, true, statusId)
2106
+ }
2107
+ }
2108
+
2109
+ function pathActions({ label, path, assetId, directory = false }) {
2110
+ const group = text('span', '', 'path-actions')
2111
+ const open = text('button', '', 'path-open')
2112
+ open.type = 'button'
2113
+ open.append(icon('folder'), text('span', '打开'))
2114
+ open.setAttribute('aria-label', `在 DSH 中打开${label ? ` ${label}` : ''}`)
2115
+ open.title = path || label || '打开'
2116
+ open.addEventListener('click', () => { void openPath({ label, assetId, directory }) })
2117
+ const copy = text('button', '', 'path-copy')
2118
+ copy.type = 'button'
2119
+ copy.append(icon('copy'))
2120
+ copy.setAttribute('aria-label', `复制${label ? ` ${label}` : ''}路径`)
2121
+ copy.title = '复制路径'
2122
+ copy.addEventListener('click', async () => {
2123
+ try {
2124
+ await navigator.clipboard.writeText(path ?? '')
2125
+ status('路径已复制。')
2126
+ } catch {
2127
+ status('无法访问剪贴板,请手动选择路径复制。', true)
2128
+ }
2129
+ })
2130
+ group.append(open, copy)
2131
+ return group
2132
+ }
2133
+
2134
+ async function copyProjectPath() {
2135
+ if (!current) return
2136
+ const button = byId('copy-path')
2137
+ try {
2138
+ await navigator.clipboard.writeText(current.cwd)
2139
+ button.dataset.state = 'copied'
2140
+ button.replaceChildren(icon('check'))
2141
+ button.setAttribute('aria-label', '已复制工作目录')
2142
+ setTimeout(() => {
2143
+ delete button.dataset.state
2144
+ button.replaceChildren(icon('copy'))
2145
+ button.setAttribute('aria-label', '复制工作目录')
2146
+ }, 1600)
2147
+ } catch {
2148
+ const selection = window.getSelection()
2149
+ if (!selection) return
2150
+ const range = document.createRange()
2151
+ range.selectNodeContents(byId('project-path'))
2152
+ selection.removeAllRanges()
2153
+ selection.addRange(range)
2154
+ status('已选中工作目录,按 Ctrl+C 或 ⌘C 复制。')
2155
+ }
2156
+ }
2157
+
2158
+ function wireClear(input, action) {
2159
+ input.parentElement.querySelector('.clear-search').addEventListener('click', () => {
2160
+ input.value = ''
2161
+ action()
2162
+ input.focus()
2163
+ })
2164
+ }
2165
+
2166
+ window.addEventListener('message', event => {
2167
+ if (event.source !== window.parent || (parentOrigin !== '*' && event.origin !== parentOrigin)) return
2168
+ const data = event.data
2169
+ if (!pending || data?.type !== 'dsh-agent-bridge:result' || pending.requestId !== data.requestId) return
2170
+ const request = pending
2171
+ pending = undefined
2172
+ clearTimeout(request.timer)
2173
+ if (data.ok) request.resolve(data)
2174
+ else request.reject(Object.assign(new Error(data.error || 'DSH 暂无法完成此操作。'), {
2175
+ recoverySessionId: typeof data.recoverySessionId === 'string' ? data.recoverySessionId : undefined,
2176
+ }))
2177
+ })
2178
+ refreshButton.addEventListener('click', () => refresh(true))
2179
+ projectSearch.addEventListener('input', event => {
2180
+ if (!event.isComposing) updateProjectSearch()
2181
+ })
2182
+ projectSearch.addEventListener('compositionend', updateProjectSearch)
2183
+ projectSearch.addEventListener('keydown', event => {
2184
+ if (event.isComposing || event.keyCode === 229 || !['ArrowDown', 'Enter'].includes(event.key)) return
2185
+ const first = projectList.querySelector('.project')
2186
+ if (!first) return
2187
+ event.preventDefault()
2188
+ first.focus()
2189
+ if (event.key === 'Enter') first.click()
2190
+ })
2191
+ agentFilter.addEventListener('click', () => {
2192
+ if (agentPopover.hidden) openAgentPicker()
2193
+ else closeAgentPicker(true)
2194
+ })
2195
+ agentFilter.addEventListener('keydown', event => {
2196
+ if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return
2197
+ event.preventDefault()
2198
+ openAgentPicker()
2199
+ })
2200
+ agentOptions.addEventListener('keydown', navigateAgents)
2201
+ agentOptions.addEventListener('pointermove', event => {
2202
+ const option = event.target.closest('.agent-option')
2203
+ if (option) activateAgentOption(availableAgents.indexOf(option.dataset.agent), false)
2204
+ })
2205
+ agentOptions.addEventListener('click', event => {
2206
+ const option = event.target.closest('.agent-option')
2207
+ if (option) chooseAgent(availableAgents.indexOf(option.dataset.agent))
2208
+ })
2209
+ document.addEventListener('pointerdown', event => {
2210
+ if (!agentPicker.contains(event.target)) closeAgentPicker()
2211
+ })
2212
+ document.addEventListener('focusin', event => {
2213
+ if (!agentPicker.contains(event.target)) closeAgentPicker()
2214
+ })
2215
+ window.addEventListener('resize', positionAgentPicker)
2216
+ window.addEventListener('scroll', positionAgentPicker, { passive: true })
2217
+ assetSearch.addEventListener('input', renderAssets)
2218
+ wireClear(projectSearch, updateProjectSearch)
2219
+ wireClear(assetSearch, renderAssets)
2220
+ draftWorkflow.addEventListener('toggle', renderAssets)
2221
+ globalLibrary.addEventListener('toggle', renderGlobalMaterials)
2222
+ projectManage.addEventListener('click', () => {
2223
+ managingProjects = !managingProjects
2224
+ selectedProjects.clear()
2225
+ renderProjects()
2226
+ })
2227
+ selectVisible.addEventListener('change', () => {
2228
+ selectedProjects.clear()
2229
+ if (selectVisible.checked) {
2230
+ for (const project of filteredProjects()) selectedProjects.add(project.id)
2231
+ }
2232
+ renderProjects()
2233
+ })
2234
+ bulkArchive.addEventListener('click', () => updateProjectArchive([...selectedProjects], projectState !== 'archived'))
2235
+ archiveAction.addEventListener('click', () => {
2236
+ if (current) void updateProjectArchive([current.id], !current.archived)
2237
+ })
2238
+ projectPin.addEventListener('click', toggleProjectPin)
2239
+ projectUndo.addEventListener('click', () => {
2240
+ if (undoArchive) void updateProjectArchive(undoArchive.projectIds, undoArchive.archived, true)
2241
+ })
2242
+ for (const button of projectFilters) {
2243
+ button.addEventListener('click', () => {
2244
+ projectState = button.dataset.projectState
2245
+ projectList.scrollTop = 0
2246
+ updateProjectView()
2247
+ })
2248
+ }
2249
+ document.addEventListener('keydown', event => {
2250
+ if (event.key !== '/' || event.ctrlKey || event.metaKey || event.altKey || dialog.open || !agentPopover.hidden
2251
+ || event.target.matches?.('input, select, textarea, [contenteditable]')) return
2252
+ event.preventDefault()
2253
+ projectSearch.focus()
2254
+ })
2255
+ projectList.addEventListener('keydown', event => {
2256
+ const buttons = [...projectList.querySelectorAll('.project')]
2257
+ const currentIndex = buttons.indexOf(event.target)
2258
+ if (currentIndex < 0) return
2259
+ let nextIndex
2260
+ if (event.key === 'ArrowDown') nextIndex = Math.min(buttons.length - 1, currentIndex + 1)
2261
+ if (event.key === 'ArrowUp') nextIndex = Math.max(0, currentIndex - 1)
2262
+ if (event.key === 'Home') nextIndex = 0
2263
+ if (event.key === 'End') nextIndex = buttons.length - 1
2264
+ if (nextIndex === undefined) return
2265
+ event.preventDefault()
2266
+ buttons[nextIndex].focus()
2267
+ })
2268
+ historyOption.addEventListener('change', () => {
2269
+ includeHistory = historyOption.checked
2270
+ renderSelection()
2271
+ void saveProjectSelection()
2272
+ })
2273
+ byId('copy-path').addEventListener('click', copyProjectPath)
2274
+ byId('open-path').addEventListener('click', () => {
2275
+ if (!current) return
2276
+ void openPath({ label: '工作目录', path: current.cwd, directory: true })
2277
+ })
2278
+ byId('preview').addEventListener('click', preview)
2279
+ byId('native-export').addEventListener('click', chooseNativeSession)
2280
+ browseHistory.addEventListener('click', chooseSourceConversation)
2281
+ byId('history-back-button').addEventListener('click', showHistoryResults)
2282
+ function searchHistory() {
2283
+ historyChosenId = undefined
2284
+ historyLimit = 30
2285
+ renderHistoryResults()
2286
+ }
2287
+ historySearch.addEventListener('input', searchHistory)
2288
+ wireClear(historySearch, searchHistory)
2289
+ byId('history-more').addEventListener('click', () => {
2290
+ const index = historyResults.childElementCount
2291
+ historyLimit += 30
2292
+ renderHistoryResults()
2293
+ historyResults.children[index]?.querySelector('button')?.focus()
2294
+ })
2295
+ historyImport.addEventListener('click', importSourceConversation)
2296
+ sessionSelect.addEventListener('change', clearDownload)
2297
+ sessionSelect.addEventListener('change', updateNativeSession)
2298
+ dialogClose.addEventListener('click', () => dialog.close())
2299
+ dialog.addEventListener('click', event => {
2300
+ if (event.target !== dialog || dialogBusy) return
2301
+ const bounds = dialog.getBoundingClientRect()
2302
+ if (event.clientX < bounds.left || event.clientX > bounds.right
2303
+ || event.clientY < bounds.top || event.clientY > bounds.bottom) dialog.close()
2304
+ })
2305
+ dialog.addEventListener('cancel', event => { if (dialogBusy) event.preventDefault() })
2306
+ dialog.addEventListener('close', () => {
2307
+ ++dialogEpoch
2308
+ if (!dialog.open) sessionTraceRequest?.abort()
2309
+ if (activateDialog.open) activateDialog.close()
2310
+ clearDownload()
2311
+ liveState('正在恢复实时扫描')
2312
+ schedulePoll(0)
2313
+ })
2314
+ importButton.addEventListener('click', importSession)
2315
+ recoverDraftButton.addEventListener('click', recoverDraftSession)
2316
+ skillApply.addEventListener('click', applyManagedSkill)
2317
+ skillUndo.addEventListener('click', undoManagedSkill)
2318
+ skillDeactivate.addEventListener('click', deactivateManagedSkill)
2319
+ activateConfirm.addEventListener('click', confirmSkillActivation)
2320
+ activateText.addEventListener('click', continueWithTextOnly)
2321
+ activateClose.addEventListener('click', () => { if (!activateConfirm.disabled) activateDialog.close() })
2322
+ activateDialog.addEventListener('cancel', event => { if (activateConfirm.disabled) event.preventDefault() })
2323
+ activateDialog.addEventListener('click', event => {
2324
+ if (event.target === activateDialog && !activateConfirm.disabled) activateDialog.close()
2325
+ })
2326
+ exportButton.addEventListener('click', () => { void exportMarkdown('local') })
2327
+ exportShareButton.addEventListener('click', () => { void exportMarkdown('share') })
2328
+ document.addEventListener('visibilitychange', () => schedulePoll(0))
2329
+ for (const button of themeOptions) button.addEventListener('click', () => setTheme(button.dataset.themeChoice))
2330
+ let savedTheme
2331
+ try { savedTheme = localStorage.getItem(themeKey) } catch { /* Use the default theme. */ }
2332
+ setTheme(savedTheme, false)
2333
+ renderAgentPicker()
2334
+ void refresh(false).finally(() => schedulePoll(0))