@wwwfz/dsh-agent-bridge 0.8.3 → 0.10.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 (45) hide show
  1. package/README.md +132 -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 +999 -605
  7. package/src/client.js +883 -4
  8. package/src/config.js +88 -88
  9. package/src/conversation-readers.js +198 -0
  10. package/src/conversation-store.js +583 -0
  11. package/src/export.js +273 -12
  12. package/src/index.js +282 -136
  13. package/src/native-transcript.js +217 -0
  14. package/src/project-archive.js +145 -145
  15. package/src/projects.js +1837 -980
  16. package/src/session-import.js +138 -93
  17. package/src/session-trace.js +121 -0
  18. package/src/skill-handoff.js +1327 -0
  19. package/src/skill-package.js +417 -0
  20. package/src/skill-provider.js +249 -0
  21. package/src/watch.js +319 -309
  22. package/web/Geist-OFL.txt +93 -93
  23. package/web/agent-icons/NOTICE.md +19 -19
  24. package/web/agent-icons/antigravity.svg +76 -76
  25. package/web/agent-icons/claude.svg +3 -3
  26. package/web/agent-icons/dsh.svg +58 -58
  27. package/web/agent-icons/licenses/copilot.txt +21 -21
  28. package/web/agent-icons/licenses/dsh.txt +21 -21
  29. package/web/agent-icons/licenses/gemini.txt +201 -201
  30. package/web/agent-icons/licenses/opencode.txt +21 -21
  31. package/web/agent-icons/licenses/qoder-notice.txt +18 -18
  32. package/web/agent-icons/licenses/qoder.txt +22 -22
  33. package/web/agent-icons/licenses/qwen.txt +202 -202
  34. package/web/agent-icons/qoder.svg +4 -4
  35. package/web/agent-icons/qwen.svg +5 -5
  36. package/web/agent-icons/workbuddy.svg +29 -29
  37. package/web/inline-process.css +22 -0
  38. package/web/markdown.js +225 -0
  39. package/web/panel.css +168 -151
  40. package/web/panel.html +82 -43
  41. package/web/panel.js +1316 -93
  42. package/web/project-context.js +25 -25
  43. package/web/reader.css +259 -0
  44. package/web/vendor/markdown-it-LICENSE.txt +156 -0
  45. package/web/vendor/markdown-it.mjs +3064 -0
package/web/panel.js CHANGED
@@ -1,15 +1,29 @@
1
1
  import { describeProjectContext } from './project-context.js'
2
+ import { isMarkdownFile, renderMarkdown } from './markdown.js'
2
3
 
3
4
  const byId = id => document.getElementById(id)
4
5
  const nonce = document.querySelector('meta[name=bridge-nonce]').content
5
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')
6
13
  const importButton = byId('import')
7
14
  const recoverDraftButton = byId('recover-draft')
8
15
  const exportButton = byId('export')
16
+ const exportShareButton = byId('export-share')
17
+ const exportTraceOption = byId('export-trace-option')
18
+ const exportTrace = byId('export-trace')
9
19
  const exportDownload = byId('export-download')
20
+ const skillUndo = byId('skill-undo')
21
+ const skillDeactivate = byId('skill-deactivate')
22
+ const skillApply = byId('skill-apply')
10
23
  const dialogClose = byId('dialog-close')
11
24
  const dialogText = byId('dialog-text')
12
25
  const sessionSelect = byId('session-select')
26
+ const sessionSourceRecord = byId('session-source-record')
13
27
  const historySearch = byId('history-search')
14
28
  const historyResults = byId('history-results')
15
29
  const historyImport = byId('history-import')
@@ -18,7 +32,7 @@ const agentFilter = byId('agent-filter')
18
32
  const agentPicker = byId('agent-picker')
19
33
  const agentPopover = byId('agent-popover')
20
34
  const agentOptions = byId('agent-options')
21
- const themeOptions = [...document.querySelectorAll('[data-theme-choice]')]
35
+ const appearance = byId('appearance')
22
36
  const themeKey = 'dsh-agent-bridge.theme'
23
37
  const projectSearch = byId('project-search')
24
38
  const assetSearch = byId('asset-search')
@@ -56,6 +70,7 @@ const materialGroups = [
56
70
  ['used', '会话中提及的 Skills', '在这个项目的近期对话中有记录。'],
57
71
  ['notes', '其他项目笔记', '经验、决策和存档,可按需带入。'],
58
72
  ['skills', '其他项目 Skills', '放在项目目录里,按任务选用。'],
73
+ ['managed', '已启用的项目 Skills', '来源不可再扫描时,私有快照仍可管理和停用。'],
59
74
  ]
