dsh-remote-plugin 0.7.6 → 0.8.0-rc.3

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 = {}
@@ -561,11 +561,13 @@ function closeNotesModal() {
561
561
  if (notesVersion) { LS.set(NOTES_KEY, notesVersion); notesVersion = '' }
562
562
  }
563
563
  async function checkNotesOnStart() {
564
+ if (typeof window !== 'undefined' && window.DshWorkflow?.isMounted()) return
564
565
  try {
565
566
  const res = await fetch('../update.json?t=' + Date.now(), { cache: 'no-store' })
566
567
  if (!res.ok || res.redirected || !String(res.headers.get('content-type') || '').includes('application/json')) return
567
568
  const info = await res.json()
568
569
  if (!info || typeof info !== 'object' || !info.version) return
570
+ if (typeof window !== 'undefined' && window.DshWorkflow?.isMounted()) return
569
571
  openNotesModal(info)
570
572
  } catch {}
571
573
  }
@@ -661,12 +663,20 @@ async function rpc(method, payload = {}, timeoutMs = 45000) {
661
663
  if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
662
664
  opts.signal = AbortSignal.timeout(timeoutMs)
663
665
  }
664
- const res = await fetch(apiUrl('/api/' + method), opts)
666
+ const operation = window.DshOperations?.supports(method) && activeGatewayCapability('operations') === true
667
+ const connection = operation ? captureConnection() : null
668
+ const receipt = operation ? await window.DshOperations.execute({ method, payload, url: apiUrl, headers: opts.headers, valid: () => connection.valid() }) : null
669
+ const res = receipt ? { status: 200, ok: true, json: async () => receipt } : await fetch(apiUrl('/api/' + method), opts)
665
670
  if (res.status === 401) throw new Error('AUTH')
666
671
  if (!res.ok) throw new Error('HTTP ' + res.status)
667
672
  const full = await res.json()
668
673
  if (!full?.result) throw new Error('bad response')
669
- if (!full.result.ok) throw new Error(full.result.error?.message || 'dsh error')
674
+ if (!full.result.ok) {
675
+ const err = full.result.error || {}
676
+ const error = new Error(err.code === 'session/migration-required' ? t('session.migrationRequired') : err.message || 'dsh error')
677
+ error.code = err.code
678
+ throw error
679
+ }
670
680
  return full.result.value
671
681
  }
672
682
  async function respond(rpcId, value) {
@@ -928,6 +938,7 @@ function renderGroupSelect() {
928
938
  const menu = $('group-select-menu')
929
939
  if (!label || !menu) return
930
940
  label.textContent = state.activeGroup
941
+ $('group-select-btn')?.setAttribute('aria-label', t('ds.groupsCurrentLabel', { group: state.activeGroup }))
931
942
  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('')
932
943
  menu.querySelectorAll('[data-group-option]').forEach(b => b.addEventListener('click', () => {
933
944
  closeGroupMenu()
@@ -1016,7 +1027,7 @@ function renderServers() {
1016
1027
  const activeManual = state.groupActive[g] || ''
1017
1028
  return `<div class="ds-srv-group" data-group="${esc(g)}">
1018
1029
  <div class="ds-srv-head">
1019
- <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>
1030
+ <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>
1020
1031
  <button class="ds-mini" data-speed-group="${esc(g)}" title="${t('ds.speedTest')}">⚡</button>
1021
1032
  <label class="ds-switch" title="${t('ds.groupsAutoSelect')}"><input type="checkbox" data-auto-group="${esc(g)}" ${auto ? 'checked' : ''}><span class="ds-slider"></span></label>
1022
1033
  ${g !== '默认' ? `<button class="ds-mini" data-del-group="${esc(g)}" title="${t('ds.groupsDelete')}">✕</button>` : ''}
@@ -1024,15 +1035,18 @@ function renderServers() {
1024
1035
  <div class="ds-srv-body ${g === state.activeGroup ? '' : 'hidden'}">
1025
1036
  ${list.map(s => {
1026
1037
  const ms = state.serverLatency[serverKey(s)]
1027
- let badge = `<span class="ds-server-badge">${t('ds.serversUntested')}</span>`
1028
1038
  const active = s.url === state.server && serverToken(s) === state.token
1029
- if (Number.isFinite(ms)) badge = `<span class="ds-server-badge ${active ? 'good' : ''}">${ms}ms${active ? t('ds.serversCurrent') : ''}</span>`
1039
+ // One status per row keeps long addresses readable.
1040
+ let badge = `<span class="ds-server-badge">${t('ds.serversUntested')}</span>`
1041
+ if (!s.token) badge = `<span class="ds-server-badge bad">${t('ds.serversTokenMissing')}</span>`
1042
+ else if (Number.isFinite(ms)) badge = `<span class="ds-server-badge ${active ? 'good' : ''}">${ms}ms${active ? t('ds.serversCurrent') : ''}</span>`
1030
1043
  else if (ms !== undefined) badge = `<span class="ds-server-badge bad">${t('ds.serversUnreachable')}</span>`
1044
+ else if (active) badge = `<span class="ds-server-badge good">${t('ds.serversCurrentOnly')}</span>`
1031
1045
  const activeInGroup = auto ? active : s.id === activeManual
1032
1046
  return `<div class="ds-server-row ${activeInGroup ? 'active' : ''}" data-use-server="${esc(s.id)}">
1033
- <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}
1034
- <button class="ds-mini" data-edit-server="${esc(s.id)}" title="${t('ds.serversEdit')}">✎</button>
1035
- <button class="ds-mini" data-del-server="${esc(s.id)}" title="${t('ds.serversDelete')}">✕</button>
1047
+ <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}
1048
+ <button class="ds-mini ds-server-edit" data-edit-server="${esc(s.id)}" title="${t('ds.serversEdit')}" aria-label="${t('ds.serversEdit')}">✎</button>
1049
+ <button class="ds-mini ds-server-del" data-del-server="${esc(s.id)}" aria-label="${t('ds.serversDelete')}">✕</button>
1036
1050
  </div>`
1037
1051
  }).join('') || `<div class="ds-empty">${t('ds.groupsNoServer')}</div>`}
1038
1052
  </div>
@@ -1074,7 +1088,7 @@ function renderServers() {
1074
1088
  const curGroup = cur ? cur.group : state.activeGroup
1075
1089
  const curLabel = cur ? (cur.note || cur.url) : (state.server || t('ds.origin'))
1076
1090
  const curMs = cur ? state.serverLatency[serverKey(cur)] : undefined
1077
- $('server-desc').textContent = t('ds.serversCurrentDesc', { group: curGroup, url: curLabel, ms: Number.isFinite(curMs) ? curMs + 'ms' : '—' })
1091
+ $('server-desc').textContent = t('ds.serversCurrentDesc', { group: curGroup, url: curLabel }) + (Number.isFinite(curMs) ? ' · ' + curMs + 'ms' : '')
1078
1092
  updateConn()
1079
1093
  }
1080
1094
 
@@ -1390,7 +1404,7 @@ async function pollKind(kind, cancellation) {
1390
1404
  const timeout = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(window.DshNetwork?.profile().pollTimeout || 30000) : undefined
1391
1405
  const signal = cancellation && timeout && typeof AbortSignal.any === 'function' ? AbortSignal.any([cancellation, timeout]) : timeout || cancellation
1392
1406
  const headers = { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }
1393
- res = signal ? await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000`), { signal, headers }) : await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000`), { headers })
1407
+ res = await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000&epoch=${encodeURIComponent(cursors[kind + "Epoch"] || "")}`), { ...(signal ? { signal } : {}), headers })
1394
1408
  } catch { return }
