@wwwfz/dsh-agent-bridge 0.10.0 → 0.11.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,5 +1,7 @@
1
1
  import { describeProjectContext } from './project-context.js'
2
2
  import { isMarkdownFile, renderMarkdown } from './markdown.js'
3
+ import { loadSourceSharePreview, openShareReview } from './share-review.js'
4
+ import { relayCategories } from './relay-categories.js'
3
5
 
4
6
  const byId = id => document.getElementById(id)
5
7
  const nonce = document.querySelector('meta[name=bridge-nonce]').content
@@ -25,8 +27,14 @@ const dialogText = byId('dialog-text')
25
27
  const sessionSelect = byId('session-select')
26
28
  const sessionSourceRecord = byId('session-source-record')
27
29
  const historySearch = byId('history-search')
30
+ const historySearchScope = byId('history-search-scope')
28
31
  const historyResults = byId('history-results')
29
32
  const historyImport = byId('history-import')
33
+ const relayReturn = byId('relay-return')
34
+ const relayPick = byId('relay-pick')
35
+ const relayExport = byId('relay-export')
36
+ const historyCopyButton = byId('history-copy')
37
+ const historyOpenExisting = byId('history-open-existing')
30
38
  const refreshButton = byId('refresh')
31
39
  const agentFilter = byId('agent-filter')
32
40
  const agentPicker = byId('agent-picker')
@@ -119,19 +127,33 @@ let sessionTraceRequest
119
127
  let recentRevision = 0
120
128
  let recentKey = ''
121
129
  let historyProject
130
+ let relayPicking = false
122
131
  let historySessions
123
132
  let historyUnavailable = []
124
133
  let historyCursor
125
134
  let historyPaging = false
126
135
  let historyLimit = 30
127
136
  let historyChosenId
137
+ let historySource
138
+ let historyLastImport
139
+ let historyCopy = false
128
140
  let historyTicket
129
141
  let historySnapshotId
130
142
  let historyImportStarted = false
131
143
  let importedSessionId
132
144
  let draftRecovery
133
145
  let historyPreview = 0
146
+ let historySearchTimer
147
+ let historySearchRequest
148
+ let historyBodySearch
149
+ let historyContext
150
+ let historyContextReady = true
151
+ let historyContextView
152
+ let historyContextRevision = 0
153
+ const historyExcerpts = new Map()
154
+ const heldHistorySnapshots = new Map()
134
155
  let downloadUrl
156
+ let closeShareReview
135
157
  let requestNumber = 0
136
158
  let dialogSkillCandidates = []
137
159
  let dialogSkillIds = new Set()
@@ -365,15 +387,20 @@ function syncSearch(input) {
365
387
  if (hint) hint.hidden = Boolean(input.value)
366
388
  }
367
389
 
