@wwwfz/dsh-agent-bridge 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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')
@@ -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,6 +115,7 @@ 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
@@ -112,6 +128,15 @@ let draftRecovery
112
128
  let historyPreview = 0
113
129
  let downloadUrl
114
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
115
140
 
116
141
  const clockFormat = new Intl.DateTimeFormat('zh-CN', { timeStyle: 'medium', hourCycle: 'h23' })
117
142
  const historyDateFormat = new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium', timeStyle: 'short' })
@@ -126,6 +151,52 @@ const text = (tag, content, className) => {
126
151
  return element
127
152
  }
128
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
+
129
200
  function icon(name, className = '') {
130
201
  const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
131
202
  svg.setAttribute('class', className ? `icon ${className}` : 'icon')
@@ -633,6 +704,69 @@ function matchesMaterial(asset, query) {
633
704
  .some(value => value?.toLowerCase().includes(query))
634
705
  }
635
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
+
636
770
  function renderGlobalCount() {
637
771
  const assets = context.entries.filter(asset => asset.global)
638
772
  const query = assetSearch.value.trim().toLowerCase()
@@ -650,6 +784,7 @@ function makeMaterialRow(asset) {
650
784
  checkbox.className = 'asset-check'
651
785
  checkbox.id = `asset-${asset.id}`
652
786
  checkbox.checked = selected.has(asset.id)
787
+ checkbox.disabled = Boolean(asset.managedOnly)
653
788
  row.dataset.selected = String(checkbox.checked)
654
789
  checkbox.addEventListener('change', () => {
655
790
  if (checkbox.checked && selected.size >= 24) {
@@ -670,6 +805,12 @@ function makeMaterialRow(asset) {
670
805
  const title = text('span', name, 'asset-title')
671
806
  const meta = text('span', '', 'asset-meta')
672
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
+ }
673
814
  if (!asset.global && context.suggestedIds.includes(asset.id)) {
674
815
  meta.append(text('span', '建议带入', 'material-suggestion'))
675
816
  } else if (asset.global && asset.used) {
@@ -677,14 +818,40 @@ function makeMaterialRow(asset) {
677
818
  }
678
819
  label.append(title, meta)
679
820
  const button = text('button', '', 'asset-view')
680
- button.append(document.createTextNode('查看'), icon('chevron'))
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'))
681
830
  button.type = 'button'
682
831
  button.id = `asset-view-${asset.id}`
683
- button.setAttribute('aria-label', `查看 ${name}`)
684
- button.addEventListener('click', () => viewAsset(asset))
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
+ })
685
838
  const marker = text('span', '', 'asset-icon')
686
839
  marker.append(icon(asset.kind))
687
- row.append(checkbox, marker, label, button)
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)
688
855
  return row
689
856
  }
690
857
 
@@ -725,8 +892,48 @@ function renderAssets() {
725
892
 
726
893
  function applyDetail(project, loaded, preserve) {
727
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] }
728
932
  detail = loaded
729
933
  context = describeProjectContext(loaded)
934
+ for (const entry of context.entries) {
935
+ if (entry.managedOnly) entry.group = 'managed'
936
+ }
730
937
  if (!preserve) {
731
938
  const saved = projectSelections.get(project.id) ?? loaded.selection
732
939
  if (saved) {
@@ -737,7 +944,7 @@ function applyDetail(project, loaded, preserve) {
737
944
  includeHistory = false
738
945
  }
739
946
  }
740
- const available = new Set(context.entries.map(item => item.id))
947
+ const available = new Set(context.entries.filter(item => !item.managedOnly).map(item => item.id))
741
948
  selected = new Set([...selected].filter(id => available.has(id)))
742
949
  historyOption.checked = includeHistory && detail.historyCount > 0
743
950
  historyOption.disabled = detail.historyCount === 0
@@ -1025,9 +1232,14 @@ function setDialogBusy(busy) {
1025
1232
  importButton.disabled = busy
1026
1233
  recoverDraftButton.disabled = busy
1027
1234
  exportButton.disabled = busy
1235
+ exportShareButton.disabled = busy
1236
+ exportTrace.disabled = busy
1028
1237
  sessionSelect.disabled = busy
1029
1238
  byId('history-back-button').disabled = busy
1030
1239
  historyImport.disabled = busy
1240
+ skillApply.disabled = busy
1241
+ skillUndo.disabled = busy
1242
+ skillDeactivate.disabled = busy
1031
1243
  }
1032
1244
 
1033
1245
  function showDialog(mode, title, note, body, assetKind = 'memory') {
@@ -1035,16 +1247,30 @@ function showDialog(mode, title, note, body, assetKind = 'memory') {
1035
1247
  dialog.dataset.mode = mode
1036
1248
  ticket = undefined
1037
1249
  nativeSessions = []
1250
+ sessionTraceRequest?.abort()
1251
+ sessionSourceRecord.replaceChildren()
1038
1252
  historyProject = undefined
1039
1253
  historySessions = undefined
1040
1254
  historyChosenId = undefined
1041
1255
  historyTicket = undefined
1042
1256
  importedSessionId = undefined
1043
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()
1044
1267
  clearDownload()
1045
1268
  byId('dialog-title').textContent = title
1046
1269
  byId('dialog-note').textContent = note
1047
- byId('dialog-mark').replaceChildren(icon(mode === 'session' ? 'download' : mode === 'asset' ? assetKind : mode === 'history' ? 'history' : 'bridge'))
1270
+ byId('dialog-mark').replaceChildren(icon(mode === 'session' ? 'download'
1271
+ : mode === 'asset' ? assetKind
1272
+ : mode === 'history' ? 'history'
1273
+ : mode === 'skill' ? 'skill' : 'bridge'))
1048
1274
  dialogText.hidden = false
1049
1275
  dialogText.dataset.format = 'plain'
1050
1276
  dialogText.textContent = body
@@ -1056,7 +1282,13 @@ function showDialog(mode, title, note, body, assetKind = 'memory') {
1056
1282
  importButton.hidden = true
1057
1283
  recoverDraftButton.hidden = true
1058
1284
  exportButton.hidden = true
1285
+ exportShareButton.hidden = true
1286
+ exportTraceOption.hidden = true
1287
+ exportTrace.checked = false
1059
1288
  historyImport.hidden = true
1289
+ skillApply.hidden = true
1290
+ skillUndo.hidden = true
1291
+ skillDeactivate.hidden = true
1060
1292
  setDialogBusy(false)
1061
1293
  if (!dialog.open) dialog.showModal()
1062
1294
  clearTimeout(pollTimer)
@@ -1072,7 +1304,7 @@ function startHistoryDialog(title, note, body) {
1072
1304
  return epoch
1073
1305
  }
1074
1306
 
1075
- const historyNote = '迁入用户与助手的文字消息。工具记录、附件和运行状态留在来源 Agent。'
1307
+ const historyNote = '迁入用户与助手的文字消息,并保留可读取的思考摘要与工具记录,只供查阅。'
1076
1308
 
1077
1309
  function openSourceConversation(session) {
1078
1310
  if (startHistoryDialog('继续旧对话', historyNote, '正在读取这条对话…') === undefined) return
@@ -1110,6 +1342,8 @@ function showHistoryResults() {
1110
1342
  historyTicket = undefined
1111
1343
  importedSessionId = undefined
1112
1344
  historyImport.hidden = true
1345
+ dialogSkillCandidates = []
1346
+ dialogSkillIds = new Set()
1113
1347
  byId('history-back').hidden = true
1114
1348
  byId('dialog-title').textContent = '查看全部对话'
1115
1349
  byId('dialog-note').textContent = '选择一条对话以预览历史消息。'
@@ -1122,6 +1356,126 @@ function showHistoryResults() {
1122
1356
  ;(previous || historySearch).focus()
1123
1357
  }
1124
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
+
1125
1479
  async function previewSourceConversation(session) {
1126
1480
  const epoch = dialogEpoch
1127
1481
  const revision = ++historyPreview
@@ -1148,19 +1502,31 @@ async function previewSourceConversation(session) {
1148
1502
  const title = text('h3', result.title, 'preview-lead')
1149
1503
  const source = text('p', '', 'preview-context history-source')
1150
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
+ }
1151
1512
  const summary = text('p', [
1152
- result.messages.length + ' 条文字消息',
1153
1513
  result.truncated ? '源记录或读取范围有限,部分历史未带入' : '',
1154
1514
  result.canImport ? '' : '原工作目录不可访问,当前可预览',
1155
1515
  ].filter(Boolean).join(' · '), 'preview-context')
1156
1516
  dialogText.dataset.format = 'history'
1157
- dialogText.replaceChildren(title, source, summary, ...result.messages.map(message => {
1517
+ dialogText.replaceChildren(title, source, stats, ...(summary.textContent ? [summary] : []), ...(skillChoices ? [skillChoices] : []), ...result.messages.map((message, index) => {
1158
1518
  const row = text('section', '', 'history-message')
1159
1519
  row.dataset.role = message.role
1160
- row.append(text('h3', message.role === 'user' ? '用户' : '助手'), text('p', message.text, 'preview-body'))
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))
1161
1526
  return row
1162
1527
  }))
1163
1528
  historyImport.hidden = !result.canImport
1529
+ syncSkillChoiceButtons()
1164
1530
  } catch (error) {
1165
1531
  if (dialog.open && dialogEpoch === epoch && revision === historyPreview) dialogText.textContent = error.message
1166
1532
  }
@@ -1168,25 +1534,14 @@ async function previewSourceConversation(session) {
1168
1534
 
1169
1535
  async function importSourceConversation() {
1170
1536
  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)
1537
+ if (!importedSessionId && dialogSkillIds.size) {
1538
+ await beginSkillActivation('history')
1539
+ return
1186
1540
  }
1541
+ await completeHandoff('history', [])
1187
1542
  }
1188
1543
 
1189
- function renderHandoff({ intro, sections, footer }) {
1544
+ function renderHandoff({ intro, sections, footer, cwd }, skillCandidates = []) {
1190
1545
  const lead = text('div', '', 'preview-intro')
1191
1546
  const [heading, ...introLines] = intro.split('\n')
1192
1547
  lead.append(text('p', heading, 'preview-lead'))
@@ -1195,6 +1550,9 @@ function renderHandoff({ intro, sections, footer }) {
1195
1550
  if (metadata) {
1196
1551
  const row = text('div', '', 'preview-meta')
1197
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
+ }
1198
1556
  lead.append(row)
1199
1557
  } else if (line) lead.append(text('p', line, 'preview-context'))
1200
1558
  }
@@ -1203,13 +1561,28 @@ function renderHandoff({ intro, sections, footer }) {
1203
1561
  const content = sections.map(section => {
1204
1562
  const block = text('section', '', 'preview-section')
1205
1563
  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'))
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)
1208
1579
  return block
1209
1580
  })
1581
+ const skillChoices = renderSkillChoices(skillCandidates)
1210
1582
  dialogText.dataset.format = 'handoff'
1211
- dialogText.replaceChildren(lead, ...content)
1583
+ dialogText.replaceChildren(lead, ...(skillChoices ? [skillChoices] : []), ...content)
1212
1584
  if (footer) dialogText.append(text('p', footer, 'preview-context'))
1585
+ syncSkillChoiceButtons()
1213
1586
  }
1214
1587
 
1215
1588
  async function viewAsset(asset) {
@@ -1218,9 +1591,18 @@ async function viewAsset(asset) {
1218
1591
  try {
1219
1592
  const result = await api('asset', { projectId: project.id, assetId: asset.id })
1220
1593
  if (!dialog.open || dialogEpoch !== epoch) return
1221
- dialogText.textContent = result.text + (result.truncated ? '\n\n[预览已截取]' : '')
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
+ }
1222
1601
  } catch (error) {
1223
- if (dialog.open && dialogEpoch === epoch) status(error.message, true, 'dialog-status')
1602
+ if (dialog.open && dialogEpoch === epoch) {
1603
+ dialogText.dataset.format = 'plain'
1604
+ dialogText.textContent = error.message
1605
+ }
1224
1606
  }
1225
1607
  }
1226
1608
 
@@ -1232,13 +1614,20 @@ async function preview() {
1232
1614
  : '原工作目录不可访问。可将现有交接资料导出为 Markdown。'
1233
1615
  const epoch = showDialog('handoff', `草稿预览 · ${project.name}`, note, '正在准备…')
1234
1616
  try {
1235
- const result = await api('preview', { projectId: project.id, assetIds: [...selected], history: historyOption.checked })
1617
+ const input = { projectId: project.id, assetIds: [...selected], history: historyOption.checked }
1618
+ previewInput = input
1619
+ const result = await api('preview', input)
1236
1620
  if (!dialog.open || dialogEpoch !== epoch) return
1237
1621
  ticket = result.ticket
1238
- if (result.preview) renderHandoff(result.preview)
1622
+ if (result.preview) renderHandoff(result.preview, result.skillCandidates)
1239
1623
  else dialogText.textContent = result.prompt
1240
1624
  importButton.hidden = result.canImport === false || !project.online
1241
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()
1242
1631
  if (result.truncated) status('部分资料已截取。完整内容可在来源文件查看。', false, 'dialog-status')
1243
1632
  } catch (error) {
1244
1633
  if (dialog.open && dialogEpoch === epoch) status(error.message, true, 'dialog-status')
@@ -1265,16 +1654,178 @@ function requestParent(type, values, requestId = `bridge-${Date.now()}-${++reque
1265
1654
  })
1266
1655
  }
1267
1656
 
1268
- async function importSession() {
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
+
1269
1810
  if (!ticket || dialogBusy || importButton.hidden) return
1270
1811
  setDialogBusy(true)
1271
1812
  status(draftRecovery ? '正在重试填入草稿…' : '正在创建 DSH 会话…', false, 'dialog-status')
1272
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
+ }
1273
1824
  const { path, prompt } = await api('open', { ticket })
1274
1825
  await requestParent('open', { path, prompt, bridgeNonce: nonce }, ticket)
1275
1826
  ticket = undefined
1276
1827
  dialog.close()
1277
- status('DSH 会话已打开。交接草稿已填入输入框。')
1828
+ status(`DSH 会话已打开。交接草稿已填入输入框。${activationSummary}`)
1278
1829
  } catch (error) {
1279
1830
  if (Object.hasOwn(error, 'recoverySessionId')) draftRecovery = error.recoverySessionId
1280
1831
  recoverDraftButton.hidden = !draftRecovery
@@ -1284,6 +1835,151 @@ async function importSession() {
1284
1835
  }
1285
1836
  }
1286
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
+
1287
1983
  async function recoverDraftSession() {
1288
1984
  if (!ticket || !draftRecovery || dialogBusy) return
1289
1985
  setDialogBusy(true)
@@ -1319,13 +2015,35 @@ function selectedNativeSession() {
1319
2015
  return nativeSessions.find(session => session.id === sessionSelect.value)
1320
2016
  }
1321
2017
 
1322
- function renderSessionPath() {
2018
+ async function updateNativeSession() {
2019
+ sessionTraceRequest?.abort()
2020
+ sessionSourceRecord.replaceChildren()
2021
+ exportTrace.checked = false
2022
+ exportTraceOption.hidden = true
1323
2023
  const session = selectedNativeSession()
1324
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
+ }
1325
2043
  }
1326
2044
 
1327
2045
  async function chooseNativeSession() {
1328
- showDialog('session', '导出 DSH 会话', '将会话中的用户与助手消息保存为 Markdown。', '正在读取 DSH 会话…')
2046
+ showDialog('session', '导出 DSH 会话', '可查阅已保存的来源记录,或将会话保存为 Markdown。', '正在读取 DSH 会话…')
1329
2047
  setDialogBusy(true)
1330
2048
  try {
1331
2049
  const result = await requestParent('sessions', {})
@@ -1341,10 +2059,11 @@ async function chooseNativeSession() {
1341
2059
  const suffix = titles.get(session.title) > 1 && session.path ? ` · ${shortPath(session.path)}` : ''
1342
2060
  return new Option(title + suffix, session.id)
1343
2061
  }))
1344
- renderSessionPath()
2062
+ void updateNativeSession()
1345
2063
  dialogText.hidden = true
1346
2064
  byId('session-choice').hidden = false
1347
2065
  exportButton.hidden = false
2066
+ exportShareButton.hidden = false
1348
2067
  } catch (error) {
1349
2068
  dialogText.hidden = true
1350
2069
  status(error.message, true, 'dialog-status')
@@ -1353,18 +2072,19 @@ async function chooseNativeSession() {
1353
2072
  }
1354
2073
  }
1355
2074
 
1356
- async function exportMarkdown() {
2075
+ async function exportMarkdown(format = 'local') {
1357
2076
  if (dialogBusy || exportButton.hidden) return
1358
2077
  setDialogBusy(true)
1359
- status('正在生成 Markdown…', false, 'dialog-status')
2078
+ status(`正在生成${format === 'share' ? '分享版' : '本机版'} Markdown…`, false, 'dialog-status')
2079
+ const includeTrace = exportTraceOption.hidden ? false : exportTrace.checked
1360
2080
  try {
1361
2081
  if (dialogMode === 'session') {
1362
2082
  const session = selectedNativeSession()
1363
2083
  if (!session) throw new Error('请选择要导出的 DSH 会话。')
1364
2084
  const result = await requestParent('session-export', { sessionId: session.id, path: session.path })
1365
- showDownload(await api('export-session', { conversation: result.conversation }))
2085
+ showDownload(await api('export-session', { sessionId: session.id, conversation: result.conversation, format, includeTrace }))
1366
2086
  } else if (ticket) {
1367
- showDownload(await api('export', { ticket }))
2087
+ showDownload(await api('export', { ticket, format, includeTrace }))
1368
2088
  }
1369
2089
  } catch (error) {
1370
2090
  status(error.message, true, 'dialog-status')
@@ -1373,6 +2093,44 @@ async function exportMarkdown() {
1373
2093
  }
1374
2094
  }
1375
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
+
1376
2134
  async function copyProjectPath() {
1377
2135
  if (!current) return
1378
2136
  const button = byId('copy-path')
@@ -1513,6 +2271,10 @@ historyOption.addEventListener('change', () => {
1513
2271
  void saveProjectSelection()
1514
2272
  })
1515
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
+ })
1516
2278
  byId('preview').addEventListener('click', preview)
1517
2279
  byId('native-export').addEventListener('click', chooseNativeSession)
1518
2280
  browseHistory.addEventListener('click', chooseSourceConversation)
@@ -1532,7 +2294,7 @@ byId('history-more').addEventListener('click', () => {
1532
2294
  })
1533
2295
  historyImport.addEventListener('click', importSourceConversation)
1534
2296
  sessionSelect.addEventListener('change', clearDownload)
1535
- sessionSelect.addEventListener('change', renderSessionPath)
2297
+ sessionSelect.addEventListener('change', updateNativeSession)
1536
2298
  dialogClose.addEventListener('click', () => dialog.close())
1537
2299
  dialog.addEventListener('click', event => {
1538
2300
  if (event.target !== dialog || dialogBusy) return
@@ -1543,13 +2305,26 @@ dialog.addEventListener('click', event => {
1543
2305
  dialog.addEventListener('cancel', event => { if (dialogBusy) event.preventDefault() })
1544
2306
  dialog.addEventListener('close', () => {
1545
2307
  ++dialogEpoch
2308
+ if (!dialog.open) sessionTraceRequest?.abort()
2309
+ if (activateDialog.open) activateDialog.close()
1546
2310
  clearDownload()
1547
2311
  liveState('正在恢复实时扫描')
1548
2312
  schedulePoll(0)
1549
2313
  })
1550
2314
  importButton.addEventListener('click', importSession)
1551
2315
  recoverDraftButton.addEventListener('click', recoverDraftSession)
1552
- exportButton.addEventListener('click', exportMarkdown)
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') })
1553
2328
  document.addEventListener('visibilitychange', () => schedulePoll(0))
1554
2329
  for (const button of themeOptions) button.addEventListener('click', () => setTheme(button.dataset.themeChoice))
1555
2330
  let savedTheme