1395
1409
  if (!valid()) return
1396
1410
  if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
@@ -1399,13 +1413,15 @@ async function pollKind(kind, cancellation) {
1399
1413
  try { data = await res.json() } catch { return }
1400
1414
  if (!valid()) return
1401
1415
  if (!data || !Array.isArray(data.events)) return
1402
- const reset = data.truncated === true || (typeof data.latestSeq === 'number' && data.latestSeq < since)
1416
+ const reset = data.reset === true || (!!data.epoch && !!cursors[kind + 'Epoch'] && cursors[kind + 'Epoch'] !== data.epoch) || data.truncated === true || (typeof data.latestSeq === 'number' && data.latestSeq < since)
1403
1417
  if (reset) {
1404
1418
  state.pollSeq[kind] = 0
1405
1419
  if (kind === 'mux') renderNotifStack()
1406
1420
  refreshSessions()
1407
1421
  if (state.current) void resyncCurrentSession()
1408
1422
  }
1423
+ if (data.epoch) cursors[kind + 'Epoch'] = data.epoch
1424
+ for (const frame of data.baseline || []) { if (kind === 'mux') onMuxFrame(frame); else onHostFrame(frame) }
1409
1425
  for (const item of data.events) {
1410
1426
  if (item.seq > (state.pollSeq[kind] || 0)) {
1411
1427
  state.pollSeq[kind] = item.seq
@@ -1521,6 +1537,7 @@ function setCompactionStatus(sessionId, next) {
1521
1537
  }
1522
1538
  if (previous?.active && previous.notify && next?.notify !== false && ['complete', 'failed'].includes(next?.phase)) {
1523
1539
  const command = previous.command || 'compact'
1540
+ if (command === 'export' && next?.phase === 'complete' && state.current === sessionId && typeof downloadSessionExport === 'function') void downloadSessionExport(sessionId)
1524
1541
  if (next?.phase === 'failed') toast(command === 'compact'
1525
1542
  ? t('ds.compactFailed', { msg: next.message || t('ds.sessionRecoveryFailed') })
1526
1543
  : t('ds.commandFailed', { command, msg: next.message || t('ds.sessionRecoveryFailed') }), 'err')
@@ -1600,9 +1617,15 @@ function hydrateSessionProjections(sessionId, projections) {
1600
1617
  if (!s || !projections || typeof projections !== 'object') return
1601
1618
  const incomingSeq = Number(projections.asOfSeq) || 0
1602
1619
  const current = s.projections || { asOfSeq: 0, values: {} }
1620
+ if (projections.kind === 'cached' && current.kind === 'sequenced') return
1621
+ if (current.kind === 'cached' || projections.kind === 'cached') {
1622
+ s.projections = { ...projections, asOfSeq: incomingSeq, kind: projections.kind || 'sequenced', values: { ...(current.values || {}), ...(projections.values || {}) } }
1623
+ return
1624
+ }
1603
1625
  const currentSeq = Number(current.asOfSeq) || 0
1604
1626
  if (incomingSeq < currentSeq) return
1605
1627
  s.projections = {
1628
+ kind: projections.kind || current.kind || 'sequenced',
1606
1629
  asOfSeq: Math.max(currentSeq, incomingSeq),
1607
1630
  values: { ...(current.values || {}), ...(projections.values || {}) }
1608
1631
  }
@@ -1623,6 +1646,7 @@ function applyProjection(sessionId, key, value, seq) {
1623
1646
  state.pendingProjections.set(sessionId, pending)
1624
1647
  return
1625
1648
  }
1649
+ if (s.projections?.kind === 'cached') s.projections = { kind: 'sequenced', asOfSeq: 0, values: { ...(s.projections.values || {}) } }
1626
1650
  const currentSeq = Number(s.projections?.asOfSeq) || 0
1627
1651
  if (seq && seq < currentSeq) return
1628
1652
  s.projections = s.projections || { asOfSeq: 0, values: {} }
@@ -1780,6 +1804,12 @@ async function refreshSessions() {
1780
1804
  if (!v) { renderSessions(); renderOverviewDesktop(); return }
1781
1805
  state.sessions = v.items || []
1782
1806
  state.byId = new Map(state.sessions.map(s => [s.sessionId, s]))
1807
+ for (const [id, child] of Object.entries(state.subagentSessions || {})) {
1808
+ const listed = state.byId.get(id)
1809
+ const merged = listed ? { ...child, ...listed, parentSessionId: child.parentSessionId, subagentMode: child.subagentMode, origin: 'subagent' } : child
1810
+ state.byId.set(id, merged)
1811
+ state.subagentSessions[id] = merged
1812
+ }
1783
1813
  applyPendingProjections()
1784
1814
  try{LS.set(historyCacheScope()+':sessions',JSON.stringify(state.sessions.slice(0,80)))}catch{}
1785
1815
  renderSessions()
@@ -1905,6 +1935,7 @@ const emptySessionCleanup = new Set()
1905
1935
  async function archiveEmptySessionOnLeave(sessionId, leaving = false) {
1906
1936
  const base = state.server, connection=captureConnection()
1907
1937
  const protectedSession = () => !connection.valid() || state.server !== base || (!leaving && state.current !== sessionId)
1938
+ || !!state.byId.get(sessionId)?.parentSessionId || state.byId.get(sessionId)?.origin === 'subagent'
1908
1939
  || !state.byId.has(sessionId) || state.byId.get(sessionId)?.running
1909
1940
  || state.sessionActivity?.has(sessionId) || state.pendingPrompts?.has(sessionId)
1910
1941
  || (state.queues[sessionId] || []).length > 0
@@ -1948,6 +1979,8 @@ async function openSession(id) {
1948
1979
  }
1949
1980
  async function closeSession() {
1950
1981
  const sessionId = state.current
1982
+ const parentId = state.byId.get(sessionId)?.parentSessionId
1983
+ if (parentId && parentId !== sessionId) return openSession(parentId)
1951
1984
  if (sessionId) await archiveEmptySessionOnLeave(sessionId)
1952
1985
  if (state.current !== sessionId) return
1953
1986
  state.current = null
@@ -1978,7 +2011,7 @@ function getConversationView() {
1978
2011
  if(!conversationView)conversationView=new window.DshHistory.HistoryView($('history'),{
1979
2012
  html:entry=>eventHtml(entry),
1980
2013
  older:()=>loadHistory(false),olderLabel:()=>t('ds.historyEarlier'),loadingLabel:()=>t('ds.historyLoadingEarlier'),live:partialReasoningHtml,
1981
- 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':'有新内容'):'');}},
2014
+ 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':'有新内容'):'')}},
1982
2015
  scrolled:()=>{}
1983
2016
  })
1984
2017
  return conversationView
@@ -2023,6 +2056,8 @@ async function loadHistory(reset = true) {
2023
2056
  if(reset){if(hadContent)historySource('syncing');else setSessionRecovery('loading')}
2024
2057
  const network=window.DshNetwork?.profile() || {historyPageSize:60,readTimeout:45000}
2025
2058
  const payload={sessionId:id,maxMessages:network.historyPageSize}
2059
+ const child=state.subagentSessions?.[id] || state.byId.get(id)
2060
+ if(child?.origin==='subagent' && child.parentSessionId) Object.assign(payload,{parentSessionId:child.parentSessionId,subagentMode:child.subagentMode || 'unknown'})
2026
2061
  if(!reset&&Number.isFinite(history.minSeq))payload.beforeSeq=history.minSeq
2027
2062
  getConversationView().more.disabled=true
2028
2063
  getConversationView().more.textContent=getConversationView().options.loadingLabel()
@@ -2128,7 +2163,9 @@ function applyReasoningStreamEvent(event) {
2128
2163
  return changed
2129
2164
  }
2130
2165
  let reasoningRenderTimer = null
2166
+ function weakStreamTrim() { return !!window.DshNetwork?.streamTrimmed?.() }
2131
2167
  function scheduleReasoningRender() {
2168
+ if (weakStreamTrim()) return
2132
2169
  if (reasoningRenderTimer) return
2133
2170
  reasoningRenderTimer = setTimeout(() => {
2134
2171
  reasoningRenderTimer = null
@@ -2136,22 +2173,32 @@ function scheduleReasoningRender() {
2136
2173
  }, 80)
2137
2174
  }
2138
2175
  function partialReasoningHtml() {
2176
+ if (weakStreamTrim()) return ''
2139
2177
  return [...state.history.partialReasoning.values()]
2140
2178
  .filter(item => item.text)
2141
2179
  .sort((a, b) => (a.turn ?? 0) - (b.turn ?? 0) || (a.step ?? 0) - (b.step ?? 0) || (a.index ?? 0) - (b.index ?? 0))
2142
- .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>`)
2180
+ .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>`)
2143
2181
  .join('')
2144
2182
  }
2145
2183
  function safeJson(v) { try { return JSON.stringify(v, null, 2) } catch { return String(v) } }
2146
- function blockHtml(b) {
2184
+ function blockHtml(b,index=0,context={}) {
2147
2185
  if (!b) return ''
2148
- if (b.type === 'text') return `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '', { fileLinks: true }) : esc(b.text ?? '')}</div>`
2186
+ if ((b.type === 'tool-call' || b.type === 'tool-result') && context.suppressBlockTools) return ''
2187
+ if (typeof window !== 'undefined' && window.DshActivity) {
2188
+ const key='block:'+context.seq+':'+index
2189
+ if (b.type==='thinking'||b.type==='reasoning') return window.DshActivity.reasoning({text:b.text??b.content??'',key:window.DshActivity.reasoningKey(context,index,key)})
2190
+ 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)})})
2191
+ }
2192
+ if (b.type === 'text') return `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '', { fileLinks: true, imageLabel: t('block.image') }) : esc(b.text ?? '')}</div>`
2149
2193
  if (b.type === 'file' && typeof window !== 'undefined' && window.DshChatFiles) return window.DshChatFiles.render(b)
2150
2194
  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>`
2151
2195
  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>`
2152
2196
  if (b.type === 'tool-call') return `<div>🔧 ${esc(b.name || '')}</div>`
2153
2197
  if (b.type === 'tool-result') return `<div>📦</div>`
2154
- if (b.type === 'image') return `<div>🖼</div>`
2198
+ if (b.type === 'image') {
2199
+ const alt = b.name || b.filename || t('block.image')
2200
+ 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>`
2201
+ }
2155
2202
  return ''
2156
2203
  }
2157
2204
  function systemReminderText(blocks) {
@@ -2161,11 +2208,25 @@ function systemReminderText(blocks) {
2161
2208
  .map(b => String(b.text ?? ''))
2162
2209
  .join('\n')
2163
2210
  }
2211
+ function activityGroupHtml(group) {
2212
+ const items = group.items || []
2213
+ if (!items.length) return ''
2214
+ const tools = items.filter(item => item.kind === 'tool').map(item => item.entry)
2215
+ const running = !!group.running
2216
+ const failed = tools.some(entry => entry.view?.toolActivity?.error || entry.event?.data?.error)
2217
+ const body = items.map(item => item.kind === 'reasoning'
2218
+ ? window.DshActivity.reasoning({ text: item.text, key: item.key })
2219
+ : eventHtml(item.entry)).join('')
2220
+ 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>`
2221
+ }
2222
+
2164
2223
  function eventHtml(entry) {
2165
2224
  const ev = entry.event || {}
2166
2225
  const data = ev.data || {}
2167
2226
  const type = ev.type || 'event'
2227
+ if (entry.view?.activityGroup) return activityGroupHtml(entry.view.activityGroup)
2168
2228
  if (!shouldShowEvent(type, ev)) return ''
2229
+ if (window.DshActivity && (type==='tool/call'||type==='tool/result')) return window.DshActivity.toolEvent(entry)
2169
2230
  if (type === 'user/message' || type === 'assistant/message') {
2170
2231
  const msg = data.message || {}
2171
2232
  const role = data.role || msg.role || (type.startsWith('user') ? 'user' : 'assistant')
@@ -2176,8 +2237,9 @@ function eventHtml(entry) {
2176
2237
  return `<details class="event ds-tool ds-event-detail"><summary>${esc(t('ds.eventSystemReminder'))}</summary><pre>${esc(shown)}</pre></details>`
2177
2238
  }
2178
2239
  if (type === 'user/message' && !isHumanUserMessage(ev)) return ''
2179
- const text = blocks.map(blockHtml).join('')
2180
- 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>`
2240
+ const text = blocks.map((block,index)=>blockHtml(block,index,{...data,seq:entry.seq,suppressBlockTools:state.history.suppressBlockTools})).join('')
2241
+ if (!text) return ''
2242
+ return `<div class="ds-msg ${esc(role)}"><div class="role">${esc(role === 'user' ? t('ds.role.me') : t('ds.role.dsh'))}</div>${text}</div>`
2181
2243
  }
2182
2244
  if (type === 'tool/call') {
2183
2245
  const name = data.name || data.toolName || t('ds.toolDefault')
@@ -2194,16 +2256,44 @@ function eventHtml(entry) {
2194
2256
  return `<div class="ds-tool">${esc(type)}</div>`
2195
2257
  }
2196
2258
  function renderHistory(reset=false, mode='auto') {
2197
- getConversationView().set(state.history.visible,{reset,follow:mode==='bottom',live:partialReasoningHtml(),hasMore:state.history.hasMore,loading:state.history.loading,emptyLabel:t('ds.historyEmpty')})
2198
- }
2259
+ let prepared=window.DshActivity?.prepare(state.history.visible)||state.history.visible
2260
+ if(weakStreamTrim())prepared=prepared.filter(entry=>entry.event?.type!=='tool/call'||entry.view?.toolActivity)
2261
+ state.history.suppressBlockTools = state.history.visible.some(entry => entry.event?.type === 'tool/call')
2262
+ if(window.DshActivity?.group)prepared=window.DshActivity.group(prepared)
2263
+ const sessionRunning = !!state.byId.get(state.current)?.running
2264
+ const groups = prepared.filter(entry => entry.view?.activityGroup)
2265
+ const activeGroup = groups.at(-1)
2266
+ if (activeGroup) activeGroup.view.activityGroup.running = sessionRunning
2267
+ getConversationView().set(prepared,{reset,follow:mode==='bottom',live:partialReasoningHtml(),hasMore:state.history.hasMore,loading:state.history.loading,emptyLabel:t('ds.historyEmpty')})
2268
+ window.DshImagePreview?.hydrate?.($('history'))
2269
+ }
2270
+ window.applyStreamPreference=()=>{if(state.current)renderHistory(false,'auto')}
2199
2271
 
2200
2272
  /* ---------------- 会话信息卡(goal / todo / 子代理) ---------------- */
2201
2273
  let sessionSubagentsJob = null
2274
+ function rememberSubagent(entry, parentId) {
2275
+ const childId = entry.id
2276
+ const child = state.byId.get(childId) || { sessionId: childId, cwd: state.byId.get(parentId)?.cwd || '' }
2277
+ Object.assign(child, { parentSessionId: parentId, origin: 'subagent', subagentMode: entry.mode || child.subagentMode || 'unknown' })
2278
+ if (entry.label && !child.projections?.values?.title) {
2279
+ child.projections ||= { values: {} }
2280
+ child.projections.values ||= {}
2281
+ child.projections.values.title = entry.label
2282
+ }
2283
+ state.byId.set(childId, child)
2284
+ state.subagentSessions ||= {}
2285
+ state.subagentSessions[childId] = child
2286
+ }
2287
+ async function openSubagentSession(childId, parentId, entry = {}, rootId = parentId) {
2288
+ if (!childId || childId === parentId || state.current !== rootId) return
2289
+ rememberSubagent({ ...entry, id: childId }, parentId)
2290
+ await openSession(childId)
2291
+ }
2202
2292
  async function loadSessionSubagents(sessionId) {
2203
2293
  if (sessionSubagentsJob?.sessionId === sessionId && sessionSubagentsJob.connection.valid()) return sessionSubagentsJob.promise
2204
2294
  const connection = captureConnection(), job = { sessionId, connection }
2205
2295
  job.promise = (async () => {
2206
- const value = await safeRpc('subagent.list', { parentSessionId: sessionId }, '')
2296
+ const value = await rpc('subagent.list', { parentSessionId: sessionId })
2207
2297
  return connection.valid() ? value : null
2208
2298
  })()
2209
2299
  sessionSubagentsJob = job
@@ -2260,30 +2350,15 @@ async function renderSessionCards() {
2260
2350
  requestAnimationFrame(() => box.querySelector(`[data-goal-collapse="${collapse ? '0' : '1'}"]`)?.focus())
2261
2351
  }))
2262
2352
 
2263
- const sub = await loadSessionSubagents(sessionId)
2264
2353
  if (!connection.valid() || renderGeneration !== sessionCardsRenderGeneration || state.current !== sessionId) return
2265
- if (sub?.entries?.length) {
2266
- const expanded = state.subagentExpandedSession === sessionId
2267
- const toggleLabel = expanded ? t('subagent.collapse') : t('subagent.expand')
2268
- const rows = sub.entries.map(e => {
2269
- 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>`
2270
- const label = e.label || short(e.id)
2271
- const running = e.activity === 'running'
2272
- 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>`
2273
- }).join('')
2274
- const subagentClosedIcon = 'M7 10l5 5 5-5'
2275
- const subagentOpenIcon = 'M7 14l5-5 5 5'
2276
- const subagentIcon = expanded ? subagentOpenIcon : subagentClosedIcon
2277
- 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>`)
2278
- box.querySelector('[data-subagent-toggle]')?.addEventListener('click', () => {
2279
- const icon = box.querySelector('[data-subagent-toggle] morph-icon')
2280
- if (icon) icon.setAttribute('data-morph-state', expanded ? 'closed' : 'open')
2281
- state.subagentExpandedSession = expanded ? '' : sessionId
2282
- setTimeout(() => renderSessionCards(), 240)
2283
- })
2284
- box.querySelectorAll('[data-sub-interrupt]').forEach(btn =>
2285
- btn.addEventListener('click', () => interruptSubagent(btn.dataset.subInterrupt)))
2286
- }
2354
+ window.DshSubagents?.configure($('btn-subagents'), {
2355
+ sessionId, title: titleOf(s), activity: s.running === true ? 'running' : s.running === false ? 'inactive' : 'unknown', parentId: s.origin === 'subagent' ? s.parentSessionId : null,
2356
+ valid: () => connection.valid() && state.current === sessionId,
2357
+ read: loadSessionSubagents, remember: rememberSubagent,
2358
+ onShow: () => conversationView?.pause(), onClose: () => conversationView?.resume(),
2359
+ open: (entry, parentId) => openSubagentSession(entry.id, parentId, entry, sessionId),
2360
+ interrupt: interruptSubagent,
2361
+ })
2287
2362
  }
2288
2363
 
2289
2364
  function setGoalPhaseLocal(phase) {
@@ -2328,10 +2403,11 @@ async function goalAction(kind) {
2328
2403
  renderSessionCards()
2329
2404
  }
2330
2405
 
2331
- async function interruptSubagent(childId) {
2406
+ async function interruptSubagent(childId, parentId = state.current) {
2407
+ const connection = captureConnection(), rootId = state.current
2332
2408
  if (!confirm(t('subagent.confirmInterrupt'))) return
2333
- const result = await safeRpc('subagent.interrupt', { parentSessionId: state.current, childSessionId: childId, mode: 'continuable' }, t('subagent.interruptFailed'))
2334
- if (result == null) return
2409
+ const result = await safeRpc('subagent.interrupt', { parentSessionId: parentId, childSessionId: childId, mode: 'continuable' }, t('subagent.interruptFailed'))
2410
+ if (result == null || !connection.valid() || state.current !== rootId) return
2335
2411
  toast(t('subagent.interruptSubmitted'), 'ok')
2336
2412
  setTimeout(renderSessionCards, 600)
2337
2413
  }
@@ -2392,7 +2468,7 @@ async function runSlashCommand(text) {
2392
2468
  const res = await fetch(apiUrl('/remote/api/command'), {
2393
2469
  method: 'POST',
2394
2470
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() },
2395
- body: JSON.stringify({ sessionId, line: clean }),
2471
+ body: JSON.stringify({ sessionId, line: clean, async: true }),
2396
2472
  ...(signal ? { signal } : {})
2397
2473
  })
2398
2474
  if (!connection.valid()) return true
@@ -2406,7 +2482,7 @@ async function runSlashCommand(text) {
2406
2482
  if (data?.ok === false) return true
2407
2483
  if (data?.ok === true && data.executed === true) {
2408
2484
  if (data.accepted) {
2409
- if (command === 'compact') {
2485
+ if (command === 'compact' || command === 'export') {
2410
2486
  setCompactionStatus(sessionId, { ...(data.operation || data.compact), active: true, command, source: 'command' })
2411
2487
  } else {
2412
2488
  state.pendingCommands[sessionId] = command
@@ -2426,7 +2502,8 @@ async function runSlashCommand(text) {
2426
2502
  return !connection.valid() || state.current !== sessionId
2427
2503
  }
2428
2504
 
2429
- async function sendMessage() {
2505
+ async function sendMessage(requestedMode = 'queue') {
2506
+ if (state.byId.get(state.current)?.origin === 'subagent') { toast('子代理记录为只读 / Subagent records are read only'); return false }
2430
2507
  const input = $('composer')
2431
2508
  const originalText = input.value, text = originalText.trim()
2432
2509
  if (!text || !state.current) return
@@ -2442,7 +2519,7 @@ async function sendMessage() {
2442
2519
  setSessionRecovery('resuming')
2443
2520
  const v = await safeRpc('session.prompt', {
2444
2521
  sessionId,
2445
- mode: 'queue',
2522
+ mode: requestedMode === 'steer' && state.byId.get(sessionId)?.running ? 'steer' : 'queue',
2446
2523
  content: [{ type: 'text', text }]
2447
2524
  }, '')
2448
2525
  if (!valid()) return
@@ -2451,7 +2528,7 @@ async function sendMessage() {
2451
2528
  setSessionRecovery('ready'); noteSessionTurnTime(sessionId, Date.now()); renderSessions(); toast(t('ds.toastSent'), 'ok')
2452
2529
  }
2453
2530
  else setSessionRecovery('error')
2454
- } finally { pending.delete(history) }
2531
+ } finally { pending.delete(history); window.DshWorkflow?.update() }
2455
2532
  }
2456
2533
 
2457
2534
  async function cancelSession() {
@@ -2512,6 +2589,7 @@ async function archiveCurrentSession() {
2512
2589
  }
2513
2590
 
2514
2591
  function updateComposerStatus() {
2592
+ window.DshWorkflow?.update()
2515
2593
  const status = $('composer-status')
2516
2594
  if (!status) return
2517
2595
  const compact = activeCompaction()
@@ -2727,6 +2805,18 @@ function fsApiUrl(sub, params = {}) {
2727
2805
  function fsHeaders() {
2728
2806
  return { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }
2729
2807
  }
2808
+
2809
+ /** Local image paths inside Markdown: resolve relative to the open session workspace. */
2810
+ function chatImageRequest(pathValue) {
2811
+ const value = String(pathValue || '').trim()
2812
+ if (!value) return null
2813
+ let target = value
2814
+ if (!/^(?:[A-Za-z]:[\\/]|\\\\|\/|~[\\/])/.test(value)) {
2815
+ const root = state.byId.get(state.current)?.cwd || ''
2816
+ if (root) target = root.replace(/[\\/]+$/, '') + (root.includes('\\') ? '\\' : '/') + value.replace(/^\.?[\\/]+/, '')
2817
+ }
2818
+ return { url: fsApiUrl('/file', { path: target }), headers: fsHeaders() }
2819
+ }
2730
2820
  function fsParent(p) {
2731
2821
  const meta = fsPathMeta(p)
2732
2822
  if (!meta.value) return null
@@ -3036,13 +3126,15 @@ function commitWorkspaceSessionOrder(workspaceId, order) {
3036
3126
  renderWorkbench()
3037
3127
  toast(t('ds.wbOrderSaved'), 'ok')
3038
3128
  }
3039
- async function refreshWorkbench({ silent = false } = {}) {
3129
+ async function refreshWorkbench({ silent = false, discover = false } = {}) {
3040
3130
  const connection = captureConnection(), request = ++workbenchRequest
3041
3131
  const valid = () => connection.valid() && request === workbenchRequest
3132
+ const sharedRead = (name, read) => window.DshNetwork?.shareRead ? window.DshNetwork.shareRead(JSON.stringify([connection.server, connection.token, name]), read) : read()
3042
3133
  if (!state.token) { renderWorkbench(); return }
3134
+ const workspaceRead = sharedRead('workspace.list', () => connection.valid() ? safeRpc('workspace.list', {}, '') : null)
3043
3135
  let wb = null
3044
3136
  try {
3045
- wb = await wbGateway('GET', '/workbench')
3137
+ wb = await sharedRead('workbench', () => connection.valid() ? wbGateway('GET', '/workbench') : null)
3046
3138
  if (!valid()) return
3047
3139
  state.wb.apiMissing = false
3048
3140
  } catch (e) {
@@ -3051,10 +3143,12 @@ async function refreshWorkbench({ silent = false } = {}) {
3051
3143
  if (!silent) toast(t('wb.loadFailed', { msg: e.message }), 'err')
3052
3144
  if (!state.wb.bound && /404/.test(e.message)) state.wb.apiMissing = true
3053
3145
  }
3054
- const wl = await safeRpc('workspace.list', {}, '')
3146
+ const wl = await workspaceRead
3055
3147
  if (!valid()) return
3056
- state.archivedIds = wl && Array.isArray(wl.archivedSessionIds) ? wl.archivedSessionIds : []
3057
- state.workspaces = wl && Array.isArray(wl.items) ? wl.items.slice() : []
3148
+ if(wl){
3149
+ state.archivedIds = Array.isArray(wl.archivedSessionIds) ? wl.archivedSessionIds : []
3150
+ state.workspaces = Array.isArray(wl.items) ? wl.items.slice() : []
3151
+ }
3058
3152
  if (!wb) { renderWorkbench(); renderSessions(); return }
3059
3153
  if (!wb.bound) {
3060
3154
  state.wb = { bound: false, path: '', title: '', expanded: false, projects: null, open: null, apiMissing: false }
@@ -3065,9 +3159,9 @@ async function refreshWorkbench({ silent = false } = {}) {
3065
3159
  state.wb.bound = true
3066
3160
  state.wb.path = wb.path || ''
3067
3161
  state.wb.title = wb.title || ''
3068
- if (!wl) { state.wb.projects = []; renderWorkbench(); renderSessions(); return }
3162
+ if (!wl) { renderWorkbench(); renderSessions(); return }
3069
3163
  const items = Array.isArray(wl.items) ? wl.items.slice() : []
3070
- try {
3164
+ if (discover) try {
3071
3165
  const listRes = await fetch(fsApiUrl('/list', { path: state.wb.path }), { headers: fsHeaders() })
3072
3166
  if (!valid()) return
3073
3167
  if (listRes.ok) {
@@ -3187,6 +3281,7 @@ async function openNewSessionModal() {
3187
3281
  if (!state.token) return showView('view-settings')
3188
3282
  if (!workspaceItems().length) await refreshWorkbench({ silent: true })
3189
3283
  renderNewSessionWorkspace(LS.get('lastNewSessionWorkspaceV1', ''))
3284
+ if (workspaceItems().length === 1) return createSessionInWorkspace()
3190
3285
  $('modal-new-session').classList.remove('hidden')
3191
3286
  setTimeout(() => $('new-session-workspace')?.focus(), 50)
3192
3287
  }
@@ -3204,9 +3299,12 @@ async function createSessionInWorkspace() {
3204
3299
  if (!connection.valid() || !value?.sessionId) return
3205
3300
  LS.set('lastNewSessionWorkspaceV1', workspaceId)
3206
3301
  closeNewSessionModal()
3207
- await refreshSessions()
3208
- if (!connection.valid()) return
3209
- openSession(value.sessionId)
3302
+ const workspace = workspaceById(workspaceId)
3303
+ const session = { sessionId: value.sessionId, cwd: workspace?.path || '', running: false, projections: { values: {} } }
3304
+ state.byId.set(session.sessionId, session)
3305
+ state.sessions.unshift(session)
3306
+ void openSession(session.sessionId)
3307
+ void refreshSessions()
3210
3308
  } finally {
3211
3309
  createSessionInWorkspace.busy = false
3212
3310
  button.disabled = false
@@ -3444,6 +3542,7 @@ window.addEventListener('offline',()=>startOverviewDetection(true))
3444
3542
  document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible')startOverviewDetection(true);else {overviewDetector?.pause();overviewPulse?.pause()}})
3445
3543
 
3446
3544
  function renderOverviewDesktop() {
3545
+ window.DshWorkflow?.update()
3447
3546
  const ring = $('ds-overview-pulse-ring')
3448
3547
  if (!ring) return
3449
3548
  const checks = overviewChecks()
@@ -3480,7 +3579,7 @@ function renderOverviewDesktop() {
3480
3579
  ...state.questions.map(q => ({ kind: 'question', item: q }))
3481
3580
  ]
3482
3581
  $('ds-overview-attention-count').textContent = pending.length ? t('ds.pendingCount', { n: pending.length }) : '—'
3483
- $('ds-overview-attention-list').innerHTML = pending.length ? pending.slice(0, 4).map(({ kind, item }) => {
3582
+ $('ds-overview-attention-list').innerHTML = pending.length ? pending.map(({ kind, item }) => {
3484
3583
  const title = sessionLabelOf(state.byId.get(item.sessionId))
3485
3584
  if (kind === 'approval') return `<div class="ds-overview-attention-item" data-ds-overview-approval="${esc(item.approvalId)}">
3486
3585
  <span class="ds-overview-mark">⌁</span><span class="ds-overview-copy"><span class="ds-overview-item-title">${esc(item.toolName || t('ds.toolDefault'))}</span><span class="ds-overview-item-desc">${esc(desktopApprovalDetail(item))} · ${esc(title)}</span></span>
@@ -3547,13 +3646,18 @@ function setMobileSidebar(open) {
3547
3646
  function openDesktopPlugins(route = 'manage') {
3548
3647
  const connection=captureConnection()
3549
3648
  if(!connection.token){$('desktop-plugin-page').textContent=t('ds.toastAuth');return}
3550
- 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)
3649
+ window.DshExtensions.mount({connection,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)
3551
3650
  }
3552
3651
 
3553
3652
  function showView(id) {
3653
+ if (id !== 'view-chat') window.DshSubagents?.close()
3654
+ document.body?.classList.toggle('viewing-subagent', id === 'view-chat' && state.byId.get(state.current)?.origin === 'subagent')
3655
+ window.DshWorkflow?.close()
3656
+ if (window.DshWorkflow?.isMounted() && id === 'view-overview') id = 'view-sessions'
3554
3657
  if (id !== 'view-chat') conversationView?.pause()
3555
3658
  if (state.view === 'view-chat' && id !== 'view-chat' && state.current) void archiveEmptySessionOnLeave(state.current)
3556
3659
  state.view = id
3660
+ document.body?.classList.toggle('workflow-at-start', !!window.DshWorkflow?.isMounted() && id === 'view-sessions')
3557
3661
  for (const v of ['view-overview', 'view-sessions', 'view-chat', 'view-files', 'view-plugins', 'view-settings']) $(v).classList.toggle('hidden', v !== id)
3558
3662
  if (id === 'view-chat') conversationView?.resume()
3559
3663
  document.querySelectorAll('.ds-nav-item').forEach(b => b.classList.toggle('active', b.dataset.view === id))
@@ -3573,6 +3677,7 @@ function showView(id) {
3573
3677
 
3574
3678
  function updateSessionActions() {
3575
3679
  const active = state.view === 'view-chat' && !!state.current
3680
+ $('btn-subagents')?.classList.toggle('hidden', !active)
3576
3681
  $('btn-rename-session')?.classList.toggle('hidden', !active)
3577
3682
  $('btn-archive-session')?.classList.toggle('hidden', !active || state.archivedIds.includes(state.current))
3578
3683
  $('ds-session-status')?.classList.toggle('hidden', !active || !recoveryLabel())
@@ -3772,7 +3877,7 @@ function bindUi() {
3772
3877
  $('btn-stats-top').addEventListener('click', toggleStatsDrawer)
3773
3878
  for (const id of ['history', 'question-body']) window.DshChatFiles?.bind($(id), () => {
3774
3879
  const c=captureConnection(),sessionId=id==='history'?state.current:state.questionModal?.sessionId
3775
- return { ...c,sessionId,cwd:sessionCwd(state.byId.get(sessionId)),native:false,headers:{authorization:'Bearer '+c.token,...clientIdHeaders()},notice:toast,
3880
+ return { ...c,sessionId,cwd:sessionCwd(state.byId.get(sessionId)),native:false,headers:{authorization:'Bearer '+c.token,...clientIdHeaders()},notice:toast,preview:(path,name)=>window.DshWorkflow?.preview({...c,headers:{authorization:'Bearer '+c.token}},path,name),
3776
3881
  valid:()=>c.valid()&&sessionId===(id==='history'?state.current:state.questionModal?.sessionId) }
3777
3882
  })
3778
3883
  $('btn-insights').addEventListener('click', () => openInsights())
@@ -3915,7 +4020,7 @@ async function start() {
3915
4020
  }
3916
4021
  loadServers()
3917
4022
  renderServers()
3918
- showView('view-overview')
4023
+ showView(window.DshWorkflow?.isMounted() ? 'view-sessions' : 'view-overview')
3919
4024
  if (urlToken) {
3920
4025
  state.token = urlToken
3921
4026
  const currentId = state.groupActive[state.activeGroup]
@@ -3926,6 +4031,7 @@ async function start() {
3926
4031
  }
3927
4032
  $('token-desc').textContent = state.token ? '● ' + state.token.slice(0, 12) + '…' : t('ds.toastAuth')
3928
4033
  bindUi()
4034
+ window.DshImagePreview?.configure?.({ resolvePath: chatImageRequest })
3929
4035
  if (!state.token) { showView('view-settings'); $('desktop-token-input').focus() }
3930
4036
  renderWorkbench()
3931
4037
  updateConn()
@@ -3942,3 +4048,43 @@ async function start() {
3942
4048
  }
3943
4049
 
3944
4050
  start()
4051
+ mountWorkflowDesktop()
4052
+
4053
+ function mountWorkflowDesktop() {
4054
+ window.DshWorkflow?.mount({
4055
+ desktop:true, start:()=>{if(state.view==='view-overview')showView('view-sessions')},
4056
+ snapshot:()=>({token:!!state.token,host:currentServerEntry()?.note || state.server || location.host,
4057
+ gateway:activeGatewayHealth()?.ok || !!state.streamsOk?.mux,dsh:dshReachable(),
4058
+ mux:!!state.streamsOk?.mux,hostEvents:!!state.streamsOk?.host,pending:state.approvals.length+state.questions.length,
4059
+ busy:!!state.byId.get(state.current)?.running,sending:sendMessage.pending?.has(state.history)}),
4060
+ settings:name=>{showView('view-settings');showSettingsPage(name)},plugins:()=>showView('view-plugins'),
4061
+ feedback:openFeedbackModal,
4062
+ browse:()=>{closeNewSessionModal();showView('view-files')},
4063
+ register:async()=>{
4064
+ const connection=captureConnection(),path=state.fs.path;if(!path)return toast('请先选择主机目录','err')
4065
+ try{const value=await rpc('workspace.create',{path});if(!connection.valid()||!value?.workspace)return
4066
+ state.workspaces=[...state.workspaces.filter(w=>w.workspaceId!==value.workspace.workspaceId),value.workspace]
4067
+ closeWorkspaceModal();renderNewSessionWorkspace(value.workspace.workspaceId);await createSessionInWorkspace()
4068
+ }catch(error){if(connection.valid())toast(error.message,'err')}
4069
+ },
4070
+ command:runSlashCommand,send:sendMessage,refresh:refreshSessions,retry:()=>{startOverviewDetection(true);void refreshSessions()},
4071
+ operations:()=>{const connection=captureConnection();return {url:apiUrl,headers:{authorization:'Bearer '+connection.token},valid:connection.valid}},
4072
+ relay:()=>{const connection=captureConnection();return {url:()=>apiUrl('/admin/api/relay'),headers:{authorization:'Bearer '+connection.token},valid:connection.valid,connected:!!connection.token}},
4073
+ discover:()=>{if(confirm('登记当前绑定目录下的子目录为工作区?'))void refreshWorkbench({discover:true})},
4074
+ 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)},
4075
+ admin:()=>window.open(new URL(apiUrl('/admin/'),location.href).href,'_blank','noopener,noreferrer'),
4076
+ clear:async kind=>{
4077
+ const text=kind==='history'?'清除本机历史缓存?主机记录保留。':kind==='connection'?'移除当前地址和保存的凭证?其他连接条目保留。':'清除本机全部 Remote 配置与凭证?主机数据保留。'
4078
+ if(!confirm(text))return
4079
+ clearTimeout(scheduleHistoryCacheSave._t)
4080
+ if(kind==='connection'){
4081
+ const current=currentServerEntry();if(current)state.servers=state.servers.filter(s=>s.id!==current.id)
4082
+ state.groupActive[state.activeGroup]='';state.token='';state.server='';LS.del('token');LS.del('server');saveServers()
4083
+ closeStream('mux');closeStream('host');stopPolling();renderServers();showView('view-settings');showSettingsPage('servers');return
4084
+ }
4085
+ await window.DshHistory.cacheClear()
4086
+ if(kind==='all'){window.DshWorkflow.clearStorage();location.reload()}else toast('历史缓存已清除','ok')
4087
+ },
4088
+ 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()},
4089
+ })
4090
+ }