368
- async function api(action, values = {}, { keepalive = false } = {}) {
390
+ async function api(action, values = {}, { keepalive = false, signal } = {}) {
369
391
  const response = await fetch('./api', {
370
392
  method: 'POST',
371
393
  headers: { 'Content-Type': 'application/json', 'X-DSH-Agent-Bridge': nonce },
372
394
  body: JSON.stringify({ action, ...values }),
373
- keepalive,
395
+ keepalive, signal,
374
396
  })
375
397
  const data = await response.json().catch(() => null)
376
- if (!response.ok || !data) throw new Error(data?.error || '无法连接 DSH 插件。')
398
+ if (!response.ok || !data) {
399
+ const error = new Error(data?.error || '无法连接 DSH 插件。')
400
+ error.status = response.status
401
+ if (typeof data?.recoveryTicket === 'string') error.recoveryTicket = data.recoveryTicket
402
+ throw error
403
+ }
377
404
  return data
378
405
  }
379
406
 
@@ -730,7 +757,8 @@ function syncSkillChoiceButtons() {
730
757
  if (historyImport.hidden === false) {
731
758
  byId('history-import-label').textContent = importedSessionId
732
759
  ? '打开已迁入会话'
733
- : count ? `启用 ${count} 项并继续` : '迁入并继续'
760
+ : count ? `启用 ${count} 项并${historyCopy ? '迁入副本' : '继续'}`
761
+ : historyCopy ? '迁入副本并继续' : '迁入并继续'
734
762
  }
735
763
  if (importButton.hidden === false) {
736
764
  importButton.replaceChildren(
@@ -1003,6 +1031,18 @@ function revealProjectDetail() {
1003
1031
  heading.closest('.detail').scrollIntoView({ block: 'start', behavior: reducedMotion.matches ? 'instant' : 'smooth' })
1004
1032
  }
1005
1033
 
1034
+ function renderImportTime(element, lastImport) {
1035
+ element.replaceChildren()
1036
+ if (!lastImport) return
1037
+ const date = new Date(lastImport.importedAt)
1038
+ if (!Number.isFinite(date.getTime())) return
1039
+ const time = text('time', historyDateFormat.format(date))
1040
+ time.dateTime = date.toISOString()
1041
+ element.append(lastImport.approximate ? '上次迁入约 ' : '上次迁入 ', time)
1042
+ if (!lastImport.sessionId) element.append(' · 已有会话不可用')
1043
+ else if (lastImport.older) element.append(' · 可打开上一份')
1044
+ }
1045
+
1006
1046
  function makeConversationRow(session, open) {
1007
1047
  const row = text('li', '', 'conversation-item')
1008
1048
  const button = text('button', '', 'conversation-row')
@@ -1028,11 +1068,32 @@ function makeConversationRow(session, open) {
1028
1068
  meta.append(text('span', ' · '), timestamp)
1029
1069
  }
1030
1070
  info.append(text('span', title, 'conversation-title'), meta)
1071
+ if (session.snippet) {
1072
+ meta.append(text('span', ` · 第 ${session.turn} 轮 · ${session.role === 'user' ? '用户' : '助手'}`))
1073
+ const snippet = text('span', '', 'history-match-snippet')
1074
+ const end = session.matchStart + session.matchLength
1075
+ snippet.append(session.snippet.slice(0, session.matchStart),
1076
+ text('mark', session.snippet.slice(session.matchStart, end)), session.snippet.slice(end))
1077
+ info.append(snippet)
1078
+ }
1079
+ if (session.lastImport) {
1080
+ const migrated = text('span', '', 'conversation-meta conversation-import-time')
1081
+ renderImportTime(migrated, session.lastImport)
1082
+ info.append(migrated)
1083
+ }
1084
+ const hasExisting = Boolean(session.lastImport?.sessionId)
1031
1085
  const action = text('span', '', 'conversation-action')
1032
- action.append(text('span', '预览'), icon('chevron'))
1086
+ action.append(text('span', session.snippet ? '跳到回合' : hasExisting ? '打开已有会话' : '预览'), icon('chevron'))
1033
1087
  button.append(agentMark(session.agent), info, action)
1034
1088
  button.addEventListener('click', () => open(session))
1035
1089
  row.append(button)
1090
+ if (hasExisting && !session.snippet) {
1091
+ const copy = text('button', '另开副本', 'text-action conversation-copy')
1092
+ copy.type = 'button'
1093
+ copy.setAttribute('aria-label', `另开副本:${title}`)
1094
+ copy.addEventListener('click', () => open(session, { duplicate: true }))
1095
+ row.append(copy)
1096
+ }
1036
1097
  return row
1037
1098
  }
1038
1099
 
@@ -1060,7 +1121,7 @@ async function loadRecentConversations(project) {
1060
1121
  const key = JSON.stringify(sessions)
1061
1122
  if (key !== recentKey) {
1062
1123
  const active = recentList.contains(document.activeElement) ? document.activeElement.dataset.session : ''
1063
- recentList.replaceChildren(...sessions.map(session => makeConversationRow(session, item => openSourceConversation(item))))
1124
+ recentList.replaceChildren(...sessions.map(session => makeConversationRow(session, openSourceConversation)))
1064
1125
  if (active) ([...recentList.querySelectorAll('button')].find(button => button.dataset.session === active)
1065
1126
  ?? byId('continue-heading')).focus({ preventScroll: true })
1066
1127
  recentKey = key
@@ -1072,8 +1133,8 @@ async function loadRecentConversations(project) {
1072
1133
  : scanning ? '已扫描的部分暂无可迁入对话。' : '这个项目还没有可迁入的对话。可以用项目资料开新对话。',
1073
1134
  unavailable.length ? `${unavailable.length} 条来源无法读取。` : '',
1074
1135
  ].filter(Boolean).join(' ')
1075
- byId('browse-history-label').textContent = scanning ? `查看对话(已确认 ${count} 条)` : `查看全部 ${count} 条对话`
1076
- browseHistory.hidden = count <= sessions.length && !scanning && !unavailable.length
1136
+ byId('browse-history-label').textContent = count ? `搜索 ${count} 条对话` : '搜索和查看对话'
1137
+ browseHistory.hidden = !count && !scanning && !unavailable.length
1077
1138
  } catch {
1078
1139
  if (!isCurrent()) return
1079
1140
  recentStatus.textContent = recentList.childElementCount
@@ -1258,8 +1319,12 @@ function setDialogBusy(busy) {
1258
1319
  exportTrace.disabled = busy
1259
1320
  sessionSelect.disabled = busy
1260
1321
  byId('history-back-button').disabled = busy
1261
- historyImport.disabled = busy
1262
- for (const field of dialogText.querySelectorAll('.history-target-form input, .history-target-form button')) field.disabled = busy
1322
+ historyOpenExisting.disabled = busy
1323
+ historyCopyButton.disabled = busy
1324
+ historyImport.disabled = busy || !historyContextReady
1325
+ for (const field of dialogText.querySelectorAll('.history-target-form input, .history-target-form button, [data-history-excerpt]')) {
1326
+ field.disabled = busy || (field.hasAttribute('data-history-excerpt') && historyImportStarted)
1327
+ }
1263
1328
  skillApply.disabled = busy
1264
1329
  skillUndo.disabled = busy
1265
1330
  skillDeactivate.disabled = busy
@@ -1268,14 +1333,36 @@ function setDialogBusy(busy) {
1268
1333
  function releaseHistoryPreview() {
1269
1334
  const snapshotId = historySnapshotId
1270
1335
  historySnapshotId = undefined
1271
- if (snapshotId && !historyImportStarted) {
1272
- void api('discard-conversation-preview', { snapshotId }, { keepalive: true }).catch(() => {})
1336
+ if (snapshotId && !historyImportStarted && ![...historyExcerpts.values()].some(item => item.snapshotId === snapshotId)) {
1337
+ discardHistorySnapshot(snapshotId)
1273
1338
  }
1274
1339
  historyImportStarted = false
1275
1340
  }
1276
1341
 
1342
+ function discardHistorySnapshot(snapshotId) {
1343
+ heldHistorySnapshots.delete(snapshotId)
1344
+ void api('discard-conversation-preview', { snapshotId }, { keepalive: true }).catch(() => {})
1345
+ }
1346
+
1347
+ function resetHistorySearch() {
1348
+ clearTimeout(historySearchTimer)
1349
+ historySearchRequest?.abort()
1350
+ historyBodySearch = undefined
1351
+ historyExcerpts.clear()
1352
+ for (const snapshotId of heldHistorySnapshots.keys()) discardHistorySnapshot(snapshotId)
1353
+ byId('history-selected-count').textContent = ''
1354
+ historyContext = undefined
1355
+ historyContextView = undefined
1356
+ historyContextReady = true
1357
+ historyContextRevision++
1358
+ historySource = undefined
1359
+ historyLastImport = undefined
1360
+ historyCopy = false
1361
+ }
1362
+
1277
1363
  function showDialog(mode, title, note, body, assetKind = 'memory') {
1278
1364
  releaseHistoryPreview()
1365
+ resetHistorySearch()
1279
1366
  dialogMode = mode
1280
1367
  dialog.dataset.mode = mode
1281
1368
  ticket = undefined
@@ -1283,6 +1370,10 @@ function showDialog(mode, title, note, body, assetKind = 'memory') {
1283
1370
  sessionTraceRequest?.abort()
1284
1371
  sessionSourceRecord.replaceChildren()
1285
1372
  historyProject = undefined
1373
+ relayPicking = false
1374
+ relayReturn.hidden = true
1375
+ relayPick.hidden = true
1376
+ relayExport.hidden = true
1286
1377
  historySessions = undefined
1287
1378
  historyUnavailable = []
1288
1379
  historyCursor = undefined
@@ -1323,6 +1414,8 @@ function showDialog(mode, title, note, body, assetKind = 'memory') {
1323
1414
  exportTraceOption.hidden = true
1324
1415
  exportTrace.checked = false
1325
1416
  historyImport.hidden = true
1417
+ historyOpenExisting.hidden = true
1418
+ historyCopyButton.hidden = true
1326
1419
  skillApply.hidden = true
1327
1420
  skillUndo.hidden = true
1328
1421
  skillDeactivate.hidden = true
@@ -1338,19 +1431,27 @@ function startHistoryDialog(title, note, body) {
1338
1431
  if (dialog.open || !project || !nativeSessionImport || !filteredProjects().some(item => item.id === project.id)) return
1339
1432
  const epoch = showDialog('history', title, note, body)
1340
1433
  historyProject = project
1434
+ relayReturn.hidden = false
1341
1435
  return epoch
1342
1436
  }
1343
1437
 
1344
1438
  const historyNote = '核对旧对话,再迁入 DSH 继续。工具记录可在来源历史中查阅。'
1345
1439
 
1346
- function openSourceConversation(session) {
1440
+ function openSourceConversation(session, options) {
1347
1441
  if (startHistoryDialog('继续旧对话', historyNote, '正在读取这条对话…') === undefined) return
1348
- void previewSourceConversation(session)
1442
+ void previewSourceConversation(session, options)
1349
1443
  }
1350
1444
 
1351
- async function chooseSourceConversation() {
1352
- const epoch = startHistoryDialog('查看全部对话', '选择一条对话以预览历史消息。', '正在读取对话列表…')
1445
+ async function chooseSourceConversation(picking = false) {
1446
+ const epoch = picking && current
1447
+ ? showDialog('history', '从对话选内容', '打开会话,在完整历史中添加条目。', '正在读取对话列表…')
1448
+ : startHistoryDialog('查看全部对话', '选择一条对话以预览历史消息。', '正在读取对话列表…')
1353
1449
  if (epoch === undefined) return
1450
+ if (picking) {
1451
+ historyProject = current
1452
+ relayPicking = true
1453
+ relayReturn.hidden = false
1454
+ }
1354
1455
  try {
1355
1456
  const { sessions, nextCursor, unavailable = [] } = await api('list-conversations', { projectId: historyProject.id })
1356
1457
  if (!dialog.open || dialogEpoch !== epoch) return
@@ -1358,6 +1459,8 @@ async function chooseSourceConversation() {
1358
1459
  historyUnavailable = unavailable
1359
1460
  historyCursor = nextCursor
1360
1461
  historySearch.value = ''
1462
+ historySearchScope.value = 'body'
1463
+ historySearch.placeholder = '搜本项目的对话正文'
1361
1464
  historyLimit = 30
1362
1465
  showHistoryResults()
1363
1466
  } catch (error) {
@@ -1372,8 +1475,24 @@ function historyMatches(sessions) {
1372
1475
 
1373
1476
  function renderHistoryResults() {
1374
1477
  syncSearch(historySearch)
1478
+ byId('history-selected-count').textContent = historyExcerpts.size ? `已选 ${historyExcerpts.size} 段摘录` : ''
1479
+ if (historyBodySearch) {
1480
+ const { matches, loading, error, incomplete, nextCursor } = historyBodySearch
1481
+ historyResults.replaceChildren(...matches.map(hit => makeConversationRow(hit, () =>
1482
+ previewSourceConversation(hit, { searchHit: hit }))))
1483
+ byId('history-unavailable').hidden = true
1484
+ byId('history-empty').textContent = error || (loading ? '正在搜索正文…' :
1485
+ [matches.length ? `找到 ${matches.length} 处匹配` : nextCursor ? '已搜索的对话暂无匹配' : '没有找到匹配的正文',
1486
+ incomplete ? '部分来源无法完整读取' : ''].filter(Boolean).join(' · '))
1487
+ const more = byId('history-more')
1488
+ more.hidden = !nextCursor && !error
1489
+ more.disabled = loading
1490
+ more.textContent = error ? '重试搜索' : '继续搜索'
1491
+ return
1492
+ }
1375
1493
  const matches = historyMatches(historySessions)
1376
- historyResults.replaceChildren(...matches.slice(0, historyLimit).map(session => makeConversationRow(session, previewSourceConversation)))
1494
+ historyResults.replaceChildren(...matches.slice(0, historyLimit).map(session => makeConversationRow(
1495
+ relayPicking ? { ...session, lastImport: undefined } : session, previewSourceConversation)))
1377
1496
  byId('history-empty').textContent = matches.length ? ''
1378
1497
  : historyCursor ? '已扫描的部分暂无匹配项,可继续扫描。'
1379
1498
  : historySearch.value.trim() ? '没有找到匹配的对话。' : '这个项目暂无可迁入的对话。'
@@ -1393,6 +1512,10 @@ function renderHistoryResults() {
1393
1512
  }
1394
1513
 
1395
1514
  async function moreHistoryResults() {
1515
+ if (historyBodySearch) {
1516
+ await loadBodySearch(historyBodySearch)
1517
+ return
1518
+ }
1396
1519
  if (historyPaging) return
1397
1520
  const index = historyResults.childElementCount
1398
1521
  if (Math.max(historyMatches(historySessions).length, historyMatches(historyUnavailable).length) <= historyLimit && historyCursor) {
@@ -1423,6 +1546,40 @@ async function moreHistoryResults() {
1423
1546
  historyResults.children[index]?.querySelector('button')?.focus()
1424
1547
  }
1425
1548
 
1549
+ async function loadBodySearch(search) {
1550
+ if (search !== historyBodySearch || byId('history-choice').hidden) return
1551
+ historySearchRequest?.abort()
1552
+ const controller = new AbortController()
1553
+ historySearchRequest = controller
1554
+ search.loading = true
1555
+ search.error = ''
1556
+ renderHistoryResults()
1557
+ try {
1558
+ let result
1559
+ do {
1560
+ result = await api('search-conversations', {
1561
+ projectId: historyProject.id, query: search.query, cursor: search.nextCursor,
1562
+ }, { signal: controller.signal })
1563
+ if (search !== historyBodySearch || controller.signal.aborted) return
1564
+ search.matches.push(...result.matches)
1565
+ search.incomplete ||= result.incomplete
1566
+ search.nextCursor = result.nextCursor
1567
+ } while (!result.matches.length && search.nextCursor && !byId('history-choice').hidden)
1568
+ } catch (error) {
1569
+ if (!controller.signal.aborted) {
1570
+ search.error = error.message
1571
+ search.nextCursor = undefined
1572
+ search.matches = []
1573
+ search.incomplete = false
1574
+ }
1575
+ } finally {
1576
+ if (search === historyBodySearch && !controller.signal.aborted) {
1577
+ search.loading = false
1578
+ if (!byId('history-choice').hidden) renderHistoryResults()
1579
+ }
1580
+ }
1581
+ }
1582
+
1426
1583
  function showHistoryResults() {
1427
1584
  if (!historySessions) return
1428
1585
  releaseHistoryPreview()
@@ -1430,11 +1587,13 @@ function showHistoryResults() {
1430
1587
  historyTicket = undefined
1431
1588
  importedSessionId = undefined
1432
1589
  historyImport.hidden = true
1590
+ historyOpenExisting.hidden = true
1591
+ historyCopyButton.hidden = true
1433
1592
  dialogSkillCandidates = []
1434
1593
  dialogSkillIds = new Set()
1435
1594
  byId('history-back').hidden = true
1436
- byId('dialog-title').textContent = '查看全部对话'
1437
- byId('dialog-note').textContent = '选择一条对话以预览历史消息。'
1595
+ byId('dialog-title').textContent = '搜索项目对话'
1596
+ byId('dialog-note').textContent = '搜索正文,或选择一条对话预览。'
1438
1597
  dialogText.hidden = true
1439
1598
  byId('history-choice').hidden = false
1440
1599
  status('', false, 'dialog-status')
@@ -1602,7 +1761,7 @@ function archiveButton(label, action) {
1602
1761
  return button
1603
1762
  }
1604
1763
 
1605
- function sourceArchive(history, { sessionId, snapshotId, ticket } = {}) {
1764
+ function sourceArchive(history, { sessionId, snapshotId, ticket, location, selectExcerpts = false } = {}) {
1606
1765
  const section = text('details', '', 'source-archive bridge-reader')
1607
1766
  section.append(text('summary', '完整历史', 'reader-summary'))
1608
1767
  const info = text('p', '', 'reader-note')
@@ -1651,14 +1810,16 @@ function sourceArchive(history, { sessionId, snapshotId, ticket } = {}) {
1651
1810
  withTools.type = 'checkbox'
1652
1811
  option.append(withTools, document.createTextNode(' 附带工具和摘要'))
1653
1812
  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
- }
1813
+ const local = text('a', '下载来源全文(本机版)', 'reader-button')
1814
+ const setUrl = () => { local.href = archiveUrl('conversation-export', sessionId, { format: 'local', includeTrace: String(withTools.checked) }) }
1815
+ local.download = ''
1816
+ withTools.addEventListener('change', setUrl)
1817
+ setUrl()
1818
+ const share = archiveButton('审阅来源全文(分享版)', () => {
1819
+ const url = archiveUrl('conversation-share-preview', sessionId, { includeTrace: String(withTools.checked) })
1820
+ reviewShare(signal => loadSourceSharePreview(url, signal))
1821
+ })
1822
+ exports.append(local, share)
1662
1823
  downloads.append(text('summary', '导出来源全文', 'reader-summary'), exports)
1663
1824
  section.append(downloads)
1664
1825
  }
@@ -1686,6 +1847,11 @@ function sourceArchive(history, { sessionId, snapshotId, ticket } = {}) {
1686
1847
 
1687
1848
  function renderItem(item) {
1688
1849
  const row = text('article', '', 'history-message reader-row')
1850
+ if (location && item.seq === location.seq && item.offset === location.offset) {
1851
+ row.classList.add('history-jump-match')
1852
+ row.tabIndex = -1
1853
+ row.setAttribute('aria-label', `匹配的来源记录,第 ${location.turn} 轮`)
1854
+ }
1689
1855
  if (item.role) row.dataset.role = item.role
1690
1856
  if (item.kind === 'gap') {
1691
1857
  row.append(text('p', archiveIssue(item.reason), 'reader-body'))
@@ -1723,6 +1889,36 @@ function sourceArchive(history, { sessionId, snapshotId, ticket } = {}) {
1723
1889
  })
1724
1890
  const actions = text('div', '', 'reader-actions')
1725
1891
  actions.append(copy)
1892
+ if (snapshotId && historyProject && item.turn && ['message','tool_result','tool_call','summary'].includes(item.kind)) {
1893
+ const projectId = historyProject.id
1894
+ const category = relaySelect('unresolved', '添加到接力分类')
1895
+ const add = archiveButton('加入接力单', async () => {
1896
+ add.disabled = true
1897
+ try {
1898
+ const saved = await api('add-relay-item', { projectId, snapshotId, seq: item.seq,
1899
+ offset: item.offset ?? 0, category: category.value })
1900
+ add.textContent = '已加入接力单'
1901
+ readError.textContent = `已加入「${relayCategories[saved.category]}」。`
1902
+ } catch (error) {
1903
+ readError.textContent = error.message
1904
+ add.disabled = false
1905
+ }
1906
+ })
1907
+ actions.append(category, add)
1908
+ }
1909
+ if (selectExcerpts && ['message', 'tool_call', 'tool_result', 'summary'].includes(item.kind)) {
1910
+ const excerpt = { snapshotId, seq: item.seq, offset: item.offset ?? 0,
1911
+ title: byId('dialog-text').querySelector('.preview-lead')?.textContent, turn: item.turn, text: item.text }
1912
+ const label = text('label', '', 'history-excerpt-option')
1913
+ const input = document.createElement('input')
1914
+ input.type = 'checkbox'
1915
+ input.dataset.historyExcerpt = excerptKey(excerpt)
1916
+ input.checked = historyExcerpts.has(input.dataset.historyExcerpt)
1917
+ input.disabled = dialogBusy || historyImportStarted
1918
+ input.addEventListener('change', () => void toggleHistoryExcerpt(excerpt, input.checked))
1919
+ label.append(input, document.createTextNode(`带入续聊${item.continued || item.offset ? '(本段)' : ''}`))
1920
+ actions.append(label)
1921
+ }
1726
1922
  if (sessionId && item.text.length <= 65_536) {
1727
1923
  actions.append(archiveButton('引用到草稿', async event => {
1728
1924
  const button = event.currentTarget
@@ -1766,6 +1962,7 @@ function sourceArchive(history, { sessionId, snapshotId, ticket } = {}) {
1766
1962
  rows.push(disclosure)
1767
1963
  }
1768
1964
  group.contents.append(row)
1965
+ if (row.classList.contains('history-jump-match')) group.contents.parentElement.open = true
1769
1966
  group.records.add(item.seq ?? item)
1770
1967
  }
1771
1968
  for (const group of groups.values()) {
@@ -1789,6 +1986,13 @@ function sourceArchive(history, { sessionId, snapshotId, ticket } = {}) {
1789
1986
  explain(page.history ?? history)
1790
1987
  result.replaceChildren(...renderPage(page.items))
1791
1988
  result.scrollTop = 0
1989
+ if (locator === location && section.isConnected && section.open) {
1990
+ const match = result.querySelector('.history-jump-match')
1991
+ if (match) {
1992
+ match.focus({ preventScroll: true })
1993
+ match.scrollIntoView({ block: 'nearest' })
1994
+ }
1995
+ }
1792
1996
  if (!page.items.length) result.append(text('p', '这页暂无来源记录。', 'muted'))
1793
1997
  if (position === 0) locators.length = 1
1794
1998
  locators[position] = locator
@@ -1802,12 +2006,91 @@ function sourceArchive(history, { sessionId, snapshotId, ticket } = {}) {
1802
2006
  }
1803
2007
  }
1804
2008
 
1805
- section.addEventListener('toggle', () => { if (section.open && index < 0) void load(0, {}) })
2009
+ section.addEventListener('toggle', () => { if (section.open && index < 0) void load(0, location ?? {}) })
2010
+ if (location) {
2011
+ turn.value = location.turn
2012
+ section.open = true
2013
+ }
1806
2014
  explain(history)
1807
2015
  syncControls()
1808
2016
  return section
1809
2017
  }
1810
2018
 
2019
+ function excerptKey({ snapshotId, seq, offset }) {
2020
+ return `${snapshotId}:${seq}:${offset}`
2021
+ }
2022
+
2023
+ function renderContextSelection() {
2024
+ if (!historyContextView) return
2025
+ const { list, first, baseText, locked } = historyContextView
2026
+ const items = locked ? historyContext?.items ?? [] : [...historyExcerpts.values()]
2027
+ list.hidden = !items.length
2028
+ list.replaceChildren(...items.map(item => {
2029
+ const row = text('li', '', 'history-excerpt')
2030
+ const excerpt = item.text.replace(/\s+/g, ' ')
2031
+ const label = [item.title, item.turn && `第 ${item.turn} 轮`].filter(Boolean).join(' · ')
2032
+ row.append(text('span', `${label} · ${excerpt.slice(0, 72)}${excerpt.length > 72 ? '…' : ''}`))
2033
+ if (!locked) {
2034
+ const remove = archiveButton('移除', () => void toggleHistoryExcerpt(item, false))
2035
+ remove.dataset.historyExcerpt = excerptKey(item)
2036
+ remove.disabled = dialogBusy || historyImportStarted
2037
+ row.append(remove)
2038
+ }
2039
+ return row
2040
+ }))
2041
+ if (first) first.textContent = historyContext?.firstMessage ?? baseText
2042
+ for (const input of dialogText.querySelectorAll('input[data-history-excerpt]')) {
2043
+ input.checked = historyExcerpts.has(input.dataset.historyExcerpt)
2044
+ }
2045
+ historyImport.disabled = dialogBusy || !historyContextReady
2046
+ }
2047
+
2048
+ async function reviewHistoryContext() {
2049
+ const revision = ++historyContextRevision
2050
+ const preview = historyPreview
2051
+ const epoch = dialogEpoch
2052
+ const ticket = historySnapshotId
2053
+ historyContextReady = false
2054
+ historyContext = undefined
2055
+ renderContextSelection()
2056
+ const view = historyContextView
2057
+ view.note.textContent = '正在生成续聊预览…'
2058
+ const excerpts = [...historyExcerpts.values()].map(({ snapshotId, seq, offset }) => ({ snapshotId, seq, offset }))
2059
+ const active = () => revision === historyContextRevision && preview === historyPreview && epoch === dialogEpoch && dialog.open
2060
+ try {
2061
+ const result = await api('preview-conversation-context', { ticket, excerpts })
2062
+ if (!active()) return
2063
+ historyContext = result
2064
+ historyContextReady = true
2065
+ view.note.textContent = view.description
2066
+ } catch (error) {
2067
+ if (!active()) return
2068
+ view.note.textContent = error.message
2069
+ } finally {
2070
+ if (active()) renderContextSelection()
2071
+ }
2072
+ }
2073
+
2074
+ function toggleHistoryExcerpt(excerpt, selected) {
2075
+ if (dialogBusy || historyImportStarted || !historyContextView) return
2076
+ const key = excerptKey(excerpt)
2077
+ if (selected) {
2078
+ if (!historyExcerpts.has(key) && historyExcerpts.size >= 8) {
2079
+ historyContextView.note.textContent = '每次最多带入 8 段摘录。'
2080
+ renderContextSelection()
2081
+ return
2082
+ }
2083
+ historyExcerpts.set(key, excerpt)
2084
+ heldHistorySnapshots.set(excerpt.snapshotId, historyChosenId)
2085
+ historyContextView.section.open = true
2086
+ } else {
2087
+ historyExcerpts.delete(key)
2088
+ if (excerpt.snapshotId !== historySnapshotId
2089
+ && ![...historyExcerpts.values()].some(item => item.snapshotId === excerpt.snapshotId)) discardHistorySnapshot(excerpt.snapshotId)
2090
+ }
2091
+ return reviewHistoryContext()
2092
+ }
2093
+
1811
2094
  function renderSourceStats(stats, counts = {}, { preview = false } = {}) {
1812
2095
  const section = text('details', '', 'bridge-reader bridge-stats')
1813
2096
  section.open = !stats
@@ -1855,21 +2138,81 @@ function renderSourceStats(stats, counts = {}, { preview = false } = {}) {
1855
2138
  return section
1856
2139
  }
1857
2140
 
1858
- async function previewSourceConversation(session, targetCwd) {
2141
+ function syncHistoryActions() {
2142
+ const existing = Boolean(historyLastImport?.sessionId)
2143
+ historyOpenExisting.hidden = !existing || Boolean(importedSessionId)
2144
+ historyOpenExisting.classList.toggle('primary', !historyCopy)
2145
+ historyOpenExisting.classList.toggle('secondary', historyCopy)
2146
+ historyCopyButton.hidden = !historyLastImport || historyCopy || Boolean(importedSessionId)
2147
+ || (!existing && Boolean(historySnapshotId))
2148
+ historyImport.hidden = !historyTicket || (existing && !historyCopy && !importedSessionId)
2149
+ const importTime = byId('history-import-info')
2150
+ if (importTime) {
2151
+ renderImportTime(importTime, historyLastImport)
2152
+ importTime.hidden = !historyLastImport
2153
+ }
2154
+ syncSkillChoiceButtons()
2155
+ }
2156
+
2157
+ async function openHistoryExisting(verifiedImport) {
2158
+ if (dialogBusy || !historySource) return
2159
+ setDialogBusy(true)
2160
+ status('正在打开已有 DSH 会话…', false, 'dialog-status')
2161
+ try {
2162
+ const { lastImport } = verifiedImport ? { lastImport: verifiedImport } : await api('conversation-import-status', {
2163
+ projectId: historyProject.id, sessionId: historySource.id,
2164
+ })
2165
+ if (lastImport) historyLastImport = lastImport
2166
+ else if (historyLastImport) historyLastImport = { ...historyLastImport, sessionId: null }
2167
+ syncHistoryActions()
2168
+ if (!lastImport?.sessionId) {
2169
+ status('已有会话暂不可用。可以从来源重新迁入。', true, 'dialog-status')
2170
+ return
2171
+ }
2172
+ await requestParent('open-imported', { sessionId: lastImport.sessionId })
2173
+ dialog.close()
2174
+ status('已打开已有的 DSH 会话。')
2175
+ } catch (error) {
2176
+ status(error.message, true, 'dialog-status')
2177
+ } finally {
2178
+ setDialogBusy(false)
2179
+ }
2180
+ }
2181
+
2182
+ function chooseHistoryCopy() {
2183
+ if (dialogBusy || !historySource || !historyLastImport) return
2184
+ if (!historySnapshotId) {
2185
+ void previewSourceConversation(historySource, { duplicate: true })
2186
+ return
2187
+ }
2188
+ historyCopy = true
2189
+ byId('dialog-title').textContent = '另开副本'
2190
+ syncHistoryActions()
2191
+ status('', false, 'dialog-status')
2192
+ if (!historyImport.hidden && !historyImport.disabled) historyImport.focus()
2193
+ }
2194
+
2195
+ async function previewSourceConversation(session, { targetCwd, searchHit, relayId, duplicate = false, refreshTicket, recoveryTicket } = {}) {
1859
2196
  const epoch = dialogEpoch
1860
2197
  const revision = ++historyPreview
1861
- if (targetCwd) {
2198
+ const updating = Boolean(targetCwd || refreshTicket)
2199
+ if (updating) {
1862
2200
  setDialogBusy(true)
1863
2201
  } else {
1864
2202
  releaseHistoryPreview()
2203
+ historySource = session
2204
+ historyCopy = duplicate
2205
+ historyLastImport = undefined
1865
2206
  historyChosenId = session.id
1866
2207
  historyTicket = undefined
1867
2208
  importedSessionId = undefined
1868
2209
  historyImport.hidden = true
2210
+ historyOpenExisting.hidden = true
2211
+ historyCopyButton.hidden = true
1869
2212
  byId('history-import-label').textContent = '迁入并继续'
1870
2213
  byId('history-choice').hidden = true
1871
2214
  byId('history-back').hidden = !historySessions
1872
- byId('dialog-title').textContent = '继续旧对话'
2215
+ byId('dialog-title').textContent = duplicate ? '另开副本' : '继续旧对话'
1873
2216
  byId('dialog-note').textContent = historyNote
1874
2217
  dialogText.hidden = false
1875
2218
  dialogText.dataset.format = 'plain'
@@ -1881,20 +2224,51 @@ async function previewSourceConversation(session, targetCwd) {
1881
2224
  status('', false, 'dialog-status')
1882
2225
  const active = () => dialog.open && dialogEpoch === epoch && revision === historyPreview
1883
2226
  try {
1884
- const result = await api('preview-conversation', {
1885
- projectId: historyProject.id, sessionId: session.id,
1886
- ...(targetCwd ? { targetCwd, snapshotId: historySnapshotId } : {}),
1887
- })
2227
+ const previousSnapshot = refreshTicket ?? (targetCwd ? historySnapshotId
2228
+ : [...heldHistorySnapshots].find(([, sourceId]) => sourceId === session.id)?.[0])
2229
+ const identifiers = { projectId: historyProject.id, sessionId: session.id }
2230
+ const result = recoveryTicket
2231
+ ? await api('retarget-failed-conversation', { ...identifiers, ticket: recoveryTicket, targetCwd })
2232
+ : await api('preview-conversation', {
2233
+ ...identifiers,
2234
+ ...(previousSnapshot ? { snapshotId: previousSnapshot } : {}),
2235
+ ...(targetCwd ? { targetCwd } : {}),
2236
+ ...(searchHit ? { searchHit } : {}),
2237
+ ...(relayId ? { relayId } : {}),
2238
+ ...(relayPicking || refreshTicket ? { inspectSource: true } : {}),
2239
+ ...(duplicate ? { duplicate: true } : {}),
2240
+ })
1888
2241
  const snapshotId = result.history?.snapshotId
1889
2242
  if (!active()) {
1890
- if (snapshotId && !result.resumePending) void api('discard-conversation-preview', { snapshotId }).catch(() => {})
2243
+ if (snapshotId && !result.resumePending && !heldHistorySnapshots.has(snapshotId)) discardHistorySnapshot(snapshotId)
1891
2244
  return
1892
2245
  }
2246
+ if (targetCwd && previousSnapshot && previousSnapshot !== snapshotId && !result.resumePending
2247
+ && heldHistorySnapshots.has(previousSnapshot)) {
2248
+ const moved = [...historyExcerpts.values()].map(item =>
2249
+ item.snapshotId === previousSnapshot ? { ...item, snapshotId } : item)
2250
+ historyExcerpts.clear()
2251
+ for (const item of moved) {
2252
+ historyExcerpts.set(excerptKey(item), item)
2253
+ }
2254
+ heldHistorySnapshots.delete(previousSnapshot)
2255
+ heldHistorySnapshots.set(snapshotId, session.id)
2256
+ }
1893
2257
  if (snapshotId !== historySnapshotId) releaseHistoryPreview()
1894
2258
  historySnapshotId = snapshotId
1895
2259
  historyImportStarted = result.resumePending === true
1896
2260
  historyTicket = result.ticket
1897
- const title = text('h3', result.title, 'preview-lead')
2261
+ historyLastImport = result.lastImport
2262
+ const title = text('h3', result.title || session.title || '未命名对话', 'preview-lead')
2263
+ const importTime = text('p', '', 'preview-context')
2264
+ importTime.id = 'history-import-info'
2265
+ if (result.openExisting) {
2266
+ dialogText.dataset.format = 'history'
2267
+ dialogText.replaceChildren(title, importTime)
2268
+ syncHistoryActions()
2269
+ await openHistoryExisting(result.lastImport)
2270
+ return
2271
+ }
1898
2272
  const source = text('p', '', 'preview-context history-source')
1899
2273
  const original = result.sourceCwd ?? result.cwd ?? historyProject.cwd
1900
2274
  source.append(agentLabel(session.agent), text('span', '原工作目录'), text('code', original, 'preview-source'))
@@ -1902,7 +2276,9 @@ async function previewSourceConversation(session, targetCwd) {
1902
2276
  if (result.targetCwd && result.targetCwd !== original) {
1903
2277
  target.append(text('span', '迁入目录'), text('code', result.targetCwd, 'preview-source'))
1904
2278
  }
1905
- const directory = result.history && !result.resumePending ? text('details', '', 'source-archive') : undefined
2279
+ const canRetarget = Boolean(result.recoveryTicket)
2280
+ const lockedContext = result.resumePending || result.continuationLocked
2281
+ const directory = result.history && (!result.resumePending || canRetarget) ? text('details', '', 'source-archive') : undefined
1906
2282
  if (directory) {
1907
2283
  const form = text('form', '', 'history-target-form')
1908
2284
  const input = document.createElement('input')
@@ -1919,7 +2295,10 @@ async function previewSourceConversation(session, targetCwd) {
1919
2295
  for (const project of catalog.filter(project => project.online)) {
1920
2296
  suggested.append(new Option(project.name, project.cwd))
1921
2297
  }
1922
- const verify = text('button', '核对目录', 'secondary')
2298
+ const verifyDirectory = path => previewSourceConversation(session, {
2299
+ targetCwd: path, duplicate: historyCopy, recoveryTicket: result.recoveryTicket,
2300
+ })
2301
+ const verify = text('button', canRetarget ? '放弃旧目录并核对新目录' : '核对目录', 'secondary')
1923
2302
  verify.type = 'submit'
1924
2303
  const browse = archiveButton('浏览本机目录', async () => {
1925
2304
  if (dialogBusy) return
@@ -1929,7 +2308,7 @@ async function previewSourceConversation(session, targetCwd) {
1929
2308
  const { path } = await requestParent('pick-history-directory')
1930
2309
  if (path && form.isConnected) {
1931
2310
  input.value = path
1932
- await previewSourceConversation(session, path)
2311
+ if (!canRetarget) await verifyDirectory(path)
1933
2312
  }
1934
2313
  } catch (error) {
1935
2314
  status(error.message, true, 'dialog-status')
@@ -1940,49 +2319,68 @@ async function previewSourceConversation(session, targetCwd) {
1940
2319
  form.append(input, suggested, browse, verify)
1941
2320
  form.addEventListener('submit', event => {
1942
2321
  event.preventDefault()
1943
- if (!dialogBusy && input.value.trim()) void previewSourceConversation(session, input.value.trim())
2322
+ if (!dialogBusy && input.value.trim()) {
2323
+ void verifyDirectory(input.value.trim())
2324
+ }
1944
2325
  })
1945
- directory.open = !result.canImport
1946
- directory.append(text('summary', '选择迁入目录'), form)
2326
+ directory.open = !result.canImport || canRetarget
2327
+ directory.append(text('summary', canRetarget ? '重新选择迁入目录' : '选择迁入目录'))
2328
+ if (canRetarget) {
2329
+ directory.append(text('p', 'DSH 尚未写入这条会话。选择目录后,已核对的摘录会保留,确认预览后再迁入。', 'preview-context'))
2330
+ }
2331
+ directory.append(form)
1947
2332
  }
1948
2333
  const skillChoices = renderSkillChoices(result.skillCandidates, { history: true })
1949
2334
  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
- }
1955
2335
  const summary = text('p', [
1956
2336
  result.truncated && !result.history ? '源记录或读取范围有限,部分历史未带入' : '',
1957
- result.canImport ? '' : '原工作目录不可访问,可以先预览或核对新的迁入目录',
1958
- result.resumePending ? '上次迁入尚未完成,可在同一会话继续。' : '',
2337
+ !result.canImport && !result.resumePending ? '原工作目录不可访问,可以先预览或核对新的迁入目录' : '',
2338
+ result.resumePending && !canRetarget ? '上次迁入尚未完成,请使用原迁入目录重试。' : '',
2339
+ result.searchHitStale ? '来源已更新,请返回重新搜索。' : '',
2340
+ result.relayLocationChanged ? '原摘录已有变化,请核对来源回合。' : '',
1959
2341
  ].filter(Boolean).join(' · '), 'preview-context')
1960
- dialogText.dataset.format = 'history'
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) => {
2342
+ historyContext = result.continuation
2343
+ historyContextReady = true
2344
+ const context = text('details', '', 'source-archive history-context')
2345
+ context.open = !result.historyLocation
2346
+ const description = (historyLastImport?.sessionId
2347
+ ? '另开副本时会带入以下历史和已选摘录。'
2348
+ : '以下是插件写入的续聊历史。') + '发送时,DSH 会加入当前模式的配置和你新输入的消息。'
2349
+ const note = text('p', description, 'preview-context')
2350
+ note.setAttribute('role', 'status')
2351
+ const list = text('ul', '', 'history-excerpt-list')
2352
+ list.setAttribute('aria-label', '已选续聊摘录')
2353
+ const messageRows = text('div', '', 'history-context-messages')
2354
+ let first
2355
+ for (const [index, message] of result.messages.entries()) {
1964
2356
  const row = text('section', '', 'history-message')
1965
2357
  row.dataset.role = message.role
1966
- const body = message.role === 'assistant'
1967
- ? markdownBody(message.text, 'preview-body')
1968
- : text('p', message.text, 'preview-body')
2358
+ const body = text('div', message.text, 'preview-body history-context-body')
2359
+ if (index === 0) first = body
1969
2360
  row.append(text('h3', message.role === 'user' ? '用户' : '助手'), body)
1970
- const items = traceByMessage.get(index)
1971
- if (items?.length) row.append(traceDisclosure(items))
1972
- return row
1973
- }))
1974
- historyImport.hidden = !result.canImport
1975
- syncSkillChoiceButtons()
2361
+ messageRows.append(row)
2362
+ }
2363
+ context.append(text('summary', 'Agent 将收到的续聊上下文'), note, list, messageRows)
2364
+ historyContextView = { section: context, note, description, list, first,
2365
+ baseText: result.messages[0]?.text, locked: lockedContext }
2366
+ dialogText.dataset.format = 'history'
2367
+ dialogText.replaceChildren(title, source, importTime, ...(target.textContent ? [target] : []), ...(directory ? [directory] : []),
2368
+ stats, ...(summary.textContent ? [summary] : []), ...(result.history ? [sourceArchive(result.history, {
2369
+ snapshotId, ticket: result.ticket, location: result.historyLocation, selectExcerpts: !lockedContext && !!first,
2370
+ })] : []), ...(skillChoices ? [skillChoices] : []), context)
2371
+ renderContextSelection()
2372
+ syncHistoryActions()
2373
+ if (first && historyExcerpts.size && !lockedContext) void reviewHistoryContext()
1976
2374
  } catch (error) {
1977
- if (active() && targetCwd) status(error.message, true, 'dialog-status')
2375
+ if (active() && updating) status(error.message, true, 'dialog-status')
1978
2376
  else if (active()) dialogText.textContent = error.message
1979
2377
  } finally {
1980
- if (active() && targetCwd) setDialogBusy(false)
2378
+ if (active() && updating) setDialogBusy(false)
1981
2379
  }
1982
2380
  }
1983
2381
 
1984
2382
  async function importSourceConversation() {
1985
- if (!historyTicket || dialogBusy) return
2383
+ if (historyImport.hidden || !historyTicket || dialogBusy || !historyContextReady) return
1986
2384
  if (!importedSessionId && dialogSkillIds.size) {
1987
2385
  await beginSkillActivation('history')
1988
2386
  return
@@ -2236,20 +2634,42 @@ async function continueWithTextOnly() {
2236
2634
 
2237
2635
  async function completeHandoff(purpose, confirmedSkillIds) {
2238
2636
  if (purpose === 'history') {
2239
- if (!historyTicket || dialogBusy) return
2637
+ if (historyImport.hidden || !historyTicket || dialogBusy || !historyContextReady) return
2240
2638
  setDialogBusy(true)
2241
2639
  status(importedSessionId ? '正在打开已迁入的会话…' : '正在迁入会话…', false, 'dialog-status')
2242
2640
  try {
2243
2641
  if (!importedSessionId) {
2244
2642
  historyImportStarted = true
2245
- const result = await api('import-conversation', { ticket: historyTicket })
2643
+ const result = await api('import-conversation', { ticket: historyTicket, duplicate: historyCopy, ...(historyContext ? {
2644
+ contextKey: historyContext.contextKey,
2645
+ excerpts: historyContext.items.map(({ snapshotId, seq, offset }) => ({ snapshotId, seq, offset })),
2646
+ } : {}) })
2647
+ if (result.reused) {
2648
+ historyImportStarted = false
2649
+ historyLastImport = result.lastImport
2650
+ syncHistoryActions()
2651
+ if (historyContext?.items.length) {
2652
+ status('这条来源已迁入。选中的摘录可随副本一起迁入。', false, 'dialog-status')
2653
+ return
2654
+ }
2655
+ await requestParent('open-imported', { sessionId: result.sessionId })
2656
+ dialog.close()
2657
+ status('已打开已有的 DSH 会话。')
2658
+ return
2659
+ }
2246
2660
  importedSessionId = result.sessionId
2247
2661
  }
2248
2662
  await requestParent('open-imported', { sessionId: importedSessionId })
2249
2663
  dialog.close()
2250
- status(`历史已迁入。打开会话即可继续。${activationSummary}`)
2664
+ status(`${historyCopy ? '已迁入并打开副本。' : '历史已迁入并打开。'}${activationSummary}`)
2665
+ if (historyProject && current?.id === historyProject.id) void loadRecentConversations(historyProject)
2251
2666
  } catch (error) {
2252
- if (importedSessionId) byId('history-import-label').textContent = '打开已迁入会话'
2667
+ if (importedSessionId) syncHistoryActions()
2668
+ else if (historySource && (error.recoveryTicket || error.status === 503)) {
2669
+ await previewSourceConversation(historySource, {
2670
+ refreshTicket: error.recoveryTicket ?? historySnapshotId, duplicate: historyCopy,
2671
+ })
2672
+ }
2253
2673
  status(error.message, true, 'dialog-status')
2254
2674
  } finally {
2255
2675
  setDialogBusy(false)
@@ -2461,6 +2881,117 @@ function showDownload({ filename, markdown }) {
2461
2881
  }
2462
2882
  }
2463
2883
 
2884
+ function reviewShare(load) {
2885
+ if (closeShareReview) return
2886
+ closeShareReview = openShareReview({
2887
+ load, theme: document.documentElement.dataset.theme,
2888
+ onClose() { closeShareReview = undefined },
2889
+ })
2890
+ }
2891
+
2892
+ function relaySelect(category, label) {
2893
+ const select = document.createElement('select')
2894
+ select.setAttribute('aria-label', label)
2895
+ for (const [key, name] of Object.entries(relayCategories)) select.add(new Option(name, key))
2896
+ select.value = category
2897
+ return select
2898
+ }
2899
+
2900
+ async function openProjectRelay() {
2901
+ const project = dialog.open && dialogMode === 'history' ? historyProject : current
2902
+ if (!project || dialogBusy) return
2903
+ const epoch = showDialog('relay', '项目接力单', project.name, '正在读取接力单…')
2904
+ const active = () => dialog.open && dialogEpoch === epoch
2905
+ relayPick.hidden = !nativeSessionImport
2906
+ const fields = { projectId: project.id }
2907
+ try {
2908
+ const { items } = await api('project-relay', fields)
2909
+ if (!active()) return
2910
+ dialogText.dataset.format = 'relay'
2911
+ const columns = new Map()
2912
+ for (const [category, label] of Object.entries(relayCategories)) {
2913
+ const group = text('section', '', 'relay-column')
2914
+ const list = text('div', '', 'relay-items')
2915
+ group.append(text('h3', label), list, text('p', '暂无条目', 'muted relay-empty'))
2916
+ columns.set(category, { group, list })
2917
+ }
2918
+ const dirty = new Set()
2919
+ const stack = text('div', '', 'relay-columns')
2920
+ stack.append(...[...columns.values()].map(({ group }) => group))
2921
+ dialogText.replaceChildren(stack)
2922
+ relayExport.hidden = !items.length
2923
+ const removeEmpty = () => { relayExport.hidden = !stack.querySelector('.relay-item') }
2924
+ function renderItem(item, before) {
2925
+ const card = text('article', '', 'relay-item')
2926
+ const source = item.source
2927
+ const heading = text('p', `${agentName(source.agent)} · ${source.title} · 第 ${source.turn} 轮`, 'relay-source')
2928
+ const note = text('p', item.text, 'relay-text')
2929
+ const jump = archiveButton('跳回原回合', () => {
2930
+ showDialog('history', '来源回合', project.name, '正在读取来源回合…')
2931
+ historyProject = project
2932
+ relayReturn.hidden = false
2933
+ void previewSourceConversation({ id: source.id, agent: source.agent, title: source.title }, { relayId: item.id })
2934
+ })
2935
+ const editor = text('details', '', 'relay-editor')
2936
+ const form = text('form', '', 'relay-form')
2937
+ const category = relaySelect(item.category, '接力分类')
2938
+ const body = document.createElement('textarea')
2939
+ body.setAttribute('aria-label', '接力正文')
2940
+ body.value = item.text
2941
+ body.maxLength = 8000
2942
+ body.required = true
2943
+ function changed() {
2944
+ if (body.value !== item.text || category.value !== item.category) dirty.add(item.id)
2945
+ else dirty.delete(item.id)
2946
+ }
2947
+ body.addEventListener('input', changed)
2948
+ category.addEventListener('change', changed)
2949
+ const save = text('button', '保存', 'primary')
2950
+ save.type = 'submit'
2951
+ async function mutate(action, values) {
2952
+ if (save.disabled) return
2953
+ save.disabled = remove.disabled = body.disabled = category.disabled = true
2954
+ try {
2955
+ const updated = await api(action, { ...fields, id: item.id, ...values })
2956
+ if (!active()) return
2957
+ dirty.delete(item.id)
2958
+ if (action === 'update-relay-item') renderItem(updated, card)
2959
+ card.remove()
2960
+ removeEmpty()
2961
+ status(action === 'update-relay-item' ? '已保存接力条目。' : '已移除接力条目。', false, 'dialog-status')
2962
+ } catch (error) {
2963
+ if (active()) status(error.message, true, 'dialog-status')
2964
+ } finally {
2965
+ save.disabled = remove.disabled = body.disabled = category.disabled = false
2966
+ }
2967
+ }
2968
+ const remove = archiveButton('移除条目', () => void mutate('remove-relay-item'))
2969
+ form.addEventListener('submit', event => {
2970
+ event.preventDefault()
2971
+ void mutate('update-relay-item', { text: body.value, category: category.value })
2972
+ })
2973
+ const actions = text('div', '', 'relay-actions')
2974
+ actions.append(category, save, remove)
2975
+ form.append(body, actions)
2976
+ editor.append(text('summary', '编辑正文和分类'), form)
2977
+ card.append(heading, note, jump, editor)
2978
+ if (before && item.category === before.dataset.category) before.before(card)
2979
+ else columns.get(item.category).list.append(card)
2980
+ card.dataset.category = item.category
2981
+ }
2982
+ items.forEach(item => renderItem(item))
2983
+ relayExport.onclick = () => {
2984
+ if (dirty.size) {
2985
+ status('请先保存已编辑的条目。', true, 'dialog-status')
2986
+ return
2987
+ }
2988
+ reviewShare(signal => api('export-relay', fields, { signal }))
2989
+ }
2990
+ } catch (error) {
2991
+ if (active()) dialogText.textContent = error.message
2992
+ }
2993
+ }
2994
+
2464
2995
  function selectedNativeSession() {
2465
2996
  return nativeSessions.find(session => session.id === sessionSelect.value)
2466
2997
  }
@@ -2526,17 +3057,23 @@ async function chooseNativeSession() {
2526
3057
  async function exportMarkdown(format = 'local') {
2527
3058
  if (dialogBusy || exportButton.hidden) return
2528
3059
  setDialogBusy(true)
2529
- status(`正在生成${format === 'share' ? '分享版' : '本机版'} Markdown…`, false, 'dialog-status')
3060
+ status('正在准备 Markdown…', false, 'dialog-status')
2530
3061
  const includeTrace = exportTraceOption.hidden ? false : exportTrace.checked
2531
3062
  try {
3063
+ let draft
2532
3064
  if (dialogMode === 'session') {
2533
3065
  const session = selectedNativeSession()
2534
3066
  if (!session) throw new Error('请选择要导出的 DSH 会话。')
2535
3067
  const result = await requestParent('session-export', { sessionId: session.id, path: session.path })
2536
- showDownload(await api('export-session', { sessionId: session.id, conversation: result.conversation, format, includeTrace }))
3068
+ draft = await api('export-session', { sessionId: session.id, conversation: result.conversation, format, includeTrace })
2537
3069
  } else if (ticket) {
2538
- showDownload(await api('export', { ticket, format, includeTrace }))
3070
+ draft = await api('export', { ticket, format, includeTrace })
2539
3071
  }
3072
+ if (!draft) return
3073
+ if (format === 'share') {
3074
+ status('', false, 'dialog-status')
3075
+ reviewShare(() => draft)
3076
+ } else showDownload(draft)
2540
3077
  } catch (error) {
2541
3078
  status(error.message, true, 'dialog-status')
2542
3079
  } finally {
@@ -2729,17 +3266,35 @@ byId('open-path').addEventListener('click', () => {
2729
3266
  })
2730
3267
  byId('preview').addEventListener('click', preview)
2731
3268
  byId('native-export').addEventListener('click', chooseNativeSession)
2732
- browseHistory.addEventListener('click', chooseSourceConversation)
3269
+ browseHistory.addEventListener('click', () => void chooseSourceConversation())
3270
+ byId('project-relay').addEventListener('click', openProjectRelay)
3271
+ relayReturn.addEventListener('click', openProjectRelay)
3272
+ relayPick.addEventListener('click', () => void chooseSourceConversation(true))
2733
3273
  byId('history-back-button').addEventListener('click', showHistoryResults)
2734
3274
  function searchHistory() {
3275
+ clearTimeout(historySearchTimer)
3276
+ historySearchRequest?.abort()
2735
3277
  historyChosenId = undefined
2736
3278
  historyLimit = 30
3279
+ const query = historySearch.value.trim()
3280
+ historyBodySearch = query && historySearchScope.value === 'body'
3281
+ ? { query, matches: [], loading: true } : undefined
2737
3282
  renderHistoryResults()
3283
+ if (historyBodySearch) {
3284
+ const search = historyBodySearch
3285
+ historySearchTimer = setTimeout(() => void loadBodySearch(search), 300)
3286
+ }
2738
3287
  }
2739
3288
  historySearch.addEventListener('input', searchHistory)
3289
+ historySearchScope.addEventListener('change', () => {
3290
+ historySearch.placeholder = historySearchScope.value === 'body' ? '搜本项目的对话正文' : '搜对话标题或 Agent'
3291
+ searchHistory()
3292
+ })
2740
3293
  wireClear(historySearch, searchHistory)
2741
3294
  byId('history-more').addEventListener('click', moreHistoryResults)
2742
3295
  historyImport.addEventListener('click', importSourceConversation)
3296
+ historyCopyButton.addEventListener('click', chooseHistoryCopy)
3297
+ historyOpenExisting.addEventListener('click', () => void openHistoryExisting())
2743
3298
  sessionSelect.addEventListener('change', clearDownload)
2744
3299
  sessionSelect.addEventListener('change', updateNativeSession)
2745
3300
  dialogClose.addEventListener('click', () => dialog.close())
@@ -2752,7 +3307,9 @@ dialog.addEventListener('click', event => {
2752
3307
  dialog.addEventListener('cancel', event => { if (dialogBusy) event.preventDefault() })
2753
3308
  dialog.addEventListener('close', () => {
2754
3309
  ++dialogEpoch
3310
+ closeShareReview?.()
2755
3311
  releaseHistoryPreview()
3312
+ resetHistorySearch()
2756
3313
  if (!dialog.open) sessionTraceRequest?.abort()
2757
3314
  if (activateDialog.open) activateDialog.close()
2758
3315
  clearDownload()