60
75
  const globalGroups = [
61
76
  ['guides', '通用指引'],
@@ -100,18 +115,33 @@ let dialogMode
100
115
  let dialogEpoch = 0
101
116
  let dialogBusy = false
102
117
  let nativeSessions = []
118
+ let sessionTraceRequest
103
119
  let recentRevision = 0
104
120
  let recentKey = ''
105
121
  let historyProject
106
122
  let historySessions
123
+ let historyUnavailable = []
124
+ let historyCursor
125
+ let historyPaging = false
107
126
  let historyLimit = 30
108
127
  let historyChosenId
109
128
  let historyTicket
129
+ let historySnapshotId
130
+ let historyImportStarted = false
110
131
  let importedSessionId
111
132
  let draftRecovery
112
133
  let historyPreview = 0
113
134
  let downloadUrl
114
135
  let requestNumber = 0
136
+ let dialogSkillCandidates = []
137
+ let dialogSkillIds = new Set()
138
+ let skillPreviewTicket
139
+ let skillManagerAsset
140
+ let skillManagerProject
141
+ let previewInput
142
+ let activationReview
143
+ let activationSummary = ''
144
+ let exportHasTrace = false
115
145
 
116
146
  const clockFormat = new Intl.DateTimeFormat('zh-CN', { timeStyle: 'medium', hourCycle: 'h23' })
117
147
  const historyDateFormat = new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium', timeStyle: 'short' })
@@ -126,6 +156,52 @@ const text = (tag, content, className) => {
126
156
  return element
127
157
  }
128
158
 
159
+ function renderProjectMarkdown(source, projectId, references = []) {
160
+ const links = new Map(references.map(reference => [reference.href, reference]))
161
+ return renderMarkdown(source, document, href => {
162
+ const reference = links.get(href)
163
+ if (!reference) return undefined
164
+ const container = text('span', '', 'md-reference')
165
+ const label = text('button', '', 'md-link md-reference-open')
166
+ label.type = 'button'
167
+ label.title = reference.path
168
+ label.addEventListener('click', () => {
169
+ if (reference.id) void openPath({ projectId, label: label.textContent, referenceId: reference.id })
170
+ else status(reference.error, true, 'dialog-status')
171
+ })
172
+ const copy = text('button', '', 'path-copy')
173
+ copy.type = 'button'
174
+ copy.append(icon('copy'))
175
+ copy.title = '复制链接路径'
176
+ copy.setAttribute('aria-label', `复制链接路径 ${reference.path}`)
177
+ copy.addEventListener('click', async () => {
178
+ try {
179
+ await navigator.clipboard.writeText(reference.path)
180
+ status('链接路径已复制。', false, 'dialog-status')
181
+ } catch {
182
+ const path = text('code', reference.path, 'preview-source')
183
+ const selection = window.getSelection()
184
+ status('请手动复制链接路径。', true, 'dialog-status')
185
+ byId('dialog-status').append(' ', path)
186
+ const range = document.createRange()
187
+ range.selectNodeContents(path)
188
+ selection?.removeAllRanges()
189
+ selection?.addRange(range)
190
+ }
191
+ })
192
+ container.append(label, copy)
193
+ return { container, label }
194
+ })
195
+ }
196
+
197
+ function markdownBody(source, className, projectId, references) {
198
+ const body = document.createElement('div')
199
+ body.className = className
200
+ body.dataset.format = 'markdown'
201
+ body.append(renderProjectMarkdown(source, projectId, references))
202
+ return body
203
+ }
204
+
129
205
  function icon(name, className = '') {
130
206
  const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
131
207
  svg.setAttribute('class', className ? `icon ${className}` : 'icon')
@@ -166,11 +242,9 @@ function agentLabel(agent, className = '', label = agentName(agent)) {
166
242
  }
167
243
 
168
244
  function setTheme(value, remember = true) {
169
- const theme = ['blue', 'white', 'black'].includes(value) ? value : 'blue'
245
+ const theme = ['white', 'mist', 'blue', 'black'].includes(value) ? value : 'white'
170
246
  document.documentElement.dataset.theme = theme
171
- for (const button of themeOptions) {
172
- button.setAttribute('aria-pressed', String(button.dataset.themeChoice === theme))
173
- }
247
+ appearance.value = theme
174
248
  if (remember) {
175
249
  try { localStorage.setItem(themeKey, theme) } catch { /* Theme is still applied to this panel. */ }
176
250
  }
@@ -399,10 +473,11 @@ function renderArchiveControls(matches) {
399
473
  archiveAction.disabled = archiveBusy || detailLoading || !current
400
474
  }
401
475
 
402
- function projectRow(project, matches) {
476
+ function projectRow(project, matches, showPath) {
403
477
  const button = document.createElement('button')
404
478
  button.type = 'button'
405
479
  button.className = 'project'
480
+ if (showPath) button.classList.add('project-show-path')
406
481
  button.id = `project-${project.id}`
407
482
  button.setAttribute('aria-pressed', String(current?.id === project.id))
408
483
  button.title = project.cwd
@@ -461,10 +536,16 @@ function renderProjects() {
461
536
  byId('project-count').textContent = matches.length === total ? `${total} 项` : `${matches.length} / ${total}`
462
537
  renderArchiveControls(matches)
463
538
  const items = []
539
+ const names = new Set()
540
+ const duplicateNames = new Set()
541
+ for (const project of matches) {
542
+ if (names.has(project.name)) duplicateNames.add(project.name)
543
+ names.add(project.name)
544
+ }
464
545
  for (const [label, group] of projectGroups(matches)) {
465
546
  if (!group.length) continue
466
547
  if (label) items.push(text('h3', label, 'project-group-heading'))
467
- for (const project of group) items.push(projectRow(project, matches))
548
+ for (const project of group) items.push(projectRow(project, matches, duplicateNames.has(project.name)))
468
549
  }
469
550
  const focused = projectList.contains(document.activeElement) ? document.activeElement.id : ''
470
551
  const scroll = projectList.scrollTop
@@ -633,6 +714,69 @@ function matchesMaterial(asset, query) {
633
714
  .some(value => value?.toLowerCase().includes(query))
634
715
  }
635
716
 
717
+ function actionableSkill(candidate) {
718
+ return Boolean(candidate?.allowed && ['enable', 'update', 'reuse-native'].includes(candidate.action))
719
+ }
720
+
721
+ function skillStatusNode(status) {
722
+ const node = text('span', status?.label || '仅可带入说明', 'skill-status')
723
+ node.dataset.state = status?.state || 'handoff'
724
+ node.title = status?.detail || status?.reason || ''
725
+ return node
726
+ }
727
+
728
+ function syncSkillChoiceButtons() {
729
+ const count = dialogSkillIds.size
730
+ if (historyImport.hidden === false) {
731
+ byId('history-import-label').textContent = importedSessionId
732
+ ? '打开已迁入会话'
733
+ : count ? `启用 ${count} 项并继续` : '迁入并继续'
734
+ }
735
+ if (importButton.hidden === false) {
736
+ importButton.replaceChildren(
737
+ document.createTextNode(count ? '启用并继续' : '打开新对话'),
738
+ icon('arrow'),
739
+ )
740
+ }
741
+ }
742
+
743
+ function renderSkillChoices(candidates, { history = false } = {}) {
744
+ dialogSkillCandidates = Array.isArray(candidates) ? candidates : []
745
+ dialogSkillIds = new Set()
746
+ if (!dialogSkillCandidates.length) return null
747
+ const panel = text('section', '', 'skill-choice-panel')
748
+ panel.setAttribute('aria-label', '沿用技能(可选)')
749
+ const heading = text('div', '', 'skill-choice-heading')
750
+ heading.append(
751
+ text('strong', '沿用技能(可选)'),
752
+ text('span', history ? '从历史记录匹配到本机技能;不会自动选择。' : '选中后由 DSH 原生技能目录调用。'),
753
+ )
754
+ const list = text('div', '', 'skill-choice-list')
755
+ for (const candidate of dialogSkillCandidates) {
756
+ const label = text('label', '', 'skill-choice')
757
+ const checkbox = document.createElement('input')
758
+ checkbox.type = 'checkbox'
759
+ checkbox.disabled = !actionableSkill(candidate)
760
+ checkbox.setAttribute('aria-label', `${candidate.name || candidate.dshName || '技能'}:${candidate.label}`)
761
+ checkbox.addEventListener('change', () => {
762
+ if (checkbox.checked) dialogSkillIds.add(candidate.assetId)
763
+ else dialogSkillIds.delete(candidate.assetId)
764
+ label.classList.toggle('selected', checkbox.checked)
765
+ syncSkillChoiceButtons()
766
+ })
767
+ const detail = text('span', '', 'skill-choice-text')
768
+ detail.append(
769
+ text('span', candidate.name || candidate.dshName || '技能', 'skill-choice-name'),
770
+ text('span', [candidate.label, candidate.detail || candidate.reason].filter(Boolean).join(' · '), 'skill-choice-note'),
771
+ )
772
+ label.append(checkbox, detail)
773
+ list.append(label)
774
+ }
775
+ panel.append(heading, list)
776
+ syncSkillChoiceButtons()
777
+ return panel
778
+ }
779
+
636
780
  function renderGlobalCount() {
637
781
  const assets = context.entries.filter(asset => asset.global)
638
782
  const query = assetSearch.value.trim().toLowerCase()
@@ -650,6 +794,7 @@ function makeMaterialRow(asset) {
650
794
  checkbox.className = 'asset-check'
651
795
  checkbox.id = `asset-${asset.id}`
652
796
  checkbox.checked = selected.has(asset.id)
797
+ checkbox.disabled = Boolean(asset.managedOnly)
653
798
  row.dataset.selected = String(checkbox.checked)
654
799
  checkbox.addEventListener('change', () => {
655
800
  if (checkbox.checked && selected.size >= 24) {
@@ -670,6 +815,12 @@ function makeMaterialRow(asset) {
670
815
  const title = text('span', name, 'asset-title')
671
816
  const meta = text('span', '', 'asset-meta')
672
817
  if (asset.agent) meta.append(agentLabel(asset.agent))
818
+ if (asset.kind === 'skill' && asset.handoff) {
819
+ meta.append(skillStatusNode(asset.handoff))
820
+ const note = asset.handoff.reason || (asset.handoff.sourceChanged
821
+ || asset.handoff.state === 'pending' || asset.handoff.manualOnly ? asset.handoff.detail : '')
822
+ if (note) meta.append(text('span', note, 'asset-status-note'))
823
+ }
673
824
  if (!asset.global && context.suggestedIds.includes(asset.id)) {
674
825
  meta.append(text('span', '建议带入', 'material-suggestion'))
675
826
  } else if (asset.global && asset.used) {
@@ -677,14 +828,40 @@ function makeMaterialRow(asset) {
677
828
  }
678
829
  label.append(title, meta)
679
830
  const button = text('button', '', 'asset-view')
680
- button.append(document.createTextNode('查看'), icon('chevron'))
831
+ const manageable = asset.kind === 'skill' && asset.handoff
832
+ && detail?.skillNativeAvailable && (asset.managedOnly || asset.handoff.state !== 'native')
833
+ const action = asset.handoff?.action
834
+ const actionLabel = !manageable ? '查看'
835
+ : asset.managedOnly || asset.handoff?.state === 'active' ? '管理'
836
+ : action === 'enable' ? '启用'
837
+ : action === 'preview-update' ? '更新'
838
+ : '详情'
839
+ button.append(document.createTextNode(actionLabel), icon('chevron'))
681
840
  button.type = 'button'
682
841
  button.id = `asset-view-${asset.id}`
683
- button.setAttribute('aria-label', `查看 ${name}`)
684
- button.addEventListener('click', () => viewAsset(asset))
842
+ button.setAttribute('aria-label', `${actionLabel} ${name}`)
843
+ button.addEventListener('click', () => {
844
+ if (!manageable) viewAsset(asset)
845
+ else if (asset.managedOnly) openManagedSkill(asset)
846
+ else openSkillManager(asset)
847
+ })
685
848
  const marker = text('span', '', 'asset-icon')
686
849
  marker.append(icon(asset.kind))
687
- row.append(checkbox, marker, label, button)
850
+ row.append(checkbox, marker, label)
851
+ // Global library entries are outside the selected project's asset list, so
852
+ // the Host cannot re-verify them for this project. Only project assets get
853
+ // an open action; every row keeps its checkbox and detail button.
854
+ if (!asset.global) {
855
+ const open = text('button', '', 'asset-open')
856
+ open.type = 'button'
857
+ open.append(icon('folder'))
858
+ open.id = `asset-open-${asset.id}`
859
+ open.setAttribute('aria-label', `在 DSH 中打开 ${name}`)
860
+ open.title = '在 DSH 中打开'
861
+ open.addEventListener('click', () => { void openPath({ label: name, assetId: asset.id }) })
862
+ row.append(open)
863
+ }
864
+ row.append(button)
688
865
  return row
689
866
  }
690
867
 
@@ -725,8 +902,48 @@ function renderAssets() {
725
902
 
726
903
  function applyDetail(project, loaded, preserve) {
727
904
  showProject(loaded.project ?? project)
905
+ const existingSkillIds = new Set(loaded.skills.map(skill => skill.id))
906
+ const managedOnly = (loaded.managedSkills ?? [])
907
+ .filter(item => !existingSkillIds.has(item.assetId))
908
+ .map(item => ({
909
+ id: item.assetId,
910
+ name: item.sourceName || item.dshName,
911
+ agent: 'dsh',
912
+ scope: 'project',
913
+ detail: 'Bridge 启用项',
914
+ file: item.sourceFile,
915
+ used: false,
916
+ managedOnly: true,
917
+ handoff: {
918
+ label: item.label,
919
+ state: item.state,
920
+ action: 'manage',
921
+ allowed: true,
922
+ current: item.state === 'active',
923
+ sourceChanged: item.sourceChanged,
924
+ sourceState: item.sourceState,
925
+ activationId: item.activationId,
926
+ dshName: item.dshName,
927
+ canUndo: item.canUndo,
928
+ registered: true,
929
+ discovered: item.discovered,
930
+ verified: item.verified,
931
+ invocation: item.invocation,
932
+ modelInvocable: item.modelInvocable,
933
+ userInvocable: item.userInvocable,
934
+ manualOnly: item.manualOnly,
935
+ disabled: item.disabled,
936
+ canOmitBody: item.canOmitBody,
937
+ detail: item.detail,
938
+ reason: item.detail,
939
+ },
940
+ }))
941
+ if (managedOnly.length) loaded = { ...loaded, skills: [...loaded.skills, ...managedOnly] }
728
942
  detail = loaded
729
943
  context = describeProjectContext(loaded)
944
+ for (const entry of context.entries) {
945
+ if (entry.managedOnly) entry.group = 'managed'
946
+ }
730
947
  if (!preserve) {
731
948
  const saved = projectSelections.get(project.id) ?? loaded.selection
732
949
  if (saved) {
@@ -737,7 +954,7 @@ function applyDetail(project, loaded, preserve) {
737
954
  includeHistory = false
738
955
  }
739
956
  }
740
- const available = new Set(context.entries.map(item => item.id))
957
+ const available = new Set(context.entries.filter(item => !item.managedOnly).map(item => item.id))
741
958
  selected = new Set([...selected].filter(id => available.has(id)))
742
959
  historyOption.checked = includeHistory && detail.historyCount > 0
743
960
  historyOption.disabled = detail.historyCount === 0
@@ -771,8 +988,16 @@ function showProject(project) {
771
988
  byId('project-detail').hidden = false
772
989
  }
773
990
 
991
+ const projectSwitch = byId('project-switch')
992
+ function expandProjectIndex(expand) {
993
+ projectSwitch.setAttribute('aria-expanded', String(expand))
994
+ projectSwitch.textContent = expand ? '收起项目' : '切换项目'
995
+ }
996
+ projectSwitch.addEventListener('click', () => expandProjectIndex(projectSwitch.getAttribute('aria-expanded') === 'false'))
997
+
774
998
  function revealProjectDetail() {
775
999
  if (!compactLayout.matches) return
1000
+ if (!managingProjects) expandProjectIndex(false)
776
1001
  const heading = byId('project-name')
777
1002
  heading.focus({ preventScroll: true })
778
1003
  heading.closest('.detail').scrollIntoView({ block: 'start', behavior: reducedMotion.matches ? 'instant' : 'smooth' })
@@ -830,7 +1055,7 @@ async function loadRecentConversations(project) {
830
1055
  }
831
1056
  if (!recentKey) recentStatus.textContent = '正在查找最近对话…'
832
1057
  try {
833
- const { sessions, total } = await api('list-conversations', { projectId: project.id, recent: true })
1058
+ const { sessions, total, hasMore, nextCursor, unavailable = [] } = await api('list-conversations', { projectId: project.id, recent: true })
834
1059
  if (!isCurrent()) return
835
1060
  const key = JSON.stringify(sessions)
836
1061
  if (key !== recentKey) {
@@ -840,11 +1065,15 @@ async function loadRecentConversations(project) {
840
1065
  ?? byId('continue-heading')).focus({ preventScroll: true })
841
1066
  recentKey = key
842
1067
  }
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
1068
+ const count = total ?? sessions.length
1069
+ const scanning = Boolean(hasMore || nextCursor)
1070
+ recentStatus.textContent = [
1071
+ sessions.length ? (current.online ? '' : '原工作目录不可访问,可在预览中选择新的迁入目录。')
1072
+ : scanning ? '已扫描的部分暂无可迁入对话。' : '这个项目还没有可迁入的对话。可以用项目资料开新对话。',
1073
+ unavailable.length ? `${unavailable.length} 条来源无法读取。` : '',
1074
+ ].filter(Boolean).join(' ')
1075
+ byId('browse-history-label').textContent = scanning ? `查看对话(已确认 ${count} 条)` : `查看全部 ${count} 条对话`
1076
+ browseHistory.hidden = count <= sessions.length && !scanning && !unavailable.length
848
1077
  } catch {
849
1078
  if (!isCurrent()) return
850
1079
  recentStatus.textContent = recentList.childElementCount
@@ -1025,26 +1254,60 @@ function setDialogBusy(busy) {
1025
1254
  importButton.disabled = busy
1026
1255
  recoverDraftButton.disabled = busy
1027
1256
  exportButton.disabled = busy
1257
+ exportShareButton.disabled = busy
1258
+ exportTrace.disabled = busy
1028
1259
  sessionSelect.disabled = busy
1029
1260
  byId('history-back-button').disabled = busy
1030
1261
  historyImport.disabled = busy
1262
+ for (const field of dialogText.querySelectorAll('.history-target-form input, .history-target-form button')) field.disabled = busy
1263
+ skillApply.disabled = busy
1264
+ skillUndo.disabled = busy
1265
+ skillDeactivate.disabled = busy
1266
+ }
1267
+
1268
+ function releaseHistoryPreview() {
1269
+ const snapshotId = historySnapshotId
1270
+ historySnapshotId = undefined
1271
+ if (snapshotId && !historyImportStarted) {
1272
+ void api('discard-conversation-preview', { snapshotId }, { keepalive: true }).catch(() => {})
1273
+ }
1274
+ historyImportStarted = false
1031
1275
  }
1032
1276
 
1033
1277
  function showDialog(mode, title, note, body, assetKind = 'memory') {
1278
+ releaseHistoryPreview()
1034
1279
  dialogMode = mode
1035
1280
  dialog.dataset.mode = mode
1036
1281
  ticket = undefined
1037
1282
  nativeSessions = []
1283
+ sessionTraceRequest?.abort()
1284
+ sessionSourceRecord.replaceChildren()
1038
1285
  historyProject = undefined
1039
1286
  historySessions = undefined
1287
+ historyUnavailable = []
1288
+ historyCursor = undefined
1289
+ historyPaging = false
1290
+ byId('history-unavailable').open = false
1040
1291
  historyChosenId = undefined
1041
1292
  historyTicket = undefined
1042
1293
  importedSessionId = undefined
1043
1294
  draftRecovery = undefined
1295
+ dialogSkillCandidates = []
1296
+ dialogSkillIds = new Set()
1297
+ skillPreviewTicket = undefined
1298
+ skillManagerAsset = undefined
1299
+ skillManagerProject = undefined
1300
+ previewInput = undefined
1301
+ activationReview = undefined
1302
+ activationSummary = ''
1303
+ if (activateDialog.open) activateDialog.close()
1044
1304
  clearDownload()
1045
1305
  byId('dialog-title').textContent = title
1046
1306
  byId('dialog-note').textContent = note
1047
- byId('dialog-mark').replaceChildren(icon(mode === 'session' ? 'download' : mode === 'asset' ? assetKind : mode === 'history' ? 'history' : 'bridge'))
1307
+ byId('dialog-mark').replaceChildren(icon(mode === 'session' ? 'download'
1308
+ : mode === 'asset' ? assetKind
1309
+ : mode === 'history' ? 'history'
1310
+ : mode === 'skill' ? 'skill' : 'bridge'))
1048
1311
  dialogText.hidden = false
1049
1312
  dialogText.dataset.format = 'plain'
1050
1313
  dialogText.textContent = body
@@ -1056,7 +1319,13 @@ function showDialog(mode, title, note, body, assetKind = 'memory') {
1056
1319
  importButton.hidden = true
1057
1320
  recoverDraftButton.hidden = true
1058
1321
  exportButton.hidden = true
1322
+ exportShareButton.hidden = true
1323
+ exportTraceOption.hidden = true
1324
+ exportTrace.checked = false
1059
1325
  historyImport.hidden = true
1326
+ skillApply.hidden = true
1327
+ skillUndo.hidden = true
1328
+ skillDeactivate.hidden = true
1060
1329
  setDialogBusy(false)
1061
1330
  if (!dialog.open) dialog.showModal()
1062
1331
  clearTimeout(pollTimer)
@@ -1072,7 +1341,7 @@ function startHistoryDialog(title, note, body) {
1072
1341
  return epoch
1073
1342
  }
1074
1343
 
1075
- const historyNote = '迁入用户与助手的文字消息。工具记录、附件和运行状态留在来源 Agent。'
1344
+ const historyNote = '核对旧对话,再迁入 DSH 继续。工具记录可在来源历史中查阅。'
1076
1345
 
1077
1346
  function openSourceConversation(session) {
1078
1347
  if (startHistoryDialog('继续旧对话', historyNote, '正在读取这条对话…') === undefined) return
@@ -1083,9 +1352,11 @@ async function chooseSourceConversation() {
1083
1352
  const epoch = startHistoryDialog('查看全部对话', '选择一条对话以预览历史消息。', '正在读取对话列表…')
1084
1353
  if (epoch === undefined) return
1085
1354
  try {
1086
- const { sessions } = await api('list-conversations', { projectId: historyProject.id })
1355
+ const { sessions, nextCursor, unavailable = [] } = await api('list-conversations', { projectId: historyProject.id })
1087
1356
  if (!dialog.open || dialogEpoch !== epoch) return
1088
1357
  historySessions = sessions
1358
+ historyUnavailable = unavailable
1359
+ historyCursor = nextCursor
1089
1360
  historySearch.value = ''
1090
1361
  historyLimit = 30
1091
1362
  showHistoryResults()
@@ -1094,22 +1365,73 @@ async function chooseSourceConversation() {
1094
1365
  }
1095
1366
  }
1096
1367
 
1097
- function renderHistoryResults() {
1368
+ function historyMatches(sessions) {
1098
1369
  const query = historySearch.value.trim().toLowerCase()
1370
+ return sessions.filter(session => [session.title, agentName(session.agent)].some(value => value?.toLowerCase().includes(query)))
1371
+ }
1372
+
1373
+ function renderHistoryResults() {
1099
1374
  syncSearch(historySearch)
1100
- const matches = historySessions.filter(session => [session.title, agentName(session.agent)]
1101
- .some(value => value?.toLowerCase().includes(query)))
1375
+ const matches = historyMatches(historySessions)
1102
1376
  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
1377
+ byId('history-empty').textContent = matches.length ? ''
1378
+ : historyCursor ? '已扫描的部分暂无匹配项,可继续扫描。'
1379
+ : historySearch.value.trim() ? '没有找到匹配的对话。' : '这个项目暂无可迁入的对话。'
1380
+ const more = byId('history-more')
1381
+ const unavailable = historyMatches(historyUnavailable)
1382
+ const moreLocally = Math.max(matches.length, unavailable.length) > historyLimit
1383
+ more.hidden = !moreLocally && !historyCursor
1384
+ more.disabled = historyPaging
1385
+ more.textContent = historyPaging ? '正在扫描…' : moreLocally ? '显示更多' : '继续扫描'
1386
+ byId('history-unavailable').hidden = unavailable.length === 0
1387
+ byId('history-unavailable-count').textContent = `${unavailable.length} 条来源无法读取`
1388
+ byId('history-unavailable-results').replaceChildren(...unavailable.slice(0, historyLimit).map(session => {
1389
+ const row = text('li', '', 'preview-context')
1390
+ row.append(text('strong', session.title || '未命名对话'), document.createTextNode(` · ${archiveIssue(session.reason)}`))
1391
+ return row
1392
+ }))
1393
+ }
1394
+
1395
+ async function moreHistoryResults() {
1396
+ if (historyPaging) return
1397
+ const index = historyResults.childElementCount
1398
+ if (Math.max(historyMatches(historySessions).length, historyMatches(historyUnavailable).length) <= historyLimit && historyCursor) {
1399
+ const epoch = dialogEpoch
1400
+ const cursor = historyCursor
1401
+ historyPaging = true
1402
+ status('', false, 'dialog-status')
1403
+ renderHistoryResults()
1404
+ try {
1405
+ const page = await api('list-conversations', { projectId: historyProject.id, cursor })
1406
+ if (!dialog.open || dialogEpoch !== epoch) return
1407
+ const merge = (first, second) => [...new Map([...first, ...second].map(item => [item.id, item])).values()]
1408
+ historySessions = merge(historySessions, page.sessions)
1409
+ historyUnavailable = merge(historyUnavailable, page.unavailable ?? [])
1410
+ historyCursor = page.nextCursor === cursor ? undefined : page.nextCursor
1411
+ } catch (error) {
1412
+ if (dialog.open && dialogEpoch === epoch) status(error.message, true, 'dialog-status')
1413
+ return
1414
+ } finally {
1415
+ if (dialogEpoch === epoch) {
1416
+ historyPaging = false
1417
+ renderHistoryResults()
1418
+ }
1419
+ }
1420
+ }
1421
+ historyLimit += 30
1422
+ renderHistoryResults()
1423
+ historyResults.children[index]?.querySelector('button')?.focus()
1105
1424
  }
1106
1425
 
1107
1426
  function showHistoryResults() {
1108
1427
  if (!historySessions) return
1428
+ releaseHistoryPreview()
1109
1429
  historyPreview++
1110
1430
  historyTicket = undefined
1111
1431
  importedSessionId = undefined
1112
1432
  historyImport.hidden = true
1433
+ dialogSkillCandidates = []
1434
+ dialogSkillIds = new Set()
1113
1435
  byId('history-back').hidden = true
1114
1436
  byId('dialog-title').textContent = '查看全部对话'
1115
1437
  byId('dialog-note').textContent = '选择一条对话以预览历史消息。'
@@ -1122,71 +1444,553 @@ function showHistoryResults() {
1122
1444
  ;(previous || historySearch).focus()
1123
1445
  }
1124
1446
 
1125
- async function previewSourceConversation(session) {
1447
+ const traceKindNames = { summary: '思考摘要', tool_call: '工具调用', tool_result: '工具结果', turn_end: '回合结束' }
1448
+ const traceStateNames = {
1449
+ missing: '未记录结果', error: '失败', pending: '待确认', truncated: '已截取', unmatched: '归属未知', incomplete: '未完成',
1450
+ completed: '已完成', interrupted: '已中断',
1451
+ }
1452
+
1453
+ function createTraceDisclosure(label, count) {
1454
+ const details = document.createElement('details')
1455
+ details.className = 'trace-disclosure'
1456
+ details.append(text('summary', `${label} · ${count} 项`))
1457
+ return details
1458
+ }
1459
+
1460
+ // Source trace is read-only: it is shown next to the question it belongs to and
1461
+ // never replayed into the new session as a tool event.
1462
+ function traceDisclosure(items, turnLabel) {
1463
+ const details = createTraceDisclosure(turnLabel ?? '来源记录', items.length)
1464
+ const list = text('div', '', 'trace-list')
1465
+ let turn
1466
+ for (const item of items) {
1467
+ if (!turnLabel && item.turn && item.turn !== turn) {
1468
+ turn = item.turn
1469
+ list.append(text('h4', `第 ${turn} 轮`, 'trace-turn'))
1470
+ }
1471
+ const row = text('article', '', 'trace-item')
1472
+ row.dataset.kind = item.kind
1473
+ const head = text('div', '', 'trace-head')
1474
+ head.append(text('span', traceKindNames[item.kind] ?? item.kind, 'trace-kind'))
1475
+ if (item.name) head.append(text('code', item.name, 'trace-name'))
1476
+ if (item.callId) head.append(text('code', `调用 ${item.callId}`, 'trace-name'))
1477
+ const state = traceStateNames[item.status]
1478
+ if (state) {
1479
+ const chip = text('span', state, 'trace-state')
1480
+ chip.dataset.state = item.status
1481
+ head.append(chip)
1482
+ }
1483
+ if (item.truncated && item.status !== 'truncated') head.append(text('span', '已截取', 'trace-state'))
1484
+ if (item.time) head.append(text('time', historyDateFormat.format(new Date(item.time)), 'trace-time'))
1485
+ row.append(head)
1486
+ if (item.text) row.append(text('p', item.text, 'trace-text'))
1487
+ else if (item.kind === 'tool_result') row.append(text('p', '未记录结果', 'trace-text trace-empty'))
1488
+ if (item.text && item.kind === 'tool_result') {
1489
+ const copy = text('button', '复制结果摘录', 'trace-copy')
1490
+ copy.type = 'button'
1491
+ copy.addEventListener('click', async () => {
1492
+ try {
1493
+ await navigator.clipboard.writeText(item.text)
1494
+ copy.textContent = '已复制'
1495
+ setTimeout(() => { copy.textContent = '复制结果摘录' }, 1600)
1496
+ } catch {
1497
+ status('无法访问剪贴板,请手动选择文字复制。', true, 'dialog-status')
1498
+ }
1499
+ })
1500
+ row.append(copy)
1501
+ }
1502
+ list.append(row)
1503
+ }
1504
+ details.append(list)
1505
+ return details
1506
+ }
1507
+
1508
+ function sessionTraceDisclosure(items) {
1509
+ const turns = new Map()
1510
+ for (const item of items) {
1511
+ const entries = turns.get(item.turn)
1512
+ if (entries) entries.push(item)
1513
+ else turns.set(item.turn, [item])
1514
+ }
1515
+ const details = createTraceDisclosure('来源记录', items.length)
1516
+ const list = text('div', '', 'trace-list trace-turn-list')
1517
+ for (const [turn, entries] of turns) {
1518
+ list.append(traceDisclosure(entries, turn ? `第 ${turn} 轮` : '未标记轮次'))
1519
+ }
1520
+ details.append(list)
1521
+ return details
1522
+ }
1523
+
1524
+ const formatStatNumber = new Intl.NumberFormat('zh-CN').format
1525
+ const archiveIssueLabels = {
1526
+ 'source-unavailable': '找不到会话来源。',
1527
+ 'source-unreadable': '无法读取部分来源记录。',
1528
+ 'source-mismatch': '来源的工作目录和项目不一致。',
1529
+ 'source-metadata-missing': '来源缺少用于核对会话身份的记录。',
1530
+ 'source-compacted': '来源已压缩早期历史,原文可能已不在源记录中。',
1531
+ 'source-dialogue-only': '来源只有已保存的问答,工具和附件记录可能缺失。',
1532
+ 'source-tool-output-truncated': '源记录中的工具输出已被截取。',
1533
+ 'archive-tool-details-unavailable': '归档缺少工具调用详情。',
1534
+ 'unresolved-branch': '无法确定部分分支的归属。',
1535
+ 'unresolved-source-projection': '有部分来源消息无法核对。',
1536
+ 'unsupported-source-schema': '当前版本不识别这份来源的存储结构。',
1537
+ 'unsupported-incremental-edit': '部分增量编辑无法恢复。',
1538
+ 'unsupported-source': '当前版本无法读取这类来源。',
1539
+ 'unsupported-compression': '当前 DSH 无法解压这份日志。',
1540
+ 'malformed-record': '有一条来源记录损坏或格式无法识别。',
1541
+ 'record-too-large': '有一条来源记录超过可读取的大小。',
1542
+ 'corrupt-compressed-source': '压缩日志不完整或已损坏。',
1543
+ 'source-changed': '读取期间,来源发生变化。',
1544
+ 'remote-reference': '此附件只有远程引用。',
1545
+ 'name-only': '来源只保存了附件名称。',
1546
+ 'outside-project': '附件不在可读取范围内。',
1547
+ 'attachment-unavailable': '附件已移动或无法访问。',
1548
+ 'attachment-too-large': '附件超过可保存的大小。',
1549
+ }
1550
+
1551
+ function archiveIssue(code) {
1552
+ return Object.hasOwn(archiveIssueLabels, code) ? archiveIssueLabels[code] : '部分来源记录无法读取。'
1553
+ }
1554
+
1555
+ function archiveUrl(route, sessionId, values = {}) {
1556
+ return `./${route}?${new URLSearchParams({ sessionId, ...values })}`
1557
+ }
1558
+
1559
+ function archivedAttachment(item, { sessionId, snapshotId }) {
1560
+ const row = text('div', '', 'archive-attachment')
1561
+ const name = item.name || '附件'
1562
+ if (item.status === 'saved' && item.attachmentId && (sessionId || snapshotId)) {
1563
+ const params = new URLSearchParams(sessionId ? { sessionId } : { snapshotId })
1564
+ params.set('attachmentId', item.attachmentId)
1565
+ if (Number.isSafeInteger(item.seq)) params.set('seq', item.seq)
1566
+ const url = `./conversation-attachment?${params}`
1567
+ if (['image/png', 'image/jpeg', 'image/gif', 'image/webp'].includes(item.mediaType)) {
1568
+ const preview = text('button', '', 'archive-attachment-preview')
1569
+ preview.type = 'button'
1570
+ preview.setAttribute('aria-label', `放大图片 ${name}`)
1571
+ preview.setAttribute('aria-pressed', 'false')
1572
+ preview.addEventListener('click', () => {
1573
+ const enlarged = preview.classList.toggle('enlarged')
1574
+ preview.setAttribute('aria-pressed', String(enlarged))
1575
+ preview.setAttribute('aria-label', `${enlarged ? '缩小图片' : '放大图片'} ${name}`)
1576
+ })
1577
+ const image = document.createElement('img')
1578
+ image.alt = name
1579
+ image.loading = 'lazy'
1580
+ image.decoding = 'async'
1581
+ image.addEventListener('error', () => preview.remove(), { once: true })
1582
+ image.src = url + '&inline=true'
1583
+ preview.append(image)
1584
+ row.append(preview)
1585
+ }
1586
+ const link = text('a', name, 'text-action archive-attachment-name')
1587
+ link.href = url
1588
+ link.download = name
1589
+ link.title = `下载「${name}」`
1590
+ row.append(link)
1591
+ } else {
1592
+ row.append(text('strong', name, 'archive-attachment-name'),
1593
+ text('span', archiveIssue(item.reason || item.status), 'muted'))
1594
+ }
1595
+ return row
1596
+ }
1597
+
1598
+ function archiveButton(label, action) {
1599
+ const button = text('button', label, 'secondary reader-button')
1600
+ button.type = 'button'
1601
+ button.addEventListener('click', action)
1602
+ return button
1603
+ }
1604
+
1605
+ function sourceArchive(history, { sessionId, snapshotId, ticket } = {}) {
1606
+ const section = text('details', '', 'source-archive bridge-reader')
1607
+ section.append(text('summary', '完整历史', 'reader-summary'))
1608
+ const info = text('p', '', 'reader-note')
1609
+ const result = text('div', '', 'source-archive-items reader-list')
1610
+ result.tabIndex = 0
1611
+ result.setAttribute('aria-label', '当前页的来源记录')
1612
+ const pagination = text('nav', '', 'reader-pager')
1613
+ pagination.setAttribute('aria-label', '完整历史分页')
1614
+ const pageLabel = text('span', '', 'muted')
1615
+ pageLabel.setAttribute('role', 'status')
1616
+ const readError = text('p', '', 'muted')
1617
+ readError.setAttribute('role', 'status')
1618
+ const locators = [{}]
1619
+ let index = -1
1620
+ let nextCursor
1621
+ let busy = false
1622
+ const first = archiveButton('最早一页', () => void load(0, {}))
1623
+ const previous = archiveButton('上一页', () => void load(index - 1, locators[index - 1]))
1624
+ const next = archiveButton('下一页', () => void load(index + 1, { cursor: nextCursor }))
1625
+ const goTo = text('form', '', 'reader-jump')
1626
+ const turn = document.createElement('input')
1627
+ turn.type = 'number'
1628
+ turn.min = '1'
1629
+ turn.step = '1'
1630
+ turn.required = true
1631
+ turn.setAttribute('aria-label', '回合号')
1632
+ turn.placeholder = '回合号'
1633
+ const go = text('button', '跳到回合', 'reader-button')
1634
+ go.type = 'submit'
1635
+ goTo.append(turn, go)
1636
+ pagination.append(first, previous, pageLabel, next)
1637
+ const toolbar = text('div', '', 'reader-toolbar')
1638
+ toolbar.append(goTo, pagination)
1639
+ section.append(info, toolbar, result, readError)
1640
+ goTo.addEventListener('submit', event => {
1641
+ event.preventDefault()
1642
+ const number = Number(turn.value)
1643
+ if (!busy && Number.isSafeInteger(number) && number > 0) void load(0, { turn: number })
1644
+ })
1645
+
1646
+ if (sessionId) {
1647
+ const downloads = text('details', '', 'reader-extra')
1648
+ const exports = text('div', '', 'reader-downloads')
1649
+ const option = document.createElement('label')
1650
+ const withTools = document.createElement('input')
1651
+ withTools.type = 'checkbox'
1652
+ option.append(withTools, document.createTextNode(' 附带工具和摘要'))
1653
+ exports.append(option)
1654
+ for (const [format, name] of [['local', '下载来源全文(本机版)'], ['share', '下载来源全文(分享版)']]) {
1655
+ const link = text('a', name, 'reader-button')
1656
+ const setUrl = () => { link.href = archiveUrl('conversation-export', sessionId, { format, includeTrace: String(withTools.checked) }) }
1657
+ link.download = ''
1658
+ withTools.addEventListener('change', setUrl)
1659
+ setUrl()
1660
+ exports.append(link)
1661
+ }
1662
+ downloads.append(text('summary', '导出来源全文', 'reader-summary'), exports)
1663
+ section.append(downloads)
1664
+ }
1665
+
1666
+ function explain(counts) {
1667
+ const partial = counts.complete === false
1668
+ ? ' · 来源不完整,缺失原因见页内记录'
1669
+ : ''
1670
+ const { nativeFirstTurn: start, nativeLastTurn: end } = counts
1671
+ const nativeRange = start && end ? `(原第 ${start === end ? start : `${start}–${end}`} 轮)` : ''
1672
+ const retained = sessionId
1673
+ ? `已迁入 ${formatStatNumber(counts.nativeMessages ?? 0)} 条消息${nativeRange}`
1674
+ : `预览保留 ${formatStatNumber(counts.nativeMessages ?? 0)} 条续聊消息${nativeRange}`
1675
+ info.textContent = `${formatStatNumber(counts.messages ?? 0)} 条历史消息 · ${formatStatNumber(counts.tools ?? 0)} 条工具记录 · ${formatStatNumber(counts.attachments ?? 0)} 个附件 · ${retained}${partial}`
1676
+ }
1677
+
1678
+ function syncControls() {
1679
+ first.disabled = busy || (index <= 0 && !locators[0].turn)
1680
+ previous.disabled = busy || index <= 0
1681
+ next.disabled = busy || !nextCursor
1682
+ turn.disabled = busy
1683
+ go.disabled = busy
1684
+ pageLabel.textContent = busy ? '正在读取…' : (index >= 0 ? `第 ${index + 1} 页` : '')
1685
+ }
1686
+
1687
+ function renderItem(item) {
1688
+ const row = text('article', '', 'history-message reader-row')
1689
+ if (item.role) row.dataset.role = item.role
1690
+ if (item.kind === 'gap') {
1691
+ row.append(text('p', archiveIssue(item.reason), 'reader-body'))
1692
+ return row
1693
+ }
1694
+ const label = item.kind === 'message'
1695
+ ? (item.role === 'user' ? '用户' : '助手')
1696
+ : traceKindNames[item.kind] ?? '附件'
1697
+ const meta = text('div', '', 'reader-meta')
1698
+ if (item.turn) meta.append(text('small', '第 ' + item.turn + ' 轮'))
1699
+ meta.append(text('strong', label))
1700
+ row.append(meta)
1701
+ const detail = [
1702
+ item.kind === 'attachment' ? '' : item.name,
1703
+ item.callId ? `调用 ${item.callId}` : '', traceStateNames[item.status],
1704
+ item.branchId ? `分支 ${item.branchId}` : '',
1705
+ item.offset || item.continued ? '分段显示' : '',
1706
+ ].filter(Boolean).join(' · ')
1707
+ if (detail) row.append(text('small', detail, 'reader-detail'))
1708
+ if (item.kind === 'attachment') {
1709
+ row.append(archivedAttachment(item, { sessionId, snapshotId }))
1710
+ return row
1711
+ }
1712
+ if (item.text) {
1713
+ row.append(item.kind === 'message' && item.role === 'assistant' && !item.offset && !item.continued
1714
+ ? markdownBody(item.text, 'preview-body reader-body')
1715
+ : text('p', item.text, 'preview-body reader-body'))
1716
+ const copy = archiveButton('复制摘录', async () => {
1717
+ try {
1718
+ await navigator.clipboard.writeText(item.text)
1719
+ readError.textContent = '已复制,可粘贴到下一条消息。'
1720
+ } catch {
1721
+ readError.textContent = '无法访问剪贴板,请手动选择文字复制。'
1722
+ }
1723
+ })
1724
+ const actions = text('div', '', 'reader-actions')
1725
+ actions.append(copy)
1726
+ if (sessionId && item.text.length <= 65_536) {
1727
+ actions.append(archiveButton('引用到草稿', async event => {
1728
+ const button = event.currentTarget
1729
+ button.disabled = true
1730
+ try {
1731
+ await requestParent('quote-history', { sessionId, text: item.text })
1732
+ dialog.close()
1733
+ } catch (error) {
1734
+ readError.textContent = error.message
1735
+ } finally {
1736
+ button.disabled = false
1737
+ }
1738
+ }))
1739
+ }
1740
+ row.append(actions)
1741
+ }
1742
+ return row
1743
+ }
1744
+
1745
+ function renderPage(items) {
1746
+ const groups = new Map()
1747
+ const rows = []
1748
+ for (const [index, item] of items.entries()) {
1749
+ const row = renderItem(item)
1750
+ const previous = items[index - 1]
1751
+ if (item.kind === 'attachment' && item.turn > 0 && previous?.kind === 'attachment'
1752
+ && previous.turn === item.turn && previous.branchId === item.branchId) row.classList.add('reader-following-file')
1753
+ if (!['summary', 'tool_call', 'tool_result'].includes(item.kind)) {
1754
+ rows.push(row)
1755
+ continue
1756
+ }
1757
+ const key = JSON.stringify([item.turn, item.branchId])
1758
+ let group = groups.get(key)
1759
+ if (!group) {
1760
+ const disclosure = text('details', '', 'source-archive-process reader-process')
1761
+ const summary = text('summary', '', 'reader-summary')
1762
+ const contents = text('div', '', 'source-archive-process-items reader-process-items')
1763
+ disclosure.append(summary, contents)
1764
+ group = { summary, contents, records: new Set(), turn: item.turn, branch: item.branchId }
1765
+ groups.set(key, group)
1766
+ rows.push(disclosure)
1767
+ }
1768
+ group.contents.append(row)
1769
+ group.records.add(item.seq ?? item)
1770
+ }
1771
+ for (const group of groups.values()) {
1772
+ const label = [
1773
+ group.turn ? `第 ${group.turn} 轮过程` : '未归属的过程',
1774
+ group.branch ? `分支 ${group.branch}` : '',
1775
+ ].filter(Boolean).join(' · ')
1776
+ group.summary.append(document.createTextNode(label), text('small', '本页 ' + group.records.size + ' 项'))
1777
+ }
1778
+ return rows
1779
+ }
1780
+
1781
+ async function load(position, locator) {
1782
+ if (busy || !locator) return
1783
+ busy = true
1784
+ readError.replaceChildren()
1785
+ syncControls()
1786
+ try {
1787
+ const identity = sessionId ? { sessionId } : { snapshotId, ticket }
1788
+ const page = await api('conversation-history', { ...identity, ...locator })
1789
+ explain(page.history ?? history)
1790
+ result.replaceChildren(...renderPage(page.items))
1791
+ result.scrollTop = 0
1792
+ if (!page.items.length) result.append(text('p', '这页暂无来源记录。', 'muted'))
1793
+ if (position === 0) locators.length = 1
1794
+ locators[position] = locator
1795
+ index = position
1796
+ nextCursor = page.nextCursor
1797
+ } catch (error) {
1798
+ readError.append(document.createTextNode(error.message + ' '), archiveButton('重试', () => void load(position, locator)))
1799
+ } finally {
1800
+ busy = false
1801
+ syncControls()
1802
+ }
1803
+ }
1804
+
1805
+ section.addEventListener('toggle', () => { if (section.open && index < 0) void load(0, {}) })
1806
+ explain(history)
1807
+ syncControls()
1808
+ return section
1809
+ }
1810
+
1811
+ function renderSourceStats(stats, counts = {}, { preview = false } = {}) {
1812
+ const section = text('details', '', 'bridge-reader bridge-stats')
1813
+ section.open = !stats
1814
+ const title = '原对话统计'
1815
+ section.setAttribute('aria-label', title)
1816
+ const heading = text('summary', title, 'reader-summary')
1817
+ if (stats) heading.append(text('small', `${formatStatNumber(stats.userMessages)} 轮 · ${formatStatNumber(stats.userMessages + stats.assistantMessages)} 条消息`))
1818
+ section.append(heading)
1819
+ const metrics = text('dl', '')
1820
+ const notes = []
1821
+ function addMetric(label, value) {
1822
+ const metric = document.createElement('div')
1823
+ metric.append(text('dt', label), text('dd', typeof value === 'number' ? formatStatNumber(value) : value))
1824
+ metrics.append(metric)
1825
+ }
1826
+ if (stats) {
1827
+ const total = stats.userMessages + stats.assistantMessages
1828
+ addMetric('已读轮次', stats.userMessages)
1829
+ addMetric('已读消息', total)
1830
+ notes.push(`用户 ${formatStatNumber(stats.userMessages)} 条,助手 ${formatStatNumber(stats.assistantMessages)} 条`)
1831
+ if (stats.importedMessages !== total) {
1832
+ notes.push(`${preview ? '预览保留' : '已迁入'} ${formatStatNumber(stats.importedMessages)} 条消息`)
1833
+ }
1834
+ }
1835
+ addMetric(preview ? '可带入工具调用' : '已保存工具调用', counts.toolCall ?? 0)
1836
+ if (stats?.elapsedMs !== undefined) {
1837
+ const seconds = Math.floor(stats.elapsedMs / 1000)
1838
+ const hours = Math.floor(seconds / 3600)
1839
+ const minutes = Math.floor(seconds / 60) % 60
1840
+ const remainder = String(seconds % 60).padStart(2, '0')
1841
+ addMetric('消息时间跨度', hours ? `${hours}:${String(minutes).padStart(2, '0')}:${remainder}` : `${minutes}:${remainder}`)
1842
+ }
1843
+ if (stats?.tokens) {
1844
+ const { total, input, output } = stats.tokens
1845
+ addMetric('源记录 Token', total)
1846
+ if (input !== undefined && output !== undefined) notes.push(`输入 ${formatStatNumber(input)},输出 ${formatStatNumber(output)}`)
1847
+ }
1848
+ if (counts.failed) notes.push(`${formatStatNumber(counts.failed)} 次失败`)
1849
+ if (counts.missing) notes.push(`${formatStatNumber(counts.missing)} 次未记录结果`)
1850
+ if (counts.summary) notes.push(`${formatStatNumber(counts.summary)} 段思考摘要`)
1851
+ section.append(metrics)
1852
+ if (notes.length) section.append(text('p', notes.join(' · ')))
1853
+ if (stats?.partial) section.append(text('p', '消息与轮次仅统计已读取的部分原记录。'))
1854
+ if (!stats) section.append(text('p', '旧版迁入的会话,统计来自当时保存的来源记录。'))
1855
+ return section
1856
+ }
1857
+
1858
+ async function previewSourceConversation(session, targetCwd) {
1126
1859
  const epoch = dialogEpoch
1127
1860
  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 })
1861
+ if (targetCwd) {
1862
+ setDialogBusy(true)
1863
+ } else {
1864
+ releaseHistoryPreview()
1865
+ historyChosenId = session.id
1866
+ historyTicket = undefined
1867
+ importedSessionId = undefined
1868
+ historyImport.hidden = true
1869
+ byId('history-import-label').textContent = '迁入并继续'
1870
+ byId('history-choice').hidden = true
1871
+ byId('history-back').hidden = !historySessions
1872
+ byId('dialog-title').textContent = '继续旧对话'
1873
+ byId('dialog-note').textContent = historyNote
1874
+ dialogText.hidden = false
1875
+ dialogText.dataset.format = 'plain'
1876
+ dialogText.textContent = '正在读取这条对话…'
1877
+ dialogText.closest('.dialog-content').scrollTop = 0
1878
+ if (historySessions) byId('history-back-button').focus()
1879
+ else dialogText.focus({ preventScroll: true })
1880
+ }
1143
1881
  status('', false, 'dialog-status')
1882
+ const active = () => dialog.open && dialogEpoch === epoch && revision === historyPreview
1144
1883
  try {
1145
- const result = await api('preview-conversation', { projectId: historyProject.id, sessionId: session.id })
1146
- if (!dialog.open || dialogEpoch !== epoch || revision !== historyPreview) return
1884
+ const result = await api('preview-conversation', {
1885
+ projectId: historyProject.id, sessionId: session.id,
1886
+ ...(targetCwd ? { targetCwd, snapshotId: historySnapshotId } : {}),
1887
+ })
1888
+ const snapshotId = result.history?.snapshotId
1889
+ if (!active()) {
1890
+ if (snapshotId && !result.resumePending) void api('discard-conversation-preview', { snapshotId }).catch(() => {})
1891
+ return
1892
+ }
1893
+ if (snapshotId !== historySnapshotId) releaseHistoryPreview()
1894
+ historySnapshotId = snapshotId
1895
+ historyImportStarted = result.resumePending === true
1147
1896
  historyTicket = result.ticket
1148
1897
  const title = text('h3', result.title, 'preview-lead')
1149
1898
  const source = text('p', '', 'preview-context history-source')
1150
- source.append(agentLabel(session.agent), text('code', result.cwd || historyProject.cwd, 'preview-source'))
1899
+ const original = result.sourceCwd ?? result.cwd ?? historyProject.cwd
1900
+ source.append(agentLabel(session.agent), text('span', '原工作目录'), text('code', original, 'preview-source'))
1901
+ const target = text('p', '', 'preview-context history-source')
1902
+ if (result.targetCwd && result.targetCwd !== original) {
1903
+ target.append(text('span', '迁入目录'), text('code', result.targetCwd, 'preview-source'))
1904
+ }
1905
+ const directory = result.history && !result.resumePending ? text('details', '', 'source-archive') : undefined
1906
+ if (directory) {
1907
+ const form = text('form', '', 'history-target-form')
1908
+ const input = document.createElement('input')
1909
+ input.type = 'text'
1910
+ input.maxLength = 4096
1911
+ input.required = true
1912
+ input.autocomplete = 'off'
1913
+ input.setAttribute('aria-label', '迁入目录的本机绝对路径')
1914
+ input.placeholder = '输入迁入目录的本机绝对路径'
1915
+ input.value = result.targetCwd || ''
1916
+ const suggested = document.createElement('datalist')
1917
+ suggested.id = 'history-target-suggestions'
1918
+ input.setAttribute('list', suggested.id)
1919
+ for (const project of catalog.filter(project => project.online)) {
1920
+ suggested.append(new Option(project.name, project.cwd))
1921
+ }
1922
+ const verify = text('button', '核对目录', 'secondary')
1923
+ verify.type = 'submit'
1924
+ const browse = archiveButton('浏览本机目录', async () => {
1925
+ if (dialogBusy) return
1926
+ setDialogBusy(true)
1927
+ status('', false, 'dialog-status')
1928
+ try {
1929
+ const { path } = await requestParent('pick-history-directory')
1930
+ if (path && form.isConnected) {
1931
+ input.value = path
1932
+ await previewSourceConversation(session, path)
1933
+ }
1934
+ } catch (error) {
1935
+ status(error.message, true, 'dialog-status')
1936
+ } finally {
1937
+ if (dialog.open) setDialogBusy(false)
1938
+ }
1939
+ })
1940
+ form.append(input, suggested, browse, verify)
1941
+ form.addEventListener('submit', event => {
1942
+ event.preventDefault()
1943
+ if (!dialogBusy && input.value.trim()) void previewSourceConversation(session, input.value.trim())
1944
+ })
1945
+ directory.open = !result.canImport
1946
+ directory.append(text('summary', '选择迁入目录'), form)
1947
+ }
1948
+ const skillChoices = renderSkillChoices(result.skillCandidates, { history: true })
1949
+ const stats = renderSourceStats(result.sourceStats, result.traceCounts, { preview: true })
1950
+ const traceByMessage = new Map()
1951
+ for (const item of result.trace ?? []) {
1952
+ if (!Number.isInteger(item.messageIndex)) continue
1953
+ traceByMessage.set(item.messageIndex, [...(traceByMessage.get(item.messageIndex) ?? []), item])
1954
+ }
1151
1955
  const summary = text('p', [
1152
- result.messages.length + ' 条文字消息',
1153
- result.truncated ? '源记录或读取范围有限,部分历史未带入' : '',
1154
- result.canImport ? '' : '原工作目录不可访问,当前可预览',
1956
+ result.truncated && !result.history ? '源记录或读取范围有限,部分历史未带入' : '',
1957
+ result.canImport ? '' : '原工作目录不可访问,可以先预览或核对新的迁入目录',
1958
+ result.resumePending ? '上次迁入尚未完成,可在同一会话继续。' : '',
1155
1959
  ].filter(Boolean).join(' · '), 'preview-context')
1156
1960
  dialogText.dataset.format = 'history'
1157
- dialogText.replaceChildren(title, source, summary, ...result.messages.map(message => {
1961
+ dialogText.replaceChildren(title, source, ...(target.textContent ? [target] : []), ...(directory ? [directory] : []),
1962
+ stats, ...(summary.textContent ? [summary] : []), ...(result.history ? [sourceArchive(result.history, { snapshotId, ticket: result.ticket })] : []),
1963
+ ...(skillChoices ? [skillChoices] : []), ...result.messages.map((message, index) => {
1158
1964
  const row = text('section', '', 'history-message')
1159
1965
  row.dataset.role = message.role
1160
- row.append(text('h3', message.role === 'user' ? '用户' : '助手'), text('p', message.text, 'preview-body'))
1966
+ const body = message.role === 'assistant'
1967
+ ? markdownBody(message.text, 'preview-body')
1968
+ : text('p', message.text, 'preview-body')
1969
+ row.append(text('h3', message.role === 'user' ? '用户' : '助手'), body)
1970
+ const items = traceByMessage.get(index)
1971
+ if (items?.length) row.append(traceDisclosure(items))
1161
1972
  return row
1162
1973
  }))
1163
1974
  historyImport.hidden = !result.canImport
1975
+ syncSkillChoiceButtons()
1164
1976
  } catch (error) {
1165
- if (dialog.open && dialogEpoch === epoch && revision === historyPreview) dialogText.textContent = error.message
1977
+ if (active() && targetCwd) status(error.message, true, 'dialog-status')
1978
+ else if (active()) dialogText.textContent = error.message
1979
+ } finally {
1980
+ if (active() && targetCwd) setDialogBusy(false)
1166
1981
  }
1167
1982
  }
1168
1983
 
1169
1984
  async function importSourceConversation() {
1170
1985
  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)
1986
+ if (!importedSessionId && dialogSkillIds.size) {
1987
+ await beginSkillActivation('history')
1988
+ return
1186
1989
  }
1990
+ await completeHandoff('history', [])
1187
1991
  }
1188
1992
 
1189
- function renderHandoff({ intro, sections, footer }) {
1993
+ function renderHandoff({ intro, sections, footer, cwd }, skillCandidates = []) {
1190
1994
  const lead = text('div', '', 'preview-intro')
1191
1995
  const [heading, ...introLines] = intro.split('\n')
1192
1996
  lead.append(text('p', heading, 'preview-lead'))
@@ -1195,6 +1999,9 @@ function renderHandoff({ intro, sections, footer }) {
1195
1999
  if (metadata) {
1196
2000
  const row = text('div', '', 'preview-meta')
1197
2001
  row.append(text('span', metadata[1]), text('code', metadata[2]))
2002
+ if (metadata[1] === '工作目录' && cwd) {
2003
+ row.append(pathActions({ label: '工作目录', path: cwd, directory: true }))
2004
+ }
1198
2005
  lead.append(row)
1199
2006
  } else if (line) lead.append(text('p', line, 'preview-context'))
1200
2007
  }
@@ -1203,13 +2010,28 @@ function renderHandoff({ intro, sections, footer }) {
1203
2010
  const content = sections.map(section => {
1204
2011
  const block = text('section', '', 'preview-section')
1205
2012
  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'))
2013
+ if (section.file) {
2014
+ const fileRow = text('div', '', 'preview-source-row')
2015
+ fileRow.append(
2016
+ text('code', section.file, 'preview-source'),
2017
+ section.assetId
2018
+ ? pathActions({ label: section.label, path: section.file, assetId: section.assetId })
2019
+ : pathActions({ label: section.label, path: section.file }),
2020
+ )
2021
+ block.append(fileRow)
2022
+ }
2023
+ const source = section.text
2024
+ const body = isMarkdownFile(section.file) || section.markdown
2025
+ ? markdownBody(source, 'preview-body', current?.id, section.references)
2026
+ : text('p', source, 'preview-body')
2027
+ block.append(body)
1208
2028
  return block
1209
2029
  })
2030
+ const skillChoices = renderSkillChoices(skillCandidates)
1210
2031
  dialogText.dataset.format = 'handoff'
1211
- dialogText.replaceChildren(lead, ...content)
2032
+ dialogText.replaceChildren(lead, ...(skillChoices ? [skillChoices] : []), ...content)
1212
2033
  if (footer) dialogText.append(text('p', footer, 'preview-context'))
2034
+ syncSkillChoiceButtons()
1213
2035
  }
1214
2036
 
1215
2037
  async function viewAsset(asset) {
@@ -1218,9 +2040,18 @@ async function viewAsset(asset) {
1218
2040
  try {
1219
2041
  const result = await api('asset', { projectId: project.id, assetId: asset.id })
1220
2042
  if (!dialog.open || dialogEpoch !== epoch) return
1221
- dialogText.textContent = result.text + (result.truncated ? '\n\n[预览已截取]' : '')
2043
+ if (isMarkdownFile(asset.file)) {
2044
+ dialogText.dataset.format = 'markdown'
2045
+ dialogText.replaceChildren(renderProjectMarkdown(result.text, project.id, result.references))
2046
+ if (result.truncated) dialogText.append(text('p', '[预览已截取,完整内容见来源文件。]', 'preview-context'))
2047
+ } else {
2048
+ dialogText.textContent = result.text + (result.truncated ? '\n\n[预览已截取]' : '')
2049
+ }
1222
2050
  } catch (error) {
1223
- if (dialog.open && dialogEpoch === epoch) status(error.message, true, 'dialog-status')
2051
+ if (dialog.open && dialogEpoch === epoch) {
2052
+ dialogText.dataset.format = 'plain'
2053
+ dialogText.textContent = error.message
2054
+ }
1224
2055
  }
1225
2056
  }
1226
2057
 
@@ -1232,13 +2063,20 @@ async function preview() {
1232
2063
  : '原工作目录不可访问。可将现有交接资料导出为 Markdown。'
1233
2064
  const epoch = showDialog('handoff', `草稿预览 · ${project.name}`, note, '正在准备…')
1234
2065
  try {
1235
- const result = await api('preview', { projectId: project.id, assetIds: [...selected], history: historyOption.checked })
2066
+ const input = { projectId: project.id, assetIds: [...selected], history: historyOption.checked }
2067
+ previewInput = input
2068
+ const result = await api('preview', input)
1236
2069
  if (!dialog.open || dialogEpoch !== epoch) return
1237
2070
  ticket = result.ticket
1238
- if (result.preview) renderHandoff(result.preview)
2071
+ if (result.preview) renderHandoff(result.preview, result.skillCandidates)
1239
2072
  else dialogText.textContent = result.prompt
1240
2073
  importButton.hidden = result.canImport === false || !project.online
1241
2074
  exportButton.hidden = false
2075
+ exportShareButton.hidden = false
2076
+ exportHasTrace = Boolean(result.preview?.trace?.length)
2077
+ exportTraceOption.hidden = !exportHasTrace
2078
+ exportTrace.checked = false
2079
+ syncSkillChoiceButtons()
1242
2080
  if (result.truncated) status('部分资料已截取。完整内容可在来源文件查看。', false, 'dialog-status')
1243
2081
  } catch (error) {
1244
2082
  if (dialog.open && dialogEpoch === epoch) status(error.message, true, 'dialog-status')
@@ -1253,7 +2091,7 @@ function requestParent(type, values, requestId = `bridge-${Date.now()}-${++reque
1253
2091
  const timer = setTimeout(() => {
1254
2092
  pending = undefined
1255
2093
  reject(new Error('DSH 暂未响应。请重试。'))
1256
- }, 25_000)
2094
+ }, type === 'pick-history-directory' ? 300_000 : 25_000)
1257
2095
  pending = { requestId, timer, resolve, reject }
1258
2096
  try {
1259
2097
  window.parent.postMessage({ type: `dsh-agent-bridge:${type}`, requestId, ...values }, parentOrigin)
@@ -1265,16 +2103,179 @@ function requestParent(type, values, requestId = `bridge-${Date.now()}-${++reque
1265
2103
  })
1266
2104
  }
1267
2105
 
1268
- async function importSession() {
2106
+ async function reloadCurrentDetail(preserve = true) {
2107
+ if (!current || !detail) return false
2108
+ const project = current
2109
+ const revision = detailRevision
2110
+ const loaded = await api('detail', { projectId: project.id })
2111
+ if (revision !== detailRevision || current?.id !== project.id) return false
2112
+ applyDetail(project, loaded, preserve)
2113
+ return true
2114
+ }
2115
+
2116
+ function appliedSkillSummary(result) {
2117
+ const confirmed = result.items.filter(item => item.applied && item.verified && item.canOmitBody).length
2118
+ const disabled = result.items.filter(item => item.applied && item.verified && item.disabled).length
2119
+ const pending = result.items.filter(item => item.applied && !item.verified).length
2120
+ const failed = result.items.filter(item => !item.applied).length
2121
+ const parts = [
2122
+ confirmed ? `已确认 ${confirmed} 项` : '',
2123
+ disabled ? `已登记但当前不可调用 ${disabled} 项` : '',
2124
+ pending ? `待 DSH 确认 ${pending} 项` : '',
2125
+ failed ? `未启用 ${failed} 项` : '',
2126
+ ].filter(Boolean)
2127
+ return parts.length ? `${parts.join(',')}。` : '没有技能被更改。'
2128
+ }
2129
+
2130
+ function setActivationBusy(busy) {
2131
+ activateConfirm.disabled = busy
2132
+ activateText.disabled = busy
2133
+ activateClose.disabled = busy
2134
+ }
2135
+
2136
+ function renderActivationReview(review) {
2137
+ const selectedNames = new Map(context?.entries.map(entry => [entry.id, entry]) ?? [])
2138
+ const panel = text('div', '', 'skill-manager')
2139
+ const lead = text('div', '', 'preview-intro')
2140
+ lead.append(text('p', `目标项目 · ${review.project.name}`, 'preview-lead'))
2141
+ const root = review.projectRoot || detail?.skillProjectRoot || review.project.cwd
2142
+ const rootRow = text('div', '', 'preview-meta')
2143
+ rootRow.append(text('span', '启用范围'), text('code', root))
2144
+ lead.append(rootRow, text('p', '确认后只登记允许的版本;冲突项和确认失败项仍保留文字摘录。', 'preview-context'))
2145
+ panel.append(lead)
2146
+ for (const item of review.items) {
2147
+ const source = selectedNames.get(item.assetId)
2148
+ const block = text('section', '', 'preview-section')
2149
+ block.append(text('h3', `${item.name || item.dshName} → ${item.dshName}`))
2150
+ const state = text('p', '', 'preview-context')
2151
+ state.append(skillStatusNode(item))
2152
+ block.append(state)
2153
+ if (source?.file) block.append(text('code', source.file, 'preview-source'))
2154
+ if (item.fileCount) {
2155
+ block.append(text('p',
2156
+ `${item.fileCount} 个文件 · ${item.resources?.scripts ?? 0} 个脚本 · ${item.resources?.references ?? 0} 个参考 · ${item.resources?.assets ?? 0} 个资源`,
2157
+ 'preview-context'))
2158
+ }
2159
+ if (item.scriptFiles?.length) block.append(text('p', `脚本:${item.scriptFiles.join('、')}`, 'preview-context'))
2160
+ if (item.detail || item.reason) block.append(text('p', item.detail || item.reason, 'preview-context'))
2161
+ panel.append(block)
2162
+ }
2163
+ activateBody.replaceChildren(panel)
2164
+ const confirmable = review.items.filter(actionableSkill).length
2165
+ const already = review.items.filter(item => item.verified && item.canOmitBody
2166
+ && ['reuse-active', 'native'].includes(item.action)).length
2167
+ activateConfirm.hidden = confirmable + already === 0
2168
+ activateConfirm.replaceChildren(
2169
+ document.createTextNode(confirmable ? `确认启用 ${confirmable} 项并继续`
2170
+ : already ? '沿用已发现技能并继续' : '没有可启用项'),
2171
+ icon('arrow'),
2172
+ )
2173
+ activateText.hidden = false
2174
+ activateText.textContent = '仅文字继续'
2175
+ activateStatus.textContent = ''
2176
+ }
2177
+
2178
+ async function beginSkillActivation(purpose) {
2179
+ const project = purpose === 'history' ? historyProject : current
2180
+ if (!project || !dialogSkillIds.size) {
2181
+ await completeHandoff(purpose, [])
2182
+ return
2183
+ }
2184
+ try {
2185
+ const preview = await api('preview-skill-activation', {
2186
+ projectId: project.id, assetIds: [...dialogSkillIds],
2187
+ })
2188
+ activationReview = { ...preview, project, purpose }
2189
+ activationSummary = ''
2190
+ renderActivationReview(activationReview)
2191
+ if (!activateDialog.open) activateDialog.showModal()
2192
+ } catch (error) {
2193
+ status(error.message, true, purpose === 'history' ? 'dialog-status' : 'dialog-status')
2194
+ }
2195
+ }
2196
+
2197
+ async function confirmSkillActivation() {
2198
+ if (!activationReview || activateConfirm.disabled) return
2199
+ setActivationBusy(true)
2200
+ activateStatus.textContent = '正在保存完整技能包…'
2201
+ try {
2202
+ const previewConfirmed = activationReview.items.filter(item => item.verified && item.canOmitBody
2203
+ && ['reuse-active', 'native'].includes(item.action)).map(item => item.assetId)
2204
+ const actionable = activationReview.items.filter(actionableSkill)
2205
+ let appliedItems = []
2206
+ if (actionable.length) {
2207
+ const applied = await api('apply-skill-activation', { ticket: activationReview.ticket })
2208
+ appliedItems = applied.items
2209
+ activationSummary = appliedSkillSummary(applied)
2210
+ } else {
2211
+ activationSummary = previewConfirmed.length ? '沿用已由 DSH 发现的技能。' : ''
2212
+ }
2213
+ const confirmedIds = [
2214
+ ...previewConfirmed,
2215
+ ...appliedItems.filter(item => item.applied && item.verified && item.canOmitBody).map(item => item.assetId),
2216
+ ]
2217
+ const purpose = activationReview.purpose
2218
+ activationReview = undefined
2219
+ activateDialog.close()
2220
+ await completeHandoff(purpose, [...new Set(confirmedIds)])
2221
+ } catch (error) {
2222
+ activateStatus.textContent = error.message
2223
+ } finally {
2224
+ setActivationBusy(false)
2225
+ }
2226
+ }
2227
+
2228
+ async function continueWithTextOnly() {
2229
+ if (!activationReview || activateText.disabled) return
2230
+ const purpose = activationReview.purpose
2231
+ activationReview = undefined
2232
+ activationSummary = '未启用技能,继续使用文字交接。'
2233
+ activateDialog.close()
2234
+ await completeHandoff(purpose, [])
2235
+ }
2236
+
2237
+ async function completeHandoff(purpose, confirmedSkillIds) {
2238
+ if (purpose === 'history') {
2239
+ if (!historyTicket || dialogBusy) return
2240
+ setDialogBusy(true)
2241
+ status(importedSessionId ? '正在打开已迁入的会话…' : '正在迁入会话…', false, 'dialog-status')
2242
+ try {
2243
+ if (!importedSessionId) {
2244
+ historyImportStarted = true
2245
+ const result = await api('import-conversation', { ticket: historyTicket })
2246
+ importedSessionId = result.sessionId
2247
+ }
2248
+ await requestParent('open-imported', { sessionId: importedSessionId })
2249
+ dialog.close()
2250
+ status(`历史已迁入。打开会话即可继续。${activationSummary}`)
2251
+ } catch (error) {
2252
+ if (importedSessionId) byId('history-import-label').textContent = '打开已迁入会话'
2253
+ status(error.message, true, 'dialog-status')
2254
+ } finally {
2255
+ setDialogBusy(false)
2256
+ }
2257
+ return
2258
+ }
2259
+
1269
2260
  if (!ticket || dialogBusy || importButton.hidden) return
1270
2261
  setDialogBusy(true)
1271
2262
  status(draftRecovery ? '正在重试填入草稿…' : '正在创建 DSH 会话…', false, 'dialog-status')
1272
2263
  try {
2264
+ if (confirmedSkillIds.length && previewInput) {
2265
+ try {
2266
+ const revised = await api('preview', { ...previewInput, nativeSkillIds: confirmedSkillIds })
2267
+ ticket = revised.ticket
2268
+ } catch (error) {
2269
+ activationSummary += ` ${error.message} 已保留技能正文。`
2270
+ const revised = await api('preview', previewInput)
2271
+ ticket = revised.ticket
2272
+ }
2273
+ }
1273
2274
  const { path, prompt } = await api('open', { ticket })
1274
2275
  await requestParent('open', { path, prompt, bridgeNonce: nonce }, ticket)
1275
2276
  ticket = undefined
1276
2277
  dialog.close()
1277
- status('DSH 会话已打开。交接草稿已填入输入框。')
2278
+ status(`DSH 会话已打开。交接草稿已填入输入框。${activationSummary}`)
1278
2279
  } catch (error) {
1279
2280
  if (Object.hasOwn(error, 'recoverySessionId')) draftRecovery = error.recoverySessionId
1280
2281
  recoverDraftButton.hidden = !draftRecovery
@@ -1284,6 +2285,151 @@ async function importSession() {
1284
2285
  }
1285
2286
  }
1286
2287
 
2288
+ function renderSkillManager(result, asset) {
2289
+ const item = result.items[0]
2290
+ skillPreviewTicket = result.ticket
2291
+ if (!item) {
2292
+ dialogText.textContent = '没有收到技能状态。'
2293
+ return
2294
+ }
2295
+ const panel = text('div', '', 'skill-manager')
2296
+ const lead = text('div', '', 'preview-intro')
2297
+ lead.append(text('p', item.name || asset.name, 'preview-lead'))
2298
+ const state = text('p', '', 'preview-context')
2299
+ state.append(skillStatusNode(item))
2300
+ lead.append(state)
2301
+ const meta = text('div', '', 'skill-manager-meta')
2302
+ const addMeta = (label, value, code = false) => {
2303
+ if (!value) return
2304
+ const row = text('div', '')
2305
+ row.append(text('span', label), code ? text('code', value) : document.createTextNode(value))
2306
+ meta.append(row)
2307
+ }
2308
+ addMeta('DSH 名称', item.dshName || asset.name, true)
2309
+ addMeta('启用范围', item.scopeRoot || detail?.skillProjectRoot)
2310
+ addMeta('来源', asset.file, true)
2311
+ if (item.fileCount) addMeta('包内容', `${item.fileCount} 个文件 · ${item.resources?.scripts ?? 0} 个脚本 · ${item.resources?.references ?? 0} 个参考 · ${item.resources?.assets ?? 0} 个资源`)
2312
+ lead.append(meta)
2313
+ if (item.detail || item.reason) lead.append(text('p', item.detail || item.reason, 'preview-context'))
2314
+ panel.append(lead)
2315
+ dialogText.dataset.format = 'handoff'
2316
+ dialogText.replaceChildren(panel)
2317
+
2318
+ const canApply = actionableSkill(item)
2319
+ skillApply.hidden = !canApply
2320
+ skillApply.dataset.action = item.action
2321
+ byId('skill-apply-label').textContent = item.action === 'update'
2322
+ ? '更新并切换'
2323
+ : item.action === 'reuse-native' ? '登记复用' : '启用技能'
2324
+ skillDeactivate.hidden = !asset.handoff?.activationId
2325
+ skillUndo.hidden = !(asset.handoff?.activationId && asset.handoff?.canUndo)
2326
+ }
2327
+
2328
+ async function openSkillManager(asset) {
2329
+ if (!current || dialog.open) return
2330
+ const project = current
2331
+ const epoch = showDialog('skill', `技能 · ${materialName(asset)}`, '核对 DSH 名称、启用范围和完整包内容。', '正在核对技能包…', 'skill')
2332
+ skillManagerAsset = asset
2333
+ skillManagerProject = project
2334
+ try {
2335
+ const result = await api('preview-skill-activation', { projectId: project.id, assetIds: [asset.id] })
2336
+ if (!dialog.open || dialogEpoch !== epoch) return
2337
+ renderSkillManager(result, asset)
2338
+ } catch (error) {
2339
+ if (dialog.open && dialogEpoch === epoch) dialogText.textContent = error.message
2340
+ }
2341
+ }
2342
+
2343
+ function openManagedSkill(asset) {
2344
+ if (!current || dialog.open) return
2345
+ const project = current
2346
+ showDialog('skill', `技能 · ${materialName(asset)}`, '核对已保存登记;来源不可扫描时仍可停用。', '', 'skill')
2347
+ skillManagerAsset = asset
2348
+ skillManagerProject = project
2349
+ renderSkillManager({
2350
+ ticket: undefined,
2351
+ items: [{
2352
+ assetId: asset.id,
2353
+ name: asset.name,
2354
+ dshName: asset.handoff.dshName,
2355
+ action: 'manage',
2356
+ label: asset.handoff.label,
2357
+ detail: asset.handoff.detail,
2358
+ reason: asset.handoff.reason,
2359
+ allowed: false,
2360
+ current: true,
2361
+ activationId: asset.handoff.activationId,
2362
+ scopeRoot: detail?.skillProjectRoot,
2363
+ }],
2364
+ }, asset)
2365
+ }
2366
+
2367
+ async function applyManagedSkill() {
2368
+ if (!skillPreviewTicket || dialogBusy) return
2369
+ setDialogBusy(true)
2370
+ status('正在保存完整技能包…', false, 'dialog-status')
2371
+ try {
2372
+ const applied = await api('apply-skill-activation', { ticket: skillPreviewTicket })
2373
+ const failed = applied.items.find(item => !item.applied)
2374
+ if (failed) throw new Error(failed.reason || `${failed.name || '技能'} 未启用。`)
2375
+ skillPreviewTicket = undefined
2376
+ dialog.close()
2377
+ await reloadCurrentDetail(true)
2378
+ status(appliedSkillSummary(applied))
2379
+ } catch (error) {
2380
+ status(error.message, true, 'dialog-status')
2381
+ } finally {
2382
+ setDialogBusy(false)
2383
+ }
2384
+ }
2385
+
2386
+ async function deactivateManagedSkill() {
2387
+ const asset = skillManagerAsset
2388
+ const project = skillManagerProject
2389
+ if (!asset?.handoff?.activationId || !project || dialogBusy) return
2390
+ setDialogBusy(true)
2391
+ try {
2392
+ await api('deactivate-skill-activation', {
2393
+ projectId: project.id, activationId: asset.handoff.activationId,
2394
+ })
2395
+ dialog.close()
2396
+ await reloadCurrentDetail(true)
2397
+ status('已停用当前项目的技能登记;来源文件和 DSH 其他目录未改动。')
2398
+ } catch (error) {
2399
+ status(error.message, true, 'dialog-status')
2400
+ } finally {
2401
+ setDialogBusy(false)
2402
+ }
2403
+ }
2404
+
2405
+ async function undoManagedSkill() {
2406
+ const asset = skillManagerAsset
2407
+ const project = skillManagerProject
2408
+ if (!asset?.handoff?.activationId || !project || dialogBusy) return
2409
+ setDialogBusy(true)
2410
+ try {
2411
+ await api('undo-skill-activation', {
2412
+ projectId: project.id, activationId: asset.handoff.activationId,
2413
+ })
2414
+ dialog.close()
2415
+ await reloadCurrentDetail(true)
2416
+ status('已恢复上一版技能快照。')
2417
+ } catch (error) {
2418
+ status(error.message, true, 'dialog-status')
2419
+ } finally {
2420
+ setDialogBusy(false)
2421
+ }
2422
+ }
2423
+
2424
+ async function importSession() {
2425
+ if (!ticket || dialogBusy || importButton.hidden) return
2426
+ if (dialogSkillIds.size) {
2427
+ await beginSkillActivation('draft')
2428
+ return
2429
+ }
2430
+ await completeHandoff('draft', [])
2431
+ }
2432
+
1287
2433
  async function recoverDraftSession() {
1288
2434
  if (!ticket || !draftRecovery || dialogBusy) return
1289
2435
  setDialogBusy(true)
@@ -1319,13 +2465,36 @@ function selectedNativeSession() {
1319
2465
  return nativeSessions.find(session => session.id === sessionSelect.value)
1320
2466
  }
1321
2467
 
1322
- function renderSessionPath() {
2468
+ async function updateNativeSession() {
2469
+ sessionTraceRequest?.abort()
2470
+ sessionSourceRecord.replaceChildren()
2471
+ exportTrace.checked = false
2472
+ exportTraceOption.hidden = true
1323
2473
  const session = selectedNativeSession()
1324
2474
  byId('session-path').textContent = session?.path ?? ''
2475
+ if (!session) return
2476
+ const request = new AbortController()
2477
+ sessionTraceRequest = request
2478
+ const url = `./session-trace?${new URLSearchParams({ sessionId: session.id })}`
2479
+ try {
2480
+ const response = await fetch(url, { signal: request.signal, headers: { Accept: 'application/json' } })
2481
+ if (response.status === 404) return
2482
+ if (!response.ok) throw new Error('无法读取来源记录。')
2483
+ const { trace = [], sourceStats, traceCounts, history } = await response.json()
2484
+ if (request.signal.aborted) return
2485
+ if (trace.length || sourceStats) sessionSourceRecord.append(renderSourceStats(sourceStats, traceCounts))
2486
+ if (history) sessionSourceRecord.append(sourceArchive(history, { sessionId: session.id }))
2487
+ if (trace.length) {
2488
+ sessionSourceRecord.append(sessionTraceDisclosure(trace))
2489
+ exportTraceOption.hidden = false
2490
+ }
2491
+ } catch {
2492
+ if (!request.signal.aborted) sessionSourceRecord.append(text('p', '暂时无法读取来源记录。', 'muted'))
2493
+ }
1325
2494
  }
1326
2495
 
1327
2496
  async function chooseNativeSession() {
1328
- showDialog('session', '导出 DSH 会话', '将会话中的用户与助手消息保存为 Markdown。', '正在读取 DSH 会话…')
2497
+ showDialog('session', '导出 DSH 会话', '可查阅已保存的来源记录,或将会话保存为 Markdown。', '正在读取 DSH 会话…')
1329
2498
  setDialogBusy(true)
1330
2499
  try {
1331
2500
  const result = await requestParent('sessions', {})
@@ -1341,10 +2510,11 @@ async function chooseNativeSession() {
1341
2510
  const suffix = titles.get(session.title) > 1 && session.path ? ` · ${shortPath(session.path)}` : ''
1342
2511
  return new Option(title + suffix, session.id)
1343
2512
  }))
1344
- renderSessionPath()
2513
+ void updateNativeSession()
1345
2514
  dialogText.hidden = true
1346
2515
  byId('session-choice').hidden = false
1347
2516
  exportButton.hidden = false
2517
+ exportShareButton.hidden = false
1348
2518
  } catch (error) {
1349
2519
  dialogText.hidden = true
1350
2520
  status(error.message, true, 'dialog-status')
@@ -1353,18 +2523,19 @@ async function chooseNativeSession() {
1353
2523
  }
1354
2524
  }
1355
2525
 
1356
- async function exportMarkdown() {
2526
+ async function exportMarkdown(format = 'local') {
1357
2527
  if (dialogBusy || exportButton.hidden) return
1358
2528
  setDialogBusy(true)
1359
- status('正在生成 Markdown…', false, 'dialog-status')
2529
+ status(`正在生成${format === 'share' ? '分享版' : '本机版'} Markdown…`, false, 'dialog-status')
2530
+ const includeTrace = exportTraceOption.hidden ? false : exportTrace.checked
1360
2531
  try {
1361
2532
  if (dialogMode === 'session') {
1362
2533
  const session = selectedNativeSession()
1363
2534
  if (!session) throw new Error('请选择要导出的 DSH 会话。')
1364
2535
  const result = await requestParent('session-export', { sessionId: session.id, path: session.path })
1365
- showDownload(await api('export-session', { conversation: result.conversation }))
2536
+ showDownload(await api('export-session', { sessionId: session.id, conversation: result.conversation, format, includeTrace }))
1366
2537
  } else if (ticket) {
1367
- showDownload(await api('export', { ticket }))
2538
+ showDownload(await api('export', { ticket, format, includeTrace }))
1368
2539
  }
1369
2540
  } catch (error) {
1370
2541
  status(error.message, true, 'dialog-status')
@@ -1373,6 +2544,44 @@ async function exportMarkdown() {
1373
2544
  }
1374
2545
  }
1375
2546
 
2547
+ // Paths are only opened after the Host re-checks them against the current
2548
+ // project. The panel never passes a raw path to the shell by itself.
2549
+ async function openPath({ projectId = current?.id, label, assetId, referenceId, directory = false }) {
2550
+ if (!projectId) return
2551
+ const statusId = dialog.open ? 'dialog-status' : 'status'
2552
+ try {
2553
+ const result = await requestParent('open-path', { projectId, directory, assetId, referenceId, bridgeNonce: nonce })
2554
+ status(`已在 DSH 中${result.revealed ? '定位' : '打开'}${label ? `「${label}」` : ''}。`, false, statusId)
2555
+ } catch (error) {
2556
+ status(`${error.message} 可复制路径后手动打开。`, true, statusId)
2557
+ }
2558
+ }
2559
+
2560
+ function pathActions({ label, path, assetId, directory = false }) {
2561
+ const group = text('span', '', 'path-actions')
2562
+ const open = text('button', '', 'path-open')
2563
+ open.type = 'button'
2564
+ open.append(icon('folder'), text('span', '打开'))
2565
+ open.setAttribute('aria-label', `在 DSH 中打开${label ? ` ${label}` : ''}`)
2566
+ open.title = path || label || '打开'
2567
+ open.addEventListener('click', () => { void openPath({ label, assetId, directory }) })
2568
+ const copy = text('button', '', 'path-copy')
2569
+ copy.type = 'button'
2570
+ copy.append(icon('copy'))
2571
+ copy.setAttribute('aria-label', `复制${label ? ` ${label}` : ''}路径`)
2572
+ copy.title = '复制路径'
2573
+ copy.addEventListener('click', async () => {
2574
+ try {
2575
+ await navigator.clipboard.writeText(path ?? '')
2576
+ status('路径已复制。')
2577
+ } catch {
2578
+ status('无法访问剪贴板,请手动选择路径复制。', true)
2579
+ }
2580
+ })
2581
+ group.append(open, copy)
2582
+ return group
2583
+ }
2584
+
1376
2585
  async function copyProjectPath() {
1377
2586
  if (!current) return
1378
2587
  const button = byId('copy-path')
@@ -1492,6 +2701,7 @@ document.addEventListener('keydown', event => {
1492
2701
  if (event.key !== '/' || event.ctrlKey || event.metaKey || event.altKey || dialog.open || !agentPopover.hidden
1493
2702
  || event.target.matches?.('input, select, textarea, [contenteditable]')) return
1494
2703
  event.preventDefault()
2704
+ if (compactLayout.matches) expandProjectIndex(true)
1495
2705
  projectSearch.focus()
1496
2706
  })
1497
2707
  projectList.addEventListener('keydown', event => {
@@ -1513,6 +2723,10 @@ historyOption.addEventListener('change', () => {
1513
2723
  void saveProjectSelection()
1514
2724
  })
1515
2725
  byId('copy-path').addEventListener('click', copyProjectPath)
2726
+ byId('open-path').addEventListener('click', () => {
2727
+ if (!current) return
2728
+ void openPath({ label: '工作目录', path: current.cwd, directory: true })
2729
+ })
1516
2730
  byId('preview').addEventListener('click', preview)
1517
2731
  byId('native-export').addEventListener('click', chooseNativeSession)
1518
2732
  browseHistory.addEventListener('click', chooseSourceConversation)
@@ -1524,15 +2738,10 @@ function searchHistory() {
1524
2738
  }
1525
2739
  historySearch.addEventListener('input', searchHistory)
1526
2740
  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
- })
2741
+ byId('history-more').addEventListener('click', moreHistoryResults)
1533
2742
  historyImport.addEventListener('click', importSourceConversation)
1534
2743
  sessionSelect.addEventListener('change', clearDownload)
1535
- sessionSelect.addEventListener('change', renderSessionPath)
2744
+ sessionSelect.addEventListener('change', updateNativeSession)
1536
2745
  dialogClose.addEventListener('click', () => dialog.close())
1537
2746
  dialog.addEventListener('click', event => {
1538
2747
  if (event.target !== dialog || dialogBusy) return
@@ -1543,15 +2752,29 @@ dialog.addEventListener('click', event => {
1543
2752
  dialog.addEventListener('cancel', event => { if (dialogBusy) event.preventDefault() })
1544
2753
  dialog.addEventListener('close', () => {
1545
2754
  ++dialogEpoch
2755
+ releaseHistoryPreview()
2756
+ if (!dialog.open) sessionTraceRequest?.abort()
2757
+ if (activateDialog.open) activateDialog.close()
1546
2758
  clearDownload()
1547
2759
  liveState('正在恢复实时扫描')
1548
2760
  schedulePoll(0)
1549
2761
  })
1550
2762
  importButton.addEventListener('click', importSession)
1551
2763
  recoverDraftButton.addEventListener('click', recoverDraftSession)
1552
- exportButton.addEventListener('click', exportMarkdown)
2764
+ skillApply.addEventListener('click', applyManagedSkill)
2765
+ skillUndo.addEventListener('click', undoManagedSkill)
2766
+ skillDeactivate.addEventListener('click', deactivateManagedSkill)
2767
+ activateConfirm.addEventListener('click', confirmSkillActivation)
2768
+ activateText.addEventListener('click', continueWithTextOnly)
2769
+ activateClose.addEventListener('click', () => { if (!activateConfirm.disabled) activateDialog.close() })
2770
+ activateDialog.addEventListener('cancel', event => { if (activateConfirm.disabled) event.preventDefault() })
2771
+ activateDialog.addEventListener('click', event => {
2772
+ if (event.target === activateDialog && !activateConfirm.disabled) activateDialog.close()
2773
+ })
2774
+ exportButton.addEventListener('click', () => { void exportMarkdown('local') })
2775
+ exportShareButton.addEventListener('click', () => { void exportMarkdown('share') })
1553
2776
  document.addEventListener('visibilitychange', () => schedulePoll(0))
1554
- for (const button of themeOptions) button.addEventListener('click', () => setTheme(button.dataset.themeChoice))
2777
+ appearance.addEventListener('change', () => setTheme(appearance.value))
1555
2778
  let savedTheme
1556
2779
  try { savedTheme = localStorage.getItem(themeKey) } catch { /* Use the default theme. */ }
1557
2780
  setTheme(savedTheme, false)