dsh-remote-plugin 0.8.0-rc.2 → 0.8.0-rc.4

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.
@@ -101,7 +101,7 @@ const state = {
101
101
  wb: { bound: false, path: '', title: '', expanded: false, projects: null, open: null, apiMissing: false },
102
102
  archivedIds: [],
103
103
  view: 'sessions',
104
- subagentExpandedSession: ''
104
+ subagentSessions: {}
105
105
  }
106
106
 
107
107
  // Increment on every identity transition, including A -> B -> A and token edits.
@@ -118,7 +118,7 @@ for (const key of ['server', 'token']) {
118
118
  state.sessions = []; state.byId.clear(); state.pendingProjections.clear()
119
119
  state.hostInfo = null
120
120
  if(typeof closeStream==='function'&&typeof streamMeta!=='undefined'){closeStream('mux');closeStream('host')}
121
- state.current = null; state.history = emptyDesktopHistory()
121
+ state.current = null; state.history = emptyDesktopHistory(); state.subagentSessions = {}; window.DshSubagents?.reset()
122
122
  state.models = { loaded: false, loading: false, groups: [], current: null, failures: [] }
123
123
  state.approvals = []; state.questions = []; state.questionModal = null
124
124
  state.queues = {}; state.queueSteering = {}; state.compactions = {}; state.compactionTerminals = {}; state.compactionSeqs = {}; state.compactionBootAt = Date.now(); state.pendingCommands = {}; state.sessionTurnTimes = {}
@@ -591,18 +591,21 @@ async function submitFeedback() {
591
591
  if (message.length > 2000) { toast(t('ds.feedbackTooLong'), 'err'); return }
592
592
  const btn = $('fb-submit')
593
593
  btn.disabled = true
594
+ const diagnostic=globalThis.DshDiagnostics?.start('feedback.submit')
594
595
  try {
595
596
  const res = await fetch(apiUrl('/feedback'), {
596
597
  method: 'POST',
597
598
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token },
598
599
  body: JSON.stringify({ type, message, contact, appVersion: '', includeDiagnostics, includeCrashLogs })
599
600
  })
601
+ diagnostic?.end({phase:res.ok?'complete':'failed',httpStatus:res.status})
600
602
  let json = {}
601
603
  try { json = await res.json() } catch {}
602
604
  if (res.ok && json.ok) { toast(t('ds.feedbackSubmitted'), 'ok'); closeFeedbackModal() }
603
605
  else if (res.status === 429) { toast(t('ds.feedbackRateLimited'), 'err') }
604
606
  else { toast(t('ds.feedbackSubmitFailed', { msg: json.error || res.status }), 'err') }
605
- } catch {
607
+ } catch(error) {
608
+ diagnostic?.fail(error)
606
609
  toast(t('ds.feedbackSubmitFailed', { msg: t('ds.feedbackNetworkError') }), 'err')
607
610
  } finally {
608
611
  btn.disabled = false
@@ -630,20 +633,19 @@ function apiUrl(path) { return (state.server || '') + path }
630
633
  let wsTicketPromise = null
631
634
  let wsTicketConnection = null
632
635
  async function getWsTicket() {
633
- const now = Date.now()
634
- if (state.wsTicket.token === state.token && state.wsTicket.server === state.server &&
635
- state.wsTicket.value && state.wsTicket.expiresAt > now + 15000) return state.wsTicket.value
636
+ // Only share an in-flight request; never reuse a previous handshake ticket.
636
637
  if (wsTicketPromise && wsTicketConnection?.valid()) return wsTicketPromise
637
638
  const connection = captureConnection()
638
639
  const token = state.token
639
640
  const server = state.server
640
641
  const job = (async () => {
641
- if (activeGatewayCapability('wsTicket') === false) throw new Error('ws ticket unsupported')
642
+ if (activeGatewayCapability('wsTicket') === false) throw Object.assign(new Error('ws ticket unsupported'), { unsupported: true })
642
643
  const res = await fetch(apiUrl('/api/ws-ticket'), {
643
644
  method: 'POST',
645
+ signal: AbortSignal.timeout(8000),
644
646
  headers: { authorization: 'Bearer ' + token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }
645
647
  })
646
- if (!res.ok) throw new Error('ws ticket HTTP ' + res.status)
648
+ if (!res.ok) throw Object.assign(new Error('ws ticket HTTP ' + res.status), { unsupported: [404, 405, 501].includes(res.status) })
647
649
  const data = await res.json()
648
650
  if (!connection.valid()) throw new Error('stale ws ticket')
649
651
  if (!data?.ticket || !Number(data.expiresAt)) throw new Error('invalid ws ticket')
@@ -655,6 +657,8 @@ async function getWsTicket() {
655
657
  try { return await job } finally { if (wsTicketPromise === job) { wsTicketPromise = null; wsTicketConnection = null } }
656
658
  }
657
659
  async function rpc(method, payload = {}, timeoutMs = 45000) {
660
+ const diagnostic=globalThis.DshDiagnostics?.start('rpc',{method,sessionId:payload.sessionId,server:state.server})
661
+ try {
658
662
  const opts = {
659
663
  method: 'POST',
660
664
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() },
@@ -667,12 +671,20 @@ async function rpc(method, payload = {}, timeoutMs = 45000) {
667
671
  const connection = operation ? captureConnection() : null
668
672
  const receipt = operation ? await window.DshOperations.execute({ method, payload, url: apiUrl, headers: opts.headers, valid: () => connection.valid() }) : null
669
673
  const res = receipt ? { status: 200, ok: true, json: async () => receipt } : await fetch(apiUrl('/api/' + method), opts)
674
+ diagnostic?.end({phase:'response',httpStatus:res.status})
670
675
  if (res.status === 401) throw new Error('AUTH')
671
676
  if (!res.ok) throw new Error('HTTP ' + res.status)
672
677
  const full = await res.json()
673
678
  if (!full?.result) throw new Error('bad response')
674
- if (!full.result.ok) throw new Error(full.result.error?.message || 'dsh error')
679
+ if (!full.result.ok) {
680
+ const err = full.result.error || {}
681
+ const error = new Error(err.code === 'session/migration-required' ? t('session.migrationRequired') : err.message || 'dsh error')
682
+ error.code = err.code
683
+ throw error
684
+ }
685
+ diagnostic?.end({phase:'complete'})
675
686
  return full.result.value
687
+ } catch(error) { diagnostic?.fail(error);throw error }
676
688
  }
677
689
  async function respond(rpcId, value) {
678
690
  const opts = {
@@ -723,8 +735,6 @@ async function refreshHostDescriptionDesktop({ notify = false } = {}) {
723
735
  const host = await rpc('host.describe', {}, 5000)
724
736
  if (!connection.valid()) return null
725
737
  state.hostInfo = host
726
- const health = activeGatewayHealth()
727
- if (health) health.upstreamReachable = true
728
738
  hostDescribeFailures = 0
729
739
  if (hostDescribeRetryTimer) clearTimeout(hostDescribeRetryTimer)
730
740
  hostDescribeRetryTimer = null
@@ -863,8 +873,9 @@ function activeGatewayHealth() {
863
873
 
864
874
  function dshReachable() {
865
875
  const health = activeGatewayHealth()
876
+ if (health && typeof health.upstreamOk === 'boolean') return health.upstreamOk
866
877
  if (health && typeof health.upstreamReachable === 'boolean') return health.upstreamReachable
867
- return !!state.hostInfo
878
+ return !!state.hostInfo && state.hostInfo.metadataOnly !== true
868
879
  }
869
880
  async function selectFastestServer({ silent = false, reconnect = true } = {}) {
870
881
  const request = selectFastestServer.request = (selectFastestServer.request || 0) + 1
@@ -933,6 +944,7 @@ function renderGroupSelect() {
933
944
  const menu = $('group-select-menu')
934
945
  if (!label || !menu) return
935
946
  label.textContent = state.activeGroup
947
+ $('group-select-btn')?.setAttribute('aria-label', t('ds.groupsCurrentLabel', { group: state.activeGroup }))
936
948
  menu.innerHTML = state.groups.map(g => `<button type="button" class="ds-group-option ${g === state.activeGroup ? 'current' : ''}" data-group-option="${esc(g)}">${esc(g)}${g === state.activeGroup ? ' ✓' : ''}</button>`).join('')
937
949
  menu.querySelectorAll('[data-group-option]').forEach(b => b.addEventListener('click', () => {
938
950
  closeGroupMenu()
@@ -1021,7 +1033,7 @@ function renderServers() {
1021
1033
  const activeManual = state.groupActive[g] || ''
1022
1034
  return `<div class="ds-srv-group" data-group="${esc(g)}">
1023
1035
  <div class="ds-srv-head">
1024
- <button class="ds-srv-name" data-group-name="${esc(g)}" title="${t('ds.groupsSwitchHint')}">${g === state.activeGroup ? '▾' : '▸'} ${esc(g)} <span class="ds-srv-count">${list.length}</span></button>
1036
+ <button class="ds-srv-name" data-group-name="${esc(g)}" title="${t('ds.groupsSwitchHint')}"><span class="ds-srv-label">${g === state.activeGroup ? '▾' : '▸'} ${esc(g)}</span><span class="ds-srv-count">${list.length}</span></button>
1025
1037
  <button class="ds-mini" data-speed-group="${esc(g)}" title="${t('ds.speedTest')}">⚡</button>
1026
1038
  <label class="ds-switch" title="${t('ds.groupsAutoSelect')}"><input type="checkbox" data-auto-group="${esc(g)}" ${auto ? 'checked' : ''}><span class="ds-slider"></span></label>
1027
1039
  ${g !== '默认' ? `<button class="ds-mini" data-del-group="${esc(g)}" title="${t('ds.groupsDelete')}">✕</button>` : ''}
@@ -1029,15 +1041,18 @@ function renderServers() {
1029
1041
  <div class="ds-srv-body ${g === state.activeGroup ? '' : 'hidden'}">
1030
1042
  ${list.map(s => {
1031
1043
  const ms = state.serverLatency[serverKey(s)]
1032
- let badge = `<span class="ds-server-badge">${t('ds.serversUntested')}</span>`
1033
1044
  const active = s.url === state.server && serverToken(s) === state.token
1034
- if (Number.isFinite(ms)) badge = `<span class="ds-server-badge ${active ? 'good' : ''}">${ms}ms${active ? t('ds.serversCurrent') : ''}</span>`
1045
+ // One status per row keeps long addresses readable.
1046
+ let badge = `<span class="ds-server-badge">${t('ds.serversUntested')}</span>`
1047
+ if (!s.token) badge = `<span class="ds-server-badge bad">${t('ds.serversTokenMissing')}</span>`
1048
+ else if (Number.isFinite(ms)) badge = `<span class="ds-server-badge ${active ? 'good' : ''}">${ms}ms${active ? t('ds.serversCurrent') : ''}</span>`
1035
1049
  else if (ms !== undefined) badge = `<span class="ds-server-badge bad">${t('ds.serversUnreachable')}</span>`
1050
+ else if (active) badge = `<span class="ds-server-badge good">${t('ds.serversCurrentOnly')}</span>`
1036
1051
  const activeInGroup = auto ? active : s.id === activeManual
1037
1052
  return `<div class="ds-server-row ${activeInGroup ? 'active' : ''}" data-use-server="${esc(s.id)}">
1038
- <span class="ds-server-main"><span class="ds-server-note">${esc(serverTitle(s))}</span>${s.note ? `<span class="ds-server-url">${esc(s.url)}</span>` : ''}<span class="ds-server-token-badge">${s.token ? t('ds.serversTokenSet') : t('ds.serversTokenMissing')}</span></span>${badge}
1039
- <button class="ds-mini" data-edit-server="${esc(s.id)}" title="${t('ds.serversEdit')}">✎</button>
1040
- <button class="ds-mini" data-del-server="${esc(s.id)}" title="${t('ds.serversDelete')}">✕</button>
1053
+ <span class="ds-server-main"><span class="ds-server-note" title="${esc(serverTitle(s))}">${esc(serverTitle(s))}</span>${s.note ? `<span class="ds-server-url">${esc(s.url)}</span>` : ''}</span>${badge}
1054
+ <button class="ds-mini ds-server-edit" data-edit-server="${esc(s.id)}" title="${t('ds.serversEdit')}" aria-label="${t('ds.serversEdit')}">✎</button>
1055
+ <button class="ds-mini ds-server-del" data-del-server="${esc(s.id)}" aria-label="${t('ds.serversDelete')}">✕</button>
1041
1056
  </div>`
1042
1057
  }).join('') || `<div class="ds-empty">${t('ds.groupsNoServer')}</div>`}
1043
1058
  </div>
@@ -1079,7 +1094,7 @@ function renderServers() {
1079
1094
  const curGroup = cur ? cur.group : state.activeGroup
1080
1095
  const curLabel = cur ? (cur.note || cur.url) : (state.server || t('ds.origin'))
1081
1096
  const curMs = cur ? state.serverLatency[serverKey(cur)] : undefined
1082
- $('server-desc').textContent = t('ds.serversCurrentDesc', { group: curGroup, url: curLabel, ms: Number.isFinite(curMs) ? curMs + 'ms' : '—' })
1097
+ $('server-desc').textContent = t('ds.serversCurrentDesc', { group: curGroup, url: curLabel }) + (Number.isFinite(curMs) ? ' · ' + curMs + 'ms' : '')
1083
1098
  updateConn()
1084
1099
  }
1085
1100
 
@@ -1256,12 +1271,25 @@ function openStreams() {
1256
1271
  function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1257
1272
  if (!state.token) return
1258
1273
  if (ticket === null) {
1259
- const token = state.token, connection=captureConnection()
1274
+ if (streams[kind] && [WebSocket.OPEN, WebSocket.CONNECTING].includes(streams[kind].readyState)) return
1275
+ const connection=captureConnection(), generation=streamMeta[kind].generation
1276
+ const valid=()=>connection.valid() && generation===streamMeta[kind].generation
1260
1277
  void getWsTicket().then((value) => {
1261
- if (connection.valid()) openStream(kind, handler, refreshOnOpen, isRestore, value)
1262
- }).catch(() => {
1278
+ if (valid()) openStream(kind, handler, refreshOnOpen, isRestore, value)
1279
+ }).catch((error) => {
1263
1280
  // 兼容旧网关/插件副本: ticket 接口不可用时临时回退旧 token 握手。
1264
- if (connection.valid()) openStream(kind, handler, refreshOnOpen, isRestore, '')
1281
+ if (!valid()) return
1282
+ if (error.unsupported) openStream(kind, handler, refreshOnOpen, isRestore, '')
1283
+ else {
1284
+ clearStreamRetry(kind)
1285
+ const meta = streamMeta[kind]
1286
+ meta.failures++
1287
+ aggregateStreamFailures()
1288
+ if (state.streamMode !== 'poll' && meta.failures >= 3) { enterPollMode(); return }
1289
+ const delay = Math.round(Math.min(1500 * 2 ** Math.min(meta.attempt++, 6), 60000) * (0.8 + Math.random() * 0.4))
1290
+ meta.retryTimer = setTimeout(() => { meta.retryTimer = null; if (valid() && navigator.onLine) openStream(kind, handler, refreshOnOpen, isRestore) }, delay)
1291
+ setReconnect(delay)
1292
+ }
1265
1293
  })
1266
1294
  return
1267
1295
  }
@@ -1289,6 +1317,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1289
1317
  ws._isRestore = !!isRestore
1290
1318
  ws.onopen = () => {
1291
1319
  if (!streamIsCurrent(kind, ws, generation)) return
1320
+ globalThis.DshDiagnostics?.record('stream.state',{channel:kind,status:'open',attempt:meta.failures})
1292
1321
  state.streamsOk[kind] = true
1293
1322
  markStreamInfo(kind, { status: 'open', lastOpenAt: Date.now(), lastCloseCode: 0, lastCloseReason: '' })
1294
1323
  meta.attempt = 0
@@ -1317,7 +1346,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1317
1346
  updateConn()
1318
1347
  try { handler(JSON.parse(msg.data)) } catch {}
1319
1348
  }
1320
- ws.onclose = () => {
1349
+ ws.onclose = (event) => {
1321
1350
  clearStreamTimers(ws)
1322
1351
  if (!streamIsCurrent(kind, ws, generation)) return
1323
1352
  streams[kind] = null
@@ -1325,9 +1354,10 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1325
1354
  markStreamInfo(kind, {
1326
1355
  status: 'closed',
1327
1356
  lastCloseAt: Date.now(),
1328
- lastCloseCode: Number(ws.code) || 0,
1329
- lastCloseReason: String(ws.reason || ''),
1357
+ lastCloseCode: Number(event.code) || 0,
1358
+ lastCloseReason: String(event.reason || '').slice(0, 200),
1330
1359
  })
1360
+ globalThis.DshDiagnostics?.record('stream.state',{channel:kind,status:'closed',closeCode:Number(event.code)||0,attempt:meta.failures+1})
1331
1361
  meta.failures++
1332
1362
  aggregateStreamFailures()
1333
1363
  updateConn()
@@ -1339,6 +1369,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1339
1369
  const attempt = meta.attempt++
1340
1370
  const baseDelay = Math.min(1500 * Math.pow(2, attempt), 60000)
1341
1371
  const delay = Math.round(baseDelay * (0.8 + Math.random() * 0.4))
1372
+ globalThis.DshDiagnostics?.record('stream.retry',{channel:kind,attempt:meta.attempt,delayMs:delay})
1342
1373
  setReconnect(delay)
1343
1374
  clearStreamRetry(kind)
1344
1375
  meta.retryTimer = setTimeout(() => {
@@ -1351,6 +1382,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1351
1382
 
1352
1383
  /* ---------------- 轮询降级模式 ---------------- */
1353
1384
  function enterPollMode() {
1385
+ globalThis.DshDiagnostics?.record('poll.state',{status:'poll'})
1354
1386
  if (state.streamMode === 'poll') return
1355
1387
  state.streamMode = 'poll'
1356
1388
  state.pollSeq = { mux: 0, host: 0 }
@@ -1481,6 +1513,7 @@ function onMuxFrame(full) {
1481
1513
  if (f.type === 'session/queue') { state.queues[f.sessionId] = f.items || []; renderQueue(); return }
1482
1514
  if (f.type === 'session/projection') { applyProjection(f.sessionId, f.key, f.value, f.seq); return }
1483
1515
  if (f.type === 'stream/error') toast(f.error?.message || 'stream error', 'err')
1516
+ if (f.type === 'session/stream-error' && f.sessionId === state.current) { const message=f.error?.code==='session/migration-required'?t('session.migrationRequired'):f.error?.message;setSessionRecovery('error',message);toast(message,'err') }
1484
1517
  }
1485
1518
  function onHostFrame(full) {
1486
1519
  const f = full.payload
@@ -1608,9 +1641,15 @@ function hydrateSessionProjections(sessionId, projections) {
1608
1641
  if (!s || !projections || typeof projections !== 'object') return
1609
1642
  const incomingSeq = Number(projections.asOfSeq) || 0
1610
1643
  const current = s.projections || { asOfSeq: 0, values: {} }
1644
+ if (projections.kind === 'cached' && current.kind === 'sequenced') return
1645
+ if (current.kind === 'cached' || projections.kind === 'cached') {
1646
+ s.projections = { ...projections, asOfSeq: incomingSeq, kind: projections.kind || 'sequenced', values: { ...(current.values || {}), ...(projections.values || {}) } }
1647
+ return
1648
+ }
1611
1649
  const currentSeq = Number(current.asOfSeq) || 0
1612
1650
  if (incomingSeq < currentSeq) return
1613
1651
  s.projections = {
1652
+ kind: projections.kind || current.kind || 'sequenced',
1614
1653
  asOfSeq: Math.max(currentSeq, incomingSeq),
1615
1654
  values: { ...(current.values || {}), ...(projections.values || {}) }
1616
1655
  }
@@ -1631,6 +1670,7 @@ function applyProjection(sessionId, key, value, seq) {
1631
1670
  state.pendingProjections.set(sessionId, pending)
1632
1671
  return
1633
1672
  }
1673
+ if (s.projections?.kind === 'cached') s.projections = { kind: 'sequenced', asOfSeq: 0, values: { ...(s.projections.values || {}) } }
1634
1674
  const currentSeq = Number(s.projections?.asOfSeq) || 0
1635
1675
  if (seq && seq < currentSeq) return
1636
1676
  s.projections = s.projections || { asOfSeq: 0, values: {} }
@@ -1709,7 +1749,8 @@ function sessionLabelOf(s) {
1709
1749
  return `${title} · ${String(s.sessionId).slice(-8)}`
1710
1750
  }
1711
1751
  function isTopLevelSession(session) {
1712
- return !!session && !session.parentSessionId && session.origin !== 'subagent'
1752
+ // Ordinary forks also carry parentSessionId; only explicit subagents leave the main list.
1753
+ return !!session && session.origin !== 'subagent'
1713
1754
  }
1714
1755
  // DSH marks sessions created via "new session" but never prompted as blank and hides
1715
1756
  // them in its own UI; keep the same semantics here so they do not occupy the list,
@@ -1788,6 +1829,12 @@ async function refreshSessions() {
1788
1829
  if (!v) { renderSessions(); renderOverviewDesktop(); return }
1789
1830
  state.sessions = v.items || []
1790
1831
  state.byId = new Map(state.sessions.map(s => [s.sessionId, s]))
1832
+ for (const [id, child] of Object.entries(state.subagentSessions || {})) {
1833
+ const listed = state.byId.get(id)
1834
+ const merged = listed ? { ...child, ...listed, parentSessionId: child.parentSessionId, subagentMode: child.subagentMode, origin: 'subagent' } : child
1835
+ state.byId.set(id, merged)
1836
+ state.subagentSessions[id] = merged
1837
+ }
1791
1838
  applyPendingProjections()
1792
1839
  try{LS.set(historyCacheScope()+':sessions',JSON.stringify(state.sessions.slice(0,80)))}catch{}
1793
1840
  renderSessions()
@@ -1913,6 +1960,7 @@ const emptySessionCleanup = new Set()
1913
1960
  async function archiveEmptySessionOnLeave(sessionId, leaving = false) {
1914
1961
  const base = state.server, connection=captureConnection()
1915
1962
  const protectedSession = () => !connection.valid() || state.server !== base || (!leaving && state.current !== sessionId)
1963
+ || !!state.byId.get(sessionId)?.parentSessionId || state.byId.get(sessionId)?.origin === 'subagent'
1916
1964
  || !state.byId.has(sessionId) || state.byId.get(sessionId)?.running
1917
1965
  || state.sessionActivity?.has(sessionId) || state.pendingPrompts?.has(sessionId)
1918
1966
  || (state.queues[sessionId] || []).length > 0
@@ -1933,6 +1981,7 @@ async function archiveEmptySessionOnLeave(sessionId, leaving = false) {
1933
1981
  }
1934
1982
 
1935
1983
  async function openSession(id) {
1984
+ globalThis.DshDiagnostics?.record('session.open',{phase:'start',sessionId:id,server:state.server})
1936
1985
  if (state.current && state.current !== id) void archiveEmptySessionOnLeave(state.current,true)
1937
1986
  state.current = id
1938
1987
  setSessionRecovery('loading')
@@ -1950,24 +1999,34 @@ async function openSession(id) {
1950
1999
  renderSessionPendingDesktop()
1951
2000
  updateComposerStatus()
1952
2001
  void refreshCompactionStatus(id)
1953
- await restoreCachedHistory()
2002
+ try { const restored=await restoreCachedHistory();globalThis.DshDiagnostics?.record('history.cache',{phase:restored?'hit':'miss',sessionId:id}) } catch(error) {
2003
+ globalThis.DshDiagnostics?.record('history.cache',{phase:'failed',sessionId:id,...globalThis.DshDiagnostics.errorFacts(error)})
2004
+ if(state.current!==id||state.history!==openingHistory||!openingConnection.valid())return
2005
+ // A broken local cache must not prevent fetching the authoritative history.
2006
+ Object.assign(openingHistory,emptyDesktopHistory())
2007
+ getConversationView().reset()
2008
+ }
1954
2009
  if(state.current!==id||state.history!==openingHistory||!openingConnection.valid())return
1955
2010
  await loadHistory()
1956
2011
  }
1957
2012
  async function closeSession() {
2013
+ globalThis.DshDiagnostics?.record('session.back',{phase:'start',sessionId:state.current,loading:state.history.loading,loaded:state.history.loaded,renderErrors:state.history.renderError?1:0})
1958
2014
  const sessionId = state.current
1959
- if (sessionId) await archiveEmptySessionOnLeave(sessionId)
1960
- if (state.current !== sessionId) return
2015
+ const parentId = state.byId.get(sessionId)?.parentSessionId
2016
+ if (parentId && parentId !== sessionId) return openSession(parentId)
2017
+ const cleanup=sessionId&&state.history.loaded&&!state.history.loading&&!state.history.renderError
1961
2018
  state.current = null
1962
2019
  setSessionRecovery('idle')
1963
2020
  state.history = emptyDesktopHistory()
2021
+ showView('view-sessions')
2022
+ globalThis.DshDiagnostics?.record('session.back',{phase:'navigate',sessionId})
1964
2023
  const cards = $('session-cards')
1965
2024
  if (cards) cards.innerHTML = ''
1966
2025
  renderQueue()
1967
2026
  renderSessionPendingDesktop()
1968
2027
  updateComposerStatus()
1969
2028
  updateSessionActions()
1970
- showView('view-sessions')
2029
+ if(cleanup)await archiveEmptySessionOnLeave(sessionId,true)
1971
2030
  }
1972
2031
 
1973
2032
  function restoreCachedSessionList() {
@@ -1980,13 +2039,15 @@ function historyCacheScope() { const hash=new SHA256();hash.update(new TextEncod
1980
2039
  function historySource(value) {
1981
2040
  state.history.source=value
1982
2041
  const el=$('history-source')
1983
- if(el)el.textContent=t(({cache:'ds.historyCached',syncing:'ds.historySyncing',synced:'ds.historySynced',saved:'ds.historySaved',offline:'ds.historyOffline',saveFailed:'ds.historyCacheFailed'})[value]||'ds.historySynced')
2042
+ if(el)el.textContent=t(({cache:'ds.historyCached',syncing:'ds.historySyncing',synced:'ds.historySynced',saved:'ds.historySaved',offline:'ds.historyOffline',saveFailed:'ds.historyCacheFailed',error:'ds.historyRenderFailed'})[value]||'ds.historySynced')
1984
2043
  }
1985
2044
  function getConversationView() {
1986
2045
  if(!conversationView)conversationView=new window.DshHistory.HistoryView($('history'),{
1987
2046
  html:entry=>eventHtml(entry),
2047
+ errorLabel:()=>t('ds.historyRenderFailed'),
1988
2048
  older:()=>loadHistory(false),olderLabel:()=>t('ds.historyEarlier'),loadingLabel:()=>t('ds.historyLoadingEarlier'),live:partialReasoningHtml,
1989
- changed:view=>{state.history.renderStart=view.start;state.history.renderEnd=view.end;const latest=$('btn-history-latest');if(latest){latest.classList.toggle('hidden',!view.reading&&view.end>=view.entries.length&&!state.history.tailEvicted);latest.textContent=t('ds.historyLatest')+(view.unread?' ('+view.unread+')':view.hasPending?' · '+(I18N.lang==='en'?'New content':'有新内容'):'');}},
2049
+ retry:()=>loadHistory(true),retryLabel:()=>t('ds.historyRetry'),unreadableLabel:()=>I18N.lang==='en'?'No displayable messages on this page. Load earlier records or retry. If DSH reports a migration failure, open the original session in DSH.':'本页历史没有可显示的消息,请加载更早记录或重试。如提示格式迁移失败,请先在 DSH 中打开原会话。',
2050
+ changed:view=>{state.history.renderStart=view.start;state.history.renderEnd=view.end;const latest=$('btn-history-latest');if(latest){latest.classList.toggle('hidden',view.atBottom&&view.unread===0&&!state.history.tailEvicted);latest.textContent=t('ds.historyLatest')+(view.unread?' ('+view.unread+')':view.hasPending?' · '+(I18N.lang==='en'?'New content':'有新内容'):'')}},
1990
2051
  scrolled:()=>{}
1991
2052
  })
1992
2053
  return conversationView
@@ -2026,51 +2087,74 @@ function trimVisible(direction='tail') {
2026
2087
  async function loadHistory(reset = true) {
2027
2088
  const connection=captureConnection(),id=state.current,history=state.history
2028
2089
  if(!id||history.loading||(!reset&&Date.now()<(history.retryAfter||0)))return
2090
+ const diagnostic=globalThis.DshDiagnostics?.start('history.load',{sessionId:id,server:state.server,reset,cached:!!history.cached,count:history.visible.length})
2029
2091
  const reasoningVersion=history.reasoningVersion||0,hadContent=history.visible.length>0
2030
2092
  history.loading=true
2031
2093
  if(reset){if(hadContent)historySource('syncing');else setSessionRecovery('loading')}
2032
2094
  const network=window.DshNetwork?.profile() || {historyPageSize:60,readTimeout:45000}
2033
2095
  const payload={sessionId:id,maxMessages:network.historyPageSize}
2096
+ const child=state.subagentSessions?.[id] || state.byId.get(id)
2097
+ if(child?.origin==='subagent' && child.parentSessionId) Object.assign(payload,{parentSessionId:child.parentSessionId,subagentMode:child.subagentMode || 'unknown'})
2034
2098
  if(!reset&&Number.isFinite(history.minSeq))payload.beforeSeq=history.minSeq
2035
2099
  getConversationView().more.disabled=true
2036
2100
  getConversationView().more.textContent=getConversationView().options.loadingLabel()
2037
2101
  let v
2038
- try{v=await rpc('session.history',payload,network.readTimeout)}catch(error){
2039
- if(!connection.valid()||state.current!==id||state.history!==history)return
2102
+ // Contain preparation and final DOM failures as well as network errors. Reset
2103
+ // the view before replacing its DOM so an identical retry cannot reuse stale nodes.
2104
+ const failLoad = (error,renderFailure=false) => {
2105
+ diagnostic?.fail(error)
2040
2106
  history.loading=false;history.retryAfter=Date.now()+1500
2041
2107
  if(error.message==='AUTH'){return}
2042
- if(hadContent){historySource('offline');setSessionRecovery('cached',error.message);renderHistory(false,'fixed');return}
2108
+ if(hadContent&&!renderFailure){try{renderHistory(false,'fixed');history.renderError=!!getConversationView().renderErrors;historySource(history.renderError?'error':'offline');setSessionRecovery(history.renderError?'error':'cached',error.message);return}catch{}}
2109
+ history.renderError=true;historySource('error')
2043
2110
  setSessionRecovery('error',error.message)
2111
+ getConversationView().reset?.()
2044
2112
  $('history').innerHTML='<div class="history-empty">'+esc(error.message)+'</div>'
2045
2113
  const retry=document.createElement('button');retry.type='button';retry.className='history-page-control';retry.textContent=t('ds.historyRetry');retry.addEventListener('click',()=>{void loadHistory(true)});$('history').append(retry)
2114
+ }
2115
+ try{v=await rpc('session.history',payload,network.readTimeout);globalThis.DshDiagnostics?.record('history.load',{phase:'response',traceId:diagnostic?.traceId,sessionId:id,rawCount:Array.isArray(v?.events)?v.events.length:0})}catch(error){
2116
+ if(!connection.valid()||state.current!==id||state.history!==history)return
2117
+ failLoad(error)
2046
2118
  return
2047
2119
  }
2048
2120
  if(!connection.valid()||state.current!==id||state.history!==history)return
2049
- const liveReasoning=(history.reasoningVersion||0)!==reasoningVersion?new Map(history.partialReasoning):null
2050
- hydrateSessionProjections(id,v.projections);history.loaded=true
2051
- const incoming=v.events||[],prepared=[]
2052
- for (const entry of v.events || []) {
2053
- const ev=entry?.event
2054
- applyReasoningStreamEvent(ev)
2055
- if(ev?.type==='turn/start'||ev?.type==='turn/end')noteSessionTurnTime(id,ev)
2056
- if(ev?.seq==null||!shouldShowEvent(ev.type,ev))continue
2057
- prepared.push({seq:ev.seq,event:ev,view:entry.view})
2058
- }
2059
- const rawSeqs=incoming.map(entry=>entry?.event?.seq).filter(Number.isFinite),floor=rawSeqs.length?Math.min(...rawSeqs):Infinity
2060
- if(reset){const retainedOlder=!!v.hasMore&&history.visible.some(entry=>entry.seq<floor);const ceiling=rawSeqs.length?Math.max(...rawSeqs)+1:Infinity;history.visible=rawSeqs.length?window.DshHistory.reconcile(history.visible,prepared,floor,!!v.hasMore,ceiling):[];history.minSeq=retainedOlder?Math.min(history.minSeq,floor):floor;history.tailEvicted=false}
2061
- else{history.visible=window.DshHistory.reconcile(history.visible,prepared,floor,true,payload.beforeSeq);history.minSeq=Math.min(history.minSeq,floor)}
2062
- history.seqs=new Set(history.visible.map(entry=>entry.seq));history.headEvicted=false;trimVisible(reset?'tail':'older')
2063
- if(liveReasoning)history.partialReasoning=liveReasoning;else applyReasoningBaseline(v.partialReasoning)
2064
- history.hasMore=(!!v.hasMore||(reset&&history.headEvicted)) && rawSeqs.length>0 && (reset || floor<payload.beforeSeq)
2065
- history.loading=false;history.cached=false;historySource('synced');setSessionRecovery('ready')
2066
- updateSessionActions();renderSessionCards()
2067
- renderHistory(!hadContent,reset?'fixed':'keep')
2068
-
2069
- scheduleHistoryCacheSave()
2121
+ let liveReasoning, rawSeqs, floor
2122
+ try {
2123
+ liveReasoning=(history.reasoningVersion||0)!==reasoningVersion?new Map(history.partialReasoning):null
2124
+ hydrateSessionProjections(id,v.projections);history.loaded=true
2125
+ const incoming=v.events||[],prepared=[]
2126
+ for (const entry of incoming) {
2127
+ const ev=entry?.event
2128
+ applyReasoningStreamEvent(ev)
2129
+ if(ev?.type==='turn/start'||ev?.type==='turn/end')noteSessionTurnTime(id,ev)
2130
+ if(ev?.seq==null||!shouldShowEvent(ev.type,ev))continue
2131
+ prepared.push({seq:ev.seq,event:ev,view:entry.view})
2132
+ }
2133
+ rawSeqs=incoming.map(entry=>entry?.event?.seq).filter(Number.isFinite);floor=rawSeqs.length?Math.min(...rawSeqs):Infinity
2134
+ if(reset){const retainedOlder=!!v.hasMore&&history.visible.some(entry=>entry.seq<floor);const ceiling=rawSeqs.length?Math.max(...rawSeqs)+1:Infinity;history.visible=rawSeqs.length?window.DshHistory.reconcile(history.visible,prepared,floor,!!v.hasMore,ceiling):[];history.minSeq=retainedOlder?Math.min(history.minSeq,floor):floor;history.tailEvicted=false}
2135
+ else{history.visible=window.DshHistory.reconcile(history.visible,prepared,floor,true,payload.beforeSeq);history.minSeq=Math.min(history.minSeq,floor)}
2136
+ history.seqs=new Set(history.visible.map(entry=>entry.seq));history.headEvicted=false;trimVisible(reset?'tail':'older')
2137
+ if(liveReasoning)history.partialReasoning=liveReasoning;else applyReasoningBaseline(v.partialReasoning)
2138
+ history.hasMore=(!!v.hasMore||(reset&&history.headEvicted)) && rawSeqs.length>0 && (reset || floor<payload.beforeSeq)
2139
+ } catch (error) {
2140
+ failLoad(error)
2141
+ return
2142
+ }
2143
+ try {
2144
+ history.loading=false;history.cached=false
2145
+ updateSessionActions();renderSessionCards()
2146
+ globalThis.DshDiagnostics?.record('history.render',{phase:'start',traceId:diagnostic?.traceId,sessionId:id,count:history.visible.length})
2147
+ renderHistory(!hadContent,reset?'fixed':'keep')
2148
+ history.renderError=!!getConversationView().renderErrors
2149
+ historySource(history.renderError?'error':'synced');setSessionRecovery(history.renderError?'error':'ready')
2150
+ diagnostic?.end({phase:history.renderError?'failed':'rendered',count:history.visible.length,renderedCount:getConversationView().end-getConversationView().start,renderErrors:getConversationView().renderErrors||0})
2151
+ if(!history.renderError)scheduleHistoryCacheSave()
2152
+ } catch(error) { failLoad(error,true) }
2070
2153
  }
2071
2154
 
2072
2155
 
2073
2156
  const INTERESTING_EVENTS = new Set([
2157
+ 'turn/start', 'turn/end',
2074
2158
  'user/message', 'assistant/message', 'tool/call', 'tool/result',
2075
2159
  'agent/status', 'checkpoint/created', 'compaction/complete', 'compaction/summary',
2076
2160
  'goal/created', 'goal/updated', 'goal/completed', 'goal/cleared',
@@ -2136,7 +2220,9 @@ function applyReasoningStreamEvent(event) {
2136
2220
  return changed
2137
2221
  }
2138
2222
  let reasoningRenderTimer = null
2223
+ function weakStreamTrim() { return !!window.DshNetwork?.streamTrimmed?.() }
2139
2224
  function scheduleReasoningRender() {
2225
+ if (weakStreamTrim()) return
2140
2226
  if (reasoningRenderTimer) return
2141
2227
  reasoningRenderTimer = setTimeout(() => {
2142
2228
  reasoningRenderTimer = null
@@ -2144,22 +2230,32 @@ function scheduleReasoningRender() {
2144
2230
  }, 80)
2145
2231
  }
2146
2232
  function partialReasoningHtml() {
2233
+ if (weakStreamTrim()) return ''
2147
2234
  return [...state.history.partialReasoning.values()]
2148
2235
  .filter(item => item.text)
2149
2236
  .sort((a, b) => (a.turn ?? 0) - (b.turn ?? 0) || (a.step ?? 0) - (b.step ?? 0) || (a.index ?? 0) - (b.index ?? 0))
2150
- .map(item => `<div class="ds-msg assistant ds-reasoning-live"><div class="role">${esc(t('ds.role.dsh'))}</div><details open><summary>${esc(t('block.thinkingLive'))}</summary><div>${esc(item.text)}</div></details></div>`)
2237
+ .map(item => window.DshActivity ? window.DshActivity.reasoning({text:item.text,live:true,key:window.DshActivity.reasoningKey(item,item.index,'live-reasoning')}) : `<div class="ds-msg assistant ds-reasoning-live"><div class="role">${esc(t('ds.role.dsh'))}</div><details open><summary>${esc(t('block.thinkingLive'))}</summary><div>${esc(item.text)}</div></details></div>`)
2151
2238
  .join('')
2152
2239
  }
2153
2240
  function safeJson(v) { try { return JSON.stringify(v, null, 2) } catch { return String(v) } }
2154
- function blockHtml(b) {
2241
+ function blockHtml(b,index=0,context={}) {
2155
2242
  if (!b) return ''
2156
- if (b.type === 'text') return `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '', { fileLinks: true }) : esc(b.text ?? '')}</div>`
2243
+ if ((b.type === 'tool-call' || b.type === 'tool-result') && context.suppressBlockTools) return ''
2244
+ if (typeof window !== 'undefined' && window.DshActivity) {
2245
+ const key='block:'+context.seq+':'+index
2246
+ if (b.type==='thinking'||b.type==='reasoning') return window.DshActivity.reasoning({text:b.text??b.content??'',key:window.DshActivity.reasoningKey(context,index,key)})
2247
+ if (b.type==='tool-call'||b.type==='tool-result') return window.DshActivity.tool({key,name:b.name||b.toolName,...(b.type==='tool-call'?{args:b.arguments??b.args??b.input}:{result:b.result??b.output??b.content??b,error:!!(b.error||b.ok===false||b.isError)})})
2248
+ }
2249
+ if (b.type === 'text') return `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '', { fileLinks: true, imageLabel: t('block.image') }) : esc(b.text ?? '')}</div>`
2157
2250
  if (b.type === 'file' && typeof window !== 'undefined' && window.DshChatFiles) return window.DshChatFiles.render(b)
2158
2251
  if (b.type === 'file') return `<div class="ds-tool">📎 ${esc(b.attachment?.name || b.name || 'file')} <small>${esc(b.attachment?.bytes ?? b.bytes ?? '')} bytes</small></div>`
2159
2252
  if (b.type === 'thinking' || b.type === 'reasoning') return `<details><summary>${esc(t('block.thinking'))}</summary><div style="opacity:.82">${esc(b.text ?? b.content ?? '')}</div></details>`
2160
2253
  if (b.type === 'tool-call') return `<div>🔧 ${esc(b.name || '')}</div>`
2161
2254
  if (b.type === 'tool-result') return `<div>📦</div>`
2162
- if (b.type === 'image') return `<div>🖼</div>`
2255
+ if (b.type === 'image') {
2256
+ const alt = b.name || b.filename || t('block.image')
2257
+ return `<button type="button" class="chat-image" data-chat-image aria-label="${esc(t('block.image'))}"><img alt="${esc(alt)}" src="data:${esc(b.mediaType || 'image/png')};base64,${esc(b.data || '')}" draggable="false"></button>`
2258
+ }
2163
2259
  return ''
2164
2260
  }
2165
2261
  function systemReminderText(blocks) {
@@ -2169,11 +2265,27 @@ function systemReminderText(blocks) {
2169
2265
  .map(b => String(b.text ?? ''))
2170
2266
  .join('\n')
2171
2267
  }
2268
+ function activityGroupHtml(group) {
2269
+ const items = group.items || []
2270
+ if (!items.length) return ''
2271
+ const tools = items.filter(item => item.kind === 'tool').map(item => item.entry)
2272
+ const running = !!group.running
2273
+ const failed = tools.some(entry => entry.view?.toolActivity?.error || entry.event?.data?.error)
2274
+ const body = items.map(item => item.kind === 'reasoning'
2275
+ ? window.DshActivity.reasoning({ text: item.text, key: item.key })
2276
+ : eventHtml(item.entry)).join('')
2277
+ return `<details class="chat-activity-group${failed ? ' is-error' : ''}${running ? ' is-running' : ''}" data-activity-key="activity-group:${items[0]?.seq ?? ''}"><summary><span class="activity-group-title">${esc(t('ds.activity.group', { n: items.length }))}</span>${running ? `<span class="activity-group-live"><i aria-hidden="true"></i>${esc(t('ds.activity.groupRunning'))}</span>` : ''}<span class="activity-chevron" aria-hidden="true"></span></summary><div class="activity-group-body">${body}</div></details>`
2278
+ }
2279
+
2172
2280
  function eventHtml(entry) {
2173
2281
  const ev = entry.event || {}
2174
2282
  const data = ev.data || {}
2175
2283
  const type = ev.type || 'event'
2284
+ if (entry.view?.turnResult) return window.DshTurnResults.html(entry.view.turnResult)
2285
+ if (type === 'turn/start' || type === 'turn/end') return ''
2286
+ if (entry.view?.activityGroup) return activityGroupHtml(entry.view.activityGroup)
2176
2287
  if (!shouldShowEvent(type, ev)) return ''
2288
+ if (window.DshActivity && (type==='tool/call'||type==='tool/result')) return window.DshActivity.toolEvent(entry)
2177
2289
  if (type === 'user/message' || type === 'assistant/message') {
2178
2290
  const msg = data.message || {}
2179
2291
  const role = data.role || msg.role || (type.startsWith('user') ? 'user' : 'assistant')
@@ -2184,8 +2296,9 @@ function eventHtml(entry) {
2184
2296
  return `<details class="event ds-tool ds-event-detail"><summary>${esc(t('ds.eventSystemReminder'))}</summary><pre>${esc(shown)}</pre></details>`
2185
2297
  }
2186
2298
  if (type === 'user/message' && !isHumanUserMessage(ev)) return ''
2187
- const text = blocks.map(blockHtml).join('')
2188
- return `<div class="ds-msg ${esc(role)}"><div class="role">${esc(role === 'user' ? t('ds.role.me') : t('ds.role.dsh'))}</div>${text || '<span style="opacity:.6">…</span>'}</div>`
2299
+ const text = blocks.map((block,index)=>blockHtml(block,index,{...data,seq:entry.seq,suppressBlockTools:state.history.suppressBlockTools})).join('')
2300
+ if (!text) return ''
2301
+ return `<div class="ds-msg ${esc(role)}"><div class="role">${esc(role === 'user' ? t('ds.role.me') : t('ds.role.dsh'))}</div>${text}</div>`
2189
2302
  }
2190
2303
  if (type === 'tool/call') {
2191
2304
  const name = data.name || data.toolName || t('ds.toolDefault')
@@ -2201,17 +2314,77 @@ function eventHtml(entry) {
2201
2314
  if (type === 'question/asked') return `<div class="ds-tool">❓ ${esc(data.question || '')}</div>`
2202
2315
  return `<div class="ds-tool">${esc(type)}</div>`
2203
2316
  }
2317
+ function canForkTurnResult() {
2318
+ const session = state.byId.get(state.current)
2319
+ return !!session && session.origin !== 'subagent' && session.formatStatus !== 'migration-required' && activeGatewayCapability('operations') === true
2320
+ }
2321
+ function bindTurnResultActions() {
2322
+ window.DshTurnResults.bind($('history'), {
2323
+ capture: () => {
2324
+ const connection = captureConnection(), sessionId = state.current, history = state.history
2325
+ return { sessionId, entries: history.visible, key: JSON.stringify([connection.server, connection.token]), canFork: canForkTurnResult(),
2326
+ valid: () => connection.valid() && state.current === sessionId && state.history === history }
2327
+ },
2328
+ copy: copyText,
2329
+ fork: payload => rpc('session.fork', payload),
2330
+ open: async (id, context) => {
2331
+ const parent = state.byId.get(context.sessionId)
2332
+ try { await refreshSessions() } catch {} // A successful fork remains usable if the roster refresh fails.
2333
+ if (!context.valid()) return
2334
+ if (!state.byId.has(id)) {
2335
+ const branch = { ...parent, sessionId: id, parentSessionId: context.sessionId, origin: 'fork', running: false, blank: false }
2336
+ state.byId.set(id, branch)
2337
+ state.sessions.unshift(branch)
2338
+ renderSessions()
2339
+ }
2340
+ await openSession(id)
2341
+ }
2342
+ })
2343
+ }
2344
+
2204
2345
  function renderHistory(reset=false, mode='auto') {
2205
- getConversationView().set(state.history.visible,{reset,follow:mode==='bottom',live:partialReasoningHtml(),hasMore:state.history.hasMore,loading:state.history.loading,emptyLabel:t('ds.historyEmpty')})
2346
+ let prepared=window.DshActivity?.prepare(state.history.visible)||state.history.visible
2347
+ if(weakStreamTrim())prepared=prepared.filter(entry=>entry.event?.type!=='tool/call'||entry.view?.toolActivity)
2348
+ state.history.suppressBlockTools = state.history.visible.some(entry => entry.event?.type === 'tool/call')
2349
+ if(window.DshActivity?.group)prepared=window.DshActivity.group(prepared)
2350
+ const sessionRunning = !!state.byId.get(state.current)?.running
2351
+ const groups = prepared.filter(entry => entry.view?.activityGroup)
2352
+ const activeGroup = groups.at(-1)
2353
+ if (activeGroup) activeGroup.view.activityGroup.running = sessionRunning
2354
+ if (window.DshTurnResults) {
2355
+ prepared = window.DshTurnResults.decorate(prepared, state.history.visible, { sessionId: state.current, canFork: canForkTurnResult() })
2356
+ bindTurnResultActions()
2357
+ }
2358
+ getConversationView().set(prepared,{reset,follow:mode==='bottom',live:partialReasoningHtml(),hasMore:state.history.hasMore,loading:state.history.loading,emptyLabel:t('ds.historyEmpty')})
2359
+ window.DshImagePreview?.hydrate?.($('history'))
2206
2360
  }
2361
+ window.applyStreamPreference=()=>{if(state.current)renderHistory(false,'auto')}
2207
2362
 
2208
2363
  /* ---------------- 会话信息卡(goal / todo / 子代理) ---------------- */
2209
2364
  let sessionSubagentsJob = null
2365
+ function rememberSubagent(entry, parentId) {
2366
+ const childId = entry.id
2367
+ const child = state.byId.get(childId) || { sessionId: childId, cwd: state.byId.get(parentId)?.cwd || '' }
2368
+ Object.assign(child, { parentSessionId: parentId, origin: 'subagent', subagentMode: entry.mode || child.subagentMode || 'unknown' })
2369
+ if (entry.label && !child.projections?.values?.title) {
2370
+ child.projections ||= { values: {} }
2371
+ child.projections.values ||= {}
2372
+ child.projections.values.title = entry.label
2373
+ }
2374
+ state.byId.set(childId, child)
2375
+ state.subagentSessions ||= {}
2376
+ state.subagentSessions[childId] = child
2377
+ }
2378
+ async function openSubagentSession(childId, parentId, entry = {}, rootId = parentId) {
2379
+ if (!childId || childId === parentId || state.current !== rootId) return
2380
+ rememberSubagent({ ...entry, id: childId }, parentId)
2381
+ await openSession(childId)
2382
+ }
2210
2383
  async function loadSessionSubagents(sessionId) {
2211
2384
  if (sessionSubagentsJob?.sessionId === sessionId && sessionSubagentsJob.connection.valid()) return sessionSubagentsJob.promise
2212
2385
  const connection = captureConnection(), job = { sessionId, connection }
2213
2386
  job.promise = (async () => {
2214
- const value = await safeRpc('subagent.list', { parentSessionId: sessionId }, '')
2387
+ const value = await rpc('subagent.list', { parentSessionId: sessionId })
2215
2388
  return connection.valid() ? value : null
2216
2389
  })()
2217
2390
  sessionSubagentsJob = job
@@ -2268,30 +2441,15 @@ async function renderSessionCards() {
2268
2441
  requestAnimationFrame(() => box.querySelector(`[data-goal-collapse="${collapse ? '0' : '1'}"]`)?.focus())
2269
2442
  }))
2270
2443
 
2271
- const sub = await loadSessionSubagents(sessionId)
2272
2444
  if (!connection.valid() || renderGeneration !== sessionCardsRenderGeneration || state.current !== sessionId) return
2273
- if (sub?.entries?.length) {
2274
- const expanded = state.subagentExpandedSession === sessionId
2275
- const toggleLabel = expanded ? t('subagent.collapse') : t('subagent.expand')
2276
- const rows = sub.entries.map(e => {
2277
- if (e.kind === 'diagnostic') return `<div class="ds-card-row"><span class="ds-card-k">${t('subagent.diagnostic')}</span><span class="ds-card-v">${esc(e.reason)}</span></div>`
2278
- const label = e.label || short(e.id)
2279
- const running = e.activity === 'running'
2280
- return `<div class="ds-card-row"><span class="ds-card-k">${running ? '▶ ' : ''}${esc(label)}</span><span class="ds-card-v">${esc(e.mode)} ${running ? t('subagent.running') : ''}${e.mode === 'continuable' && running ? ` <button class="ds-mini-btn" data-sub-interrupt="${esc(e.id)}">${t('subagent.interrupt')}</button>` : ''}</span></div>`
2281
- }).join('')
2282
- const subagentClosedIcon = 'M7 10l5 5 5-5'
2283
- const subagentOpenIcon = 'M7 14l5-5 5 5'
2284
- const subagentIcon = expanded ? subagentOpenIcon : subagentClosedIcon
2285
- box.insertAdjacentHTML('beforeend', `<div class="ds-card ds-subagent-card"><button type="button" class="ds-subagent-toggle" data-subagent-toggle aria-expanded="${expanded}" aria-label="${esc(toggleLabel)}" title="${esc(toggleLabel)}"><span class="ds-card-title">${esc(t('subagent.count', { n: sub.entries.length }))}</span><span class="ds-subagent-toggle-icon" aria-hidden="true"><morph-icon data-morph-state="${expanded ? 'open' : 'closed'}" data-morph-closed="${subagentClosedIcon}" data-morph-open="${subagentOpenIcon}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${subagentIcon}"/></svg></morph-icon></span></button><div class="ds-subagent-list${expanded ? '' : ' hidden'}">${rows}</div></div>`)
2286
- box.querySelector('[data-subagent-toggle]')?.addEventListener('click', () => {
2287
- const icon = box.querySelector('[data-subagent-toggle] morph-icon')
2288
- if (icon) icon.setAttribute('data-morph-state', expanded ? 'closed' : 'open')
2289
- state.subagentExpandedSession = expanded ? '' : sessionId
2290
- setTimeout(() => renderSessionCards(), 240)
2291
- })
2292
- box.querySelectorAll('[data-sub-interrupt]').forEach(btn =>
2293
- btn.addEventListener('click', () => interruptSubagent(btn.dataset.subInterrupt)))
2294
- }
2445
+ window.DshSubagents?.configure($('btn-subagents'), {
2446
+ sessionId, title: titleOf(s), activity: s.running === true ? 'running' : s.running === false ? 'inactive' : 'unknown', parentId: s.origin === 'subagent' ? s.parentSessionId : null,
2447
+ valid: () => connection.valid() && state.current === sessionId,
2448
+ read: loadSessionSubagents, remember: rememberSubagent,
2449
+ onShow: () => conversationView?.pause(), onClose: () => conversationView?.resume(),
2450
+ open: (entry, parentId) => openSubagentSession(entry.id, parentId, entry, sessionId),
2451
+ interrupt: interruptSubagent,
2452
+ })
2295
2453
  }
2296
2454
 
2297
2455
  function setGoalPhaseLocal(phase) {
@@ -2336,10 +2494,11 @@ async function goalAction(kind) {
2336
2494
  renderSessionCards()
2337
2495
  }
2338
2496
 
2339
- async function interruptSubagent(childId) {
2497
+ async function interruptSubagent(childId, parentId = state.current) {
2498
+ const connection = captureConnection(), rootId = state.current
2340
2499
  if (!confirm(t('subagent.confirmInterrupt'))) return
2341
- const result = await safeRpc('subagent.interrupt', { parentSessionId: state.current, childSessionId: childId, mode: 'continuable' }, t('subagent.interruptFailed'))
2342
- if (result == null) return
2500
+ const result = await safeRpc('subagent.interrupt', { parentSessionId: parentId, childSessionId: childId, mode: 'continuable' }, t('subagent.interruptFailed'))
2501
+ if (result == null || !connection.valid() || state.current !== rootId) return
2343
2502
  toast(t('subagent.interruptSubmitted'), 'ok')
2344
2503
  setTimeout(renderSessionCards, 600)
2345
2504
  }
@@ -2435,6 +2594,7 @@ async function runSlashCommand(text) {
2435
2594
  }
2436
2595
 
2437
2596
  async function sendMessage(requestedMode = 'queue') {
2597
+ if (state.byId.get(state.current)?.origin === 'subagent') { toast('子代理记录为只读 / Subagent records are read only'); return false }
2438
2598
  const input = $('composer')
2439
2599
  const originalText = input.value, text = originalText.trim()
2440
2600
  if (!text || !state.current) return
@@ -2736,6 +2896,18 @@ function fsApiUrl(sub, params = {}) {
2736
2896
  function fsHeaders() {
2737
2897
  return { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }
2738
2898
  }
2899
+
2900
+ /** Local image paths inside Markdown: resolve relative to the open session workspace. */
2901
+ function chatImageRequest(pathValue) {
2902
+ const value = String(pathValue || '').trim()
2903
+ if (!value) return null
2904
+ let target = value
2905
+ if (!/^(?:[A-Za-z]:[\\/]|\\\\|\/|~[\\/])/.test(value)) {
2906
+ const root = state.byId.get(state.current)?.cwd || ''
2907
+ if (root) target = root.replace(/[\\/]+$/, '') + (root.includes('\\') ? '\\' : '/') + value.replace(/^\.?[\\/]+/, '')
2908
+ }
2909
+ return { url: fsApiUrl('/file', { path: target }), headers: fsHeaders() }
2910
+ }
2739
2911
  function fsParent(p) {
2740
2912
  const meta = fsPathMeta(p)
2741
2913
  if (!meta.value) return null
@@ -3434,15 +3606,15 @@ async function probeOverviewLinks(signal) {
3434
3606
  let timer
3435
3607
  const controller=new AbortController(),cancel=()=>controller.abort()
3436
3608
  signal.addEventListener('abort',cancel,{once:true});if(signal.aborted)controller.abort()
3437
- timer=setTimeout(cancel,4000)
3438
- const healthRequest=fetch(base+'/health?probe=live&t='+Date.now(),{signal:controller.signal,cache:'no-store'}).then(async response=>{
3609
+ timer=setTimeout(cancel,6500)
3610
+ const healthRequest=fetch(base+'/health?probe=fresh&t='+Date.now(),{signal:controller.signal,cache:'no-store'}).then(async response=>{
3439
3611
  if(!response.ok)throw Error('health')
3440
3612
  const health=await response.json();if(health?.ok!==true)throw Error('health')
3441
3613
  return health
3442
3614
  }).catch(()=>null).finally(()=>{clearTimeout(timer);signal.removeEventListener('abort',cancel)})
3443
3615
  const [health,host]=await Promise.all([healthRequest,refreshHostDescriptionDesktop()])
3444
3616
  if(!connection.valid()||signal.aborted)throw Error('stale check')
3445
- if(health){if(host)health.upstreamReachable=true;state.gatewayHealth[base]=health}
3617
+ if(health){state.gatewayHealth[base]=health}
3446
3618
  else delete state.gatewayHealth[base]
3447
3619
  return {gateway:!!health}
3448
3620
  }
@@ -3565,10 +3737,24 @@ function setMobileSidebar(open) {
3565
3737
  function openDesktopPlugins(route = 'manage') {
3566
3738
  const connection=captureConnection()
3567
3739
  if(!connection.token){$('desktop-plugin-page').textContent=t('ds.toastAuth');return}
3568
- window.DshExtensions.mount({connection,getSession:()=>state.byId.get(state.current),getTitle:()=>titleOf(state.byId.get(state.current)),openContext:()=>void openInsights('context',true),scrollTop:()=>{$('view-plugins').scrollTop=0},url:path=>connection.server+path,headers:{authorization:'Bearer '+connection.token,'x-dsh-remote-client':'web',...clientIdHeaders()},valid:connection.valid},$('desktop-plugin-page'),route)
3740
+ window.DshExtensions.mount({connection,getWorkspaces: () => state.workspaces || [],
3741
+ getWorkspaceId: () => (state.workspaces || []).find(w => (w.sessionIds || []).includes(state.current))?.workspaceId || '',
3742
+ openTeamCaptain: async id => { if (!connection.valid()) return; await openSession(id) },
3743
+ openTeamMember: async (id, parentId) => {
3744
+ const selected = state.current
3745
+ const catalog = await loadSessionSubagents(parentId)
3746
+ if (!connection.valid() || state.view !== 'view-plugins' || state.current !== selected) return
3747
+ const entry = catalog?.entries?.find(row => row.id === id)
3748
+ if (!entry || entry.kind === 'diagnostic') throw Error('unavailable')
3749
+ rememberSubagent(entry, parentId)
3750
+ await openSession(id)
3751
+ },
3752
+ back:()=>showView('view-settings'),getSession:()=>state.byId.get(state.current),getTitle:()=>titleOf(state.byId.get(state.current)),openContext:()=>void openInsights('context',true),scrollTop:()=>{$('view-plugins').scrollTop=0},url:path=>connection.server+path,headers:{authorization:'Bearer '+connection.token,'x-dsh-remote-client':'web',...clientIdHeaders()},valid:connection.valid},$('desktop-plugin-page'),route)
3569
3753
  }
3570
3754
 
3571
3755
  function showView(id) {
3756
+ if (id !== 'view-chat') window.DshSubagents?.close()
3757
+ document.body?.classList.toggle('viewing-subagent', id === 'view-chat' && state.byId.get(state.current)?.origin === 'subagent')
3572
3758
  window.DshWorkflow?.close()
3573
3759
  if (window.DshWorkflow?.isMounted() && id === 'view-overview') id = 'view-sessions'
3574
3760
  if (id !== 'view-chat') conversationView?.pause()
@@ -3594,6 +3780,7 @@ function showView(id) {
3594
3780
 
3595
3781
  function updateSessionActions() {
3596
3782
  const active = state.view === 'view-chat' && !!state.current
3783
+ $('btn-subagents')?.classList.toggle('hidden', !active)
3597
3784
  $('btn-rename-session')?.classList.toggle('hidden', !active)
3598
3785
  $('btn-archive-session')?.classList.toggle('hidden', !active || state.archivedIds.includes(state.current))
3599
3786
  $('ds-session-status')?.classList.toggle('hidden', !active || !recoveryLabel())
@@ -3947,6 +4134,7 @@ async function start() {
3947
4134
  }
3948
4135
  $('token-desc').textContent = state.token ? '● ' + state.token.slice(0, 12) + '…' : t('ds.toastAuth')
3949
4136
  bindUi()
4137
+ window.DshImagePreview?.configure?.({ resolvePath: chatImageRequest })
3950
4138
  if (!state.token) { showView('view-settings'); $('desktop-token-input').focus() }
3951
4139
  renderWorkbench()
3952
4140
  updateConn()
@@ -3984,6 +4172,7 @@ function mountWorkflowDesktop() {
3984
4172
  },
3985
4173
  command:runSlashCommand,send:sendMessage,refresh:refreshSessions,retry:()=>{startOverviewDetection(true);void refreshSessions()},
3986
4174
  operations:()=>{const connection=captureConnection();return {url:apiUrl,headers:{authorization:'Bearer '+connection.token},valid:connection.valid}},
4175
+ relay:()=>{const connection=captureConnection();return {url:()=>apiUrl('/admin/api/relay'),headers:{authorization:'Bearer '+connection.token},valid:connection.valid,connected:!!connection.token}},
3987
4176
  discover:()=>{if(confirm('登记当前绑定目录下的子目录为工作区?'))void refreshWorkbench({discover:true})},
3988
4177
  files:()=>{const cwd=sessionCwd(state.byId.get(state.current));if(!cwd)return toast('当前会话没有工作目录','err');state.fs.loaded=true;showView('view-files');void loadFs(cwd,true)},
3989
4178
  admin:()=>window.open(new URL(apiUrl('/admin/'),location.href).href,'_blank','noopener,noreferrer'),
@@ -4002,3 +4191,6 @@ function mountWorkflowDesktop() {
4002
4191
  recover:(row,receipt)=>{const value=receipt.result?.result?.value;if(row.method==='session.create'&&value?.sessionId)void openSession(value.sessionId);if(row.sessionId===state.current)void resyncCurrentSession()},
4003
4192
  })
4004
4193
  }
4194
+
4195
+ // Operation logs stay on this device; users can copy or export them.
4196
+ globalThis.DshDiagnostics?.configure({surface:"desktop",copy:copyText,snapshot:()=>({sessionId:state.current,server:state.server,loading:!!state.history.loading,loaded:!!state.history.loaded,count:state.history.visible.length,...globalThis.DshDiagnostics.nativeSnapshot()})})