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.
package/public/app.js CHANGED
@@ -103,7 +103,7 @@ const state = {
103
103
  wbArchived: [],
104
104
  wbOpen: false,
105
105
  wbOpenProjects: {},
106
- subagentExpandedSession: ''
106
+ subagentSessions: {}
107
107
  }
108
108
 
109
109
  // Increment on every identity transition, including A -> B -> A and token edits.
@@ -120,7 +120,7 @@ for (const key of ['server', 'token']) {
120
120
  state.sessions = []; state.byId.clear(); state.pendingProjections.clear()
121
121
  state.hostInfo = null
122
122
  if(typeof closeStream==='function'&&typeof streamMeta!=='undefined'){closeStream('mux');closeStream('host')}
123
- state.current = null; state.history = emptyHistory()
123
+ state.current = null; state.history = emptyHistory(); state.subagentSessions = {}; window.DshSubagents?.reset()
124
124
  state.models = { loaded: false, loading: false, groups: [], current: null, failures: [] }
125
125
  state.modelSettings = { status: 'idle', error: '', writable: false, hasDocument: false, providers: [], namespaces: [], credentials: {} }; state.modelEditor = null
126
126
  state.goalEdit = null; state.goalEditContext = null
@@ -513,14 +513,18 @@ async function rpc(method, payload = {}, timeoutMs = 45000) {
513
513
  if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
514
514
  opts.signal = AbortSignal.timeout(timeoutMs)
515
515
  }
516
- const res = await fetch(apiUrl('/api/' + method), opts)
516
+ const operation = window.DshOperations?.supports(method) && activeGatewayCapability('operations') === true
517
+ const connection = operation ? captureConnection() : null
518
+ const receipt = operation ? await window.DshOperations.execute({ method, payload, url: apiUrl, headers: opts.headers, valid: () => connection.valid() }) : null
519
+ const res = receipt ? { status: 200, ok: true, json: async () => receipt } : await fetch(apiUrl('/api/' + method), opts)
517
520
  if (res.status === 401) throw new Error('AUTH')
518
521
  if (!res.ok) throw new Error('HTTP ' + res.status)
519
522
  const full = await res.json()
520
523
  if (!full?.result) throw new Error(t('err.badResponse'))
521
524
  if (!full.result.ok) {
522
525
  const err = full.result.error || {}
523
- const error = new Error(err.message || t('err.dshError'))
526
+ const error = new Error(err.code === 'session/migration-required' ? t('session.migrationRequired') : err.message || t('err.dshError'))
527
+ error.code = err.code
524
528
  error.rpcRejected = true
525
529
  throw error
526
530
  }
@@ -851,6 +855,7 @@ function renderGroupSelect() {
851
855
  const menu = $('group-select-menu')
852
856
  if (!label || !menu) return
853
857
  label.textContent = state.activeGroup
858
+ $('group-select-btn')?.setAttribute('aria-label', t('groups.currentLabel', { group: state.activeGroup }))
854
859
  menu.innerHTML = state.groups.map(g =>
855
860
  `<button type="button" class="group-option ${g === state.activeGroup ? 'current' : ''}" data-group-option="${esc(g)}">${esc(g)}${g === state.activeGroup ? ' ✓' : ''}</button>`).join('')
856
861
  menu.querySelectorAll('[data-group-option]').forEach(b =>
@@ -952,7 +957,7 @@ function renderServers() {
952
957
  const activeManual = state.groupActive[g] || ''
953
958
  return `<div class="srv-group" data-group="${esc(g)}">
954
959
  <div class="srv-group-head">
955
- <button class="srv-group-name" data-group-name="${esc(g)}">${g === state.activeGroup ? '▾' : '▸'} ${esc(g)} <span class="srv-group-count">${list.length}</span></button>
960
+ <button class="srv-group-name" data-group-name="${esc(g)}"><span class="srv-group-label">${g === state.activeGroup ? '▾' : '▸'} ${esc(g)}</span><span class="srv-group-count">${list.length}</span></button>
956
961
  <button class="srv-group-speed mini-btn" data-speed-group="${esc(g)}" title="${t('groups.speedTest')}">⚡</button>
957
962
  <label class="switch small" title="${t('groups.autoSelect')}">
958
963
  <input type="checkbox" data-auto-group="${esc(g)}" ${auto ? 'checked' : ''}>
@@ -963,14 +968,17 @@ function renderServers() {
963
968
  <div class="srv-group-body ${g === state.activeGroup ? '' : 'hidden'}">
964
969
  ${list.map(s => {
965
970
  const ms = state.serverLatency[serverKey(s)]
966
- let badge = `<span class="server-badge">${t('servers.untested')}</span>`
967
971
  const active = s.url === state.server && serverToken(s) === state.token
968
- if (Number.isFinite(ms)) badge = `<span class="server-badge ${active ? 'good' : ''}">${ms}ms${active ? t('servers.current') : ''}</span>`
972
+ // 只显示一条最有用的状态,避免地址被状态文案挤成竖排。
973
+ let badge = `<span class="server-badge">${t('servers.untested')}</span>`
974
+ if (!s.token) badge = `<span class="server-badge bad">${t('servers.tokenMissing')}</span>`
975
+ else if (Number.isFinite(ms)) badge = `<span class="server-badge ${active ? 'good' : ''}">${ms}ms${active ? t('servers.current') : ''}</span>`
969
976
  else if (ms !== undefined) badge = '<span class="server-badge bad">' + t('servers.unreachable') + '</span>'
977
+ else if (active) badge = `<span class="server-badge good">${t('servers.currentOnly')}</span>`
970
978
  const activeInGroup = auto ? active : s.id === activeManual
971
979
  return `<div class="server-row ${activeInGroup ? 'active' : ''}" data-use-server="${esc(s.id)}">
972
- <span class="server-main"><span class="server-note">${esc(serverTitle(s))}</span>${s.note ? `<span class="server-url">${esc(s.url)}</span>` : ''}<span class="server-token-badge">${s.token ? t('servers.tokenSet') : t('servers.tokenMissing')}</span></span>${badge}
973
- <button class="server-edit" data-edit-server="${esc(s.id)}" title="${t('servers.edit')}">✎</button>
980
+ <span class="server-main"><span class="server-note" title="${esc(serverTitle(s))}">${esc(serverTitle(s))}</span>${s.note ? `<span class="server-url">${esc(s.url)}</span>` : ''}</span>${badge}
981
+ <button class="server-edit" data-edit-server="${esc(s.id)}" title="${t('servers.edit')}" aria-label="${t('servers.edit')}">✎</button>
974
982
  <button class="server-del" data-del-server="${esc(s.id)}" aria-label="${t('servers.delete')}">✕</button>
975
983
  </div>`
976
984
  }).join('') || '<div class="server-empty">' + t('groups.noServer') + '</div>'}
@@ -1028,7 +1036,7 @@ function renderServers() {
1028
1036
  const curGroup = cur ? cur.group : state.activeGroup
1029
1037
  const curMs = cur ? state.serverLatency[serverKey(cur)] : undefined
1030
1038
  $('server-desc').textContent = state.server
1031
- ? t('servers.currentDescGroup', { group: curGroup, url: curNote, ms: Number.isFinite(curMs) ? curMs + 'ms' : '—' })
1039
+ ? t('servers.currentDescGroup', { group: curGroup, url: curNote }) + (Number.isFinite(curMs) ? ' · ' + curMs + 'ms' : '')
1032
1040
  : (CAP?.isNativePlatform?.() ? t('servers.notSet') : t('servers.defaultDesc'))
1033
1041
  updateConn()
1034
1042
  }
@@ -1402,7 +1410,7 @@ async function pollKind(kind, cancellation) {
1402
1410
  const timeout = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(window.DshNetwork?.profile().pollTimeout || 30000) : undefined
1403
1411
  const signal = cancellation && timeout && typeof AbortSignal.any === 'function' ? AbortSignal.any([cancellation, timeout]) : timeout || cancellation
1404
1412
  const headers = { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }
1405
- 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 })
1413
+ res = await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000&epoch=${encodeURIComponent(cursors[kind + "Epoch"] || "")}`), { ...(signal ? { signal } : {}), headers })
1406
1414
  } catch { return }
1407
1415
  if (!valid()) return
1408
1416
  if (res.status === 401) { authFailure(); return }
@@ -1413,7 +1421,7 @@ async function pollKind(kind, cancellation) {
1413
1421
  if (!data || !Array.isArray(data.events)) return
1414
1422
  // 网关重启或客户端离线过久后,游标可能落后于内存环形缓冲;
1415
1423
  // 从当前缓冲重新接收,并刷新权威会话列表,避免静默漏事件。
1416
- const reset = data.truncated === true || (typeof data.latestSeq === 'number' && data.latestSeq < since)
1424
+ 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)
1417
1425
  if (reset) {
1418
1426
  state.pollSeq[kind] = 0
1419
1427
  if (kind === 'mux') {
@@ -1424,6 +1432,8 @@ async function pollKind(kind, cancellation) {
1424
1432
  scheduleRefresh()
1425
1433
  if (state.current) void resyncCurrentSession()
1426
1434
  }
1435
+ if (data.epoch) cursors[kind + 'Epoch'] = data.epoch
1436
+ for (const frame of data.baseline || []) { if (kind === 'mux') onMuxFrame(frame); else onHostFrame(frame) }
1427
1437
  for (const item of data.events) {
1428
1438
  if (item.seq > (state.pollSeq[kind] || 0)) {
1429
1439
  state.pollSeq[kind] = item.seq
@@ -1585,6 +1595,7 @@ function setCompactionStatus(sessionId, next) {
1585
1595
  }
1586
1596
  if (previous?.active && previous.notify && next?.notify !== false && ['complete', 'failed'].includes(next?.phase)) {
1587
1597
  const command = previous.command || 'compact'
1598
+ if (command === 'export' && next?.phase === 'complete' && state.current === sessionId && typeof downloadSessionExport === 'function') void downloadSessionExport(sessionId)
1588
1599
  if (next?.phase === 'failed') toast(command === 'compact'
1589
1600
  ? t('session.compactFailed', { msg: next.message || t('send.failed') })
1590
1601
  : t('session.commandFailed', { command, msg: next.message || t('send.failed') }), 'err')
@@ -1721,6 +1732,12 @@ async function refreshSessions() {
1721
1732
  }
1722
1733
  state.sessions = v.items || []
1723
1734
  state.byId = new Map(state.sessions.map(s => [s.sessionId, s]))
1735
+ for (const [id, child] of Object.entries(state.subagentSessions || {})) {
1736
+ const listed = state.byId.get(id)
1737
+ const merged = listed ? { ...child, ...listed, parentSessionId: child.parentSessionId, subagentMode: child.subagentMode, origin: 'subagent' } : child
1738
+ state.byId.set(id, merged)
1739
+ state.subagentSessions[id] = merged
1740
+ }
1724
1741
  applyPendingProjections()
1725
1742
  cacheWrite(CACHE.sessions, state.sessions.slice(0, 80))
1726
1743
  renderSessions()
@@ -1779,9 +1796,15 @@ function hydrateSessionProjections(sessionId, projections) {
1779
1796
  if (!s || !projections || typeof projections !== 'object') return
1780
1797
  const incomingSeq = Number(projections.asOfSeq) || 0
1781
1798
  const current = s.projections || { asOfSeq: 0, values: {} }
1799
+ if (projections.kind === 'cached' && current.kind === 'sequenced') return
1800
+ if (current.kind === 'cached' || projections.kind === 'cached') {
1801
+ s.projections = { ...projections, asOfSeq: incomingSeq, kind: projections.kind || 'sequenced', values: { ...(current.values || {}), ...(projections.values || {}) } }
1802
+ return
1803
+ }
1782
1804
  const currentSeq = Number(current.asOfSeq) || 0
1783
1805
  if (incomingSeq < currentSeq) return
1784
1806
  s.projections = {
1807
+ kind: projections.kind || current.kind || 'sequenced',
1785
1808
  asOfSeq: Math.max(currentSeq, incomingSeq),
1786
1809
  values: { ...(current.values || {}), ...(projections.values || {}) }
1787
1810
  }
@@ -1802,6 +1825,7 @@ function applyProjection(sessionId, key, value, seq) {
1802
1825
  state.pendingProjections.set(sessionId, pending)
1803
1826
  return
1804
1827
  }
1828
+ if (s.projections?.kind === 'cached') s.projections = { kind: 'sequenced', asOfSeq: 0, values: { ...(s.projections.values || {}) } }
1805
1829
  const currentSeq = Number(s.projections?.asOfSeq) || 0
1806
1830
  if (seq && seq < currentSeq) return
1807
1831
  s.projections = s.projections || { asOfSeq: 0, values: {} }
@@ -2040,34 +2064,41 @@ function renderWorkspaceNavigation() {
2040
2064
  if ($('modal-new-session') && !$('modal-new-session').classList.contains('hidden')) renderNewSessionWorkspace()
2041
2065
  return items
2042
2066
  }
2043
- async function refreshWorkbench() {
2067
+ async function refreshWorkbench({ discover = false } = {}) {
2044
2068
  const connection = captureConnection(), request = ++workbenchRequest
2045
2069
  const valid = () => connection.valid() && request === workbenchRequest
2070
+ const sharedRead = (name, read) => window.DshNetwork?.shareRead ? window.DshNetwork.shareRead(JSON.stringify([connection.server, connection.token, name]), read) : read()
2046
2071
  if (!state.token) return
2072
+ const workspaceRead = sharedRead('workspace.list', () => connection.valid() ? rpc('workspace.list', {}) : null).catch(() => null)
2047
2073
  try {
2048
- const res = await fetch(apiUrl('/workbench'), {
2049
- headers: { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }
2074
+ const target = apiUrl('/workbench')
2075
+ const res = await sharedRead('workbench', async () => {
2076
+ if(!connection.valid())return {ok:false,value:null}
2077
+ const response = await fetch(target, {
2078
+ headers: { authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }, signal: AbortSignal.timeout(10000)
2079
+ })
2080
+ return { ok: response.ok, value: await response.json().catch(() => null) }
2050
2081
  })
2051
2082
  if (!valid()) return
2052
2083
  if (res.ok) {
2053
- const value = await res.json().catch(() => null)
2084
+ const value = res.value
2054
2085
  if (!valid()) return
2055
2086
  if (value && typeof value.bound === 'boolean') state.wb = value
2056
2087
  }
2057
2088
  } catch {}
2058
2089
  if (!valid()) return
2059
2090
  try {
2060
- const value = await rpc('workspace.list', {})
2091
+ const value = await workspaceRead
2061
2092
  if (!valid()) return
2062
- state.wbProjects = Array.isArray(value?.items) ? value.items : []
2063
- state.wbArchived = Array.isArray(value?.archivedSessionIds) ? value.archivedSessionIds : []
2093
+ if (value) state.wbProjects = Array.isArray(value.items) ? value.items : []
2094
+ if (value) state.wbArchived = Array.isArray(value.archivedSessionIds) ? value.archivedSessionIds : []
2064
2095
  } catch {
2065
2096
  if (!valid()) return
2066
2097
  state.wbProjects = []
2067
2098
  state.wbArchived = []
2068
2099
  }
2069
2100
  // 以磁盘实际目录为准同步工作台项目:删除目录后不再残留,新增子目录自动收纳。
2070
- if (state.wb?.bound && state.wb.path) {
2101
+ if (discover && state.wb?.bound && state.wb.path) {
2071
2102
  try {
2072
2103
  const listRes = await fetch(fsApiUrl('/list', { path: state.wb.path }), { headers: fsHeaders() })
2073
2104
  if (!valid()) return
@@ -2131,7 +2162,7 @@ function renderWorkbench() {
2131
2162
  const open = !!state.wbOpenProjects[id]
2132
2163
  const sessions = orderedWorkspaceSessions(id, (w.sessionIds || []).map(sid => state.byId.get(sid)).filter(isVisibleSession).filter(s => !archivedSet.has(s.sessionId)))
2133
2164
  const body = open ? `<div class="wb-sessions">${sessions.length ? sessions.map(s => `
2134
- <div class="session-swipe" data-session-swipe data-id="${esc(s.sessionId)}">
2165
+ <div class="session-swipe" data-session-swipe data-id="${esc(s.sessionId)}" role="button" tabindex="0" aria-label="${esc(sessionLabelOf(s))}">
2135
2166
  <button class="wb-session" type="button" data-wb-session="${esc(s.sessionId)}" data-motion-key="${esc(s.sessionId)}">
2136
2167
  <span class="wb-session-drag-handle" data-reorder-handle aria-hidden="true">⠿</span>
2137
2168
  <span class="wb-session-title">${esc(sessionLabelOf(s))}</span>
@@ -2236,7 +2267,7 @@ function renderSessions() {
2236
2267
  const badge = goal ? `<span class="sc-badge ${goal.phase === 'active' ? 'goal-active' : ''}">${esc(t('sessions.goalBadge', { phase: goal.phase || '?' }))}</span>` : ''
2237
2268
  const queueBadge = queueN ? `<span class="sc-badge">${esc(t('sessions.queueBadge', { n: queueN }))}</span>` : ''
2238
2269
  const archiveButton = archivedSet.has(s.sessionId) ? '' : `<button type="button" class="sc-archive-btn" data-archive-session="${esc(s.sessionId)}">${esc(t('session.archive'))}</button>`
2239
- return `<div class="session-swipe" data-session-swipe data-id="${esc(s.sessionId)}">
2270
+ return `<div class="session-swipe" data-session-swipe data-id="${esc(s.sessionId)}" role="button" tabindex="0" aria-label="${esc(sessionLabelOf(s))}">
2240
2271
  <div class="session-card ${state.current === s.sessionId ? 'current' : ''}">
2241
2272
  <div class="sc-title">${esc(title)}</div>
2242
2273
  <div class="sc-meta">
@@ -2303,6 +2334,7 @@ const emptySessionCleanup = new Set()
2303
2334
  async function archiveEmptySessionOnLeave(sessionId, leaving = false) {
2304
2335
  const base = state.server, connection=captureConnection()
2305
2336
  const protectedSession = () => !connection.valid() || state.server !== base || (!leaving && state.current !== sessionId)
2337
+ || !!state.byId.get(sessionId)?.parentSessionId || state.byId.get(sessionId)?.origin === 'subagent'
2306
2338
  || !state.byId.has(sessionId) || state.byId.get(sessionId)?.running
2307
2339
  || state.sessionActivity?.has(sessionId) || state.pendingPrompts?.has(sessionId)
2308
2340
  || (state.queues[sessionId] || []).length > 0
@@ -2334,6 +2366,7 @@ async function openSession(id) {
2334
2366
  $('btn-archive-session').classList.toggle('hidden', (state.wbArchived || []).includes(id))
2335
2367
  $('session-cards').innerHTML = ''
2336
2368
  renderSessionTitle(); renderSessionSub(); updateCancelBtn(); updateSessionStatus()
2369
+ renderSessionCards()
2337
2370
  $('history').innerHTML = '<div class="empty">' + t('history.loading') + '</div>'
2338
2371
  renderQueue()
2339
2372
  renderSessionPending()
@@ -2368,6 +2401,11 @@ async function closeSession() {
2368
2401
  if (closeSession.pending) return closeSession.pending
2369
2402
  const sessionId = state.current
2370
2403
  if (!sessionId) return
2404
+ const parentId = state.byId.get(sessionId)?.parentSessionId
2405
+ if (parentId && parentId !== sessionId) {
2406
+ setComposerFullscreen(false);clearComposerImages();hideComposerMenu()
2407
+ return openSession(parentId)
2408
+ }
2371
2409
  const task = (async () => {
2372
2410
  const discard = await shouldDiscardEmptySession(sessionId) && await archiveEmptySessionOnLeave(sessionId)
2373
2411
  if (state.current !== sessionId) return
@@ -2399,13 +2437,24 @@ function bindNativeBack() {
2399
2437
  CAP.Plugins?.App?.addListener?.('backButton', () => {
2400
2438
  if ($('composer-wrap')?.classList.contains('fs')) { setComposerFullscreen(false); return }
2401
2439
  if (customSelectCurrent) { closeCustomSelect(); return }
2440
+ if (groupDrawerOpen()) { closeGroupDrawer(); return }
2441
+ if (typeof window !== 'undefined' && window.DshImagePreview?.isOpen?.()) { window.DshImagePreview.close(); return }
2442
+ const dialog = document.querySelector('dialog[open]')
2443
+ if (dialog) { dialog.close(); return }
2402
2444
  const openModal = [...document.querySelectorAll('.modal')].find(m => !m.classList.contains('hidden'))
2403
2445
  if (openModal) { if (openModal.id === 'modal-notes') closeNotesModal(); else if (openModal.id === 'modal-archive') closeArchiveConfirm(); else if (openModal.id === 'modal-rename') closeRenameSession(); else if (openModal.id === 'modal-app-version-warning') closeAppVersionWarning(false); else if (openModal.id === 'modal-scan-live') closeLiveScan(''); else openModal.classList.add('hidden'); return } // 先关弹窗
2446
+ if (!$('view-settings').classList.contains('hidden')) {
2447
+ if ($('settings-home').classList.contains('hidden')) showSettingsHome()
2448
+ else showView('view-home')
2449
+ return
2450
+ }
2451
+ if (!$('view-plugins').classList.contains('hidden')) { showView('view-settings'); return }
2404
2452
  if (document.body.classList.contains('in-session')) { void closeSession(); return } // 会话页 → 回主页
2405
2453
  if (!$('view-files').classList.contains('hidden')) { // 文件页 → 上级目录 → 主页
2406
2454
  if (state.fs.path && state.fs.initial && state.fs.path !== state.fs.initial) { fsUp(); return }
2407
2455
  showView('view-home'); return
2408
2456
  }
2457
+ if ($('view-home').classList.contains('hidden')) { showView('view-home'); return }
2409
2458
  try { CAP.Plugins?.App?.exitApp?.() } catch {} // 主页再返回 → 退出(与系统一致)
2410
2459
  })
2411
2460
  } catch {}
@@ -2530,7 +2579,9 @@ function applyReasoningStreamEvent(event) {
2530
2579
  }
2531
2580
 
2532
2581
  let reasoningRenderTimer = null
2582
+ function weakStreamTrim() { return !!window.DshNetwork?.streamTrimmed?.() }
2533
2583
  function scheduleReasoningRender() {
2584
+ if (weakStreamTrim()) return
2534
2585
  if (reasoningRenderTimer) return
2535
2586
  reasoningRenderTimer = setTimeout(() => {
2536
2587
  reasoningRenderTimer = null
@@ -2540,10 +2591,11 @@ function scheduleReasoningRender() {
2540
2591
  }
2541
2592
 
2542
2593
  function partialReasoningHtml() {
2594
+ if (weakStreamTrim()) return ''
2543
2595
  return [...state.history.partialReasoning.values()]
2544
2596
  .filter(item => item.text)
2545
2597
  .sort((a, b) => (a.turn ?? 0) - (b.turn ?? 0) || (a.step ?? 0) - (b.step ?? 0) || (a.index ?? 0) - (b.index ?? 0))
2546
- .map(item => `<div class="msg assistant reasoning-live"><div class="role">${esc(t('role.dsh'))}</div><details class="tool" open><summary>${esc(t('block.thinkingLive'))}</summary><div class="tool-text">${esc(truncate(item.text, 12000))}</div></details></div>`)
2598
+ .map(item => window.DshActivity ? window.DshActivity.reasoning({text:item.text,live:true,key:window.DshActivity.reasoningKey(item,item.index,'live-reasoning')}) : `<div class="msg assistant reasoning-live"><div class="role">${esc(t('role.dsh'))}</div><details class="tool" open><summary>${esc(t('block.thinkingLive'))}</summary><div class="tool-text">${esc(truncate(item.text, 12000))}</div></details></div>`)
2547
2599
  .join('')
2548
2600
  }
2549
2601
 
@@ -2564,7 +2616,7 @@ function getConversationView() {
2564
2616
  if(!conversationView)conversationView=new window.DshHistory.HistoryView($('history'),{
2565
2617
  html:entry=>eventHtml(entry, {toolNames:state.history.toolNames}),
2566
2618
  older:()=>loadHistory(false),olderLabel:()=>t('history.earlier'),loadingLabel:()=>t('history.loadingEarlier'),live:partialReasoningHtml,
2567
- changed:view=>{state.history.renderStart=view.start;state.history.renderEnd=view.end;$('btn-history-latest')?.classList.toggle('hidden',!view.reading&&view.end>=view.entries.length&&!state.history.tailEvicted);const latest=$('btn-history-latest');if(latest)latest.textContent=t('history.latest')+(view.unread?' ('+view.unread+')':view.hasPending?' · '+(I18N.lang==='en'?'New content':'有新内容'):'');updateRail(view.domChanged)},
2619
+ 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('history.latest')+(view.unread?' ('+view.unread+')':view.hasPending?' · '+(I18N.lang==='en'?'New content':'有新内容'):'')}updateRail(view.domChanged)},
2568
2620
  scrolled:()=>{updateRail()}
2569
2621
  })
2570
2622
  return conversationView
@@ -2609,6 +2661,8 @@ async function loadHistory(reset = true) {
2609
2661
  if(reset){if(hadContent)historySource('syncing');else setSessionRecovery('loading')}
2610
2662
  const network=window.DshNetwork?.profile() || {historyPageSize:60,readTimeout:45000}
2611
2663
  const payload={sessionId:id,maxMessages:network.historyPageSize}
2664
+ const child=state.subagentSessions?.[id] || state.byId.get(id)
2665
+ if(child?.origin==='subagent' && child.parentSessionId) Object.assign(payload,{parentSessionId:child.parentSessionId,subagentMode:child.subagentMode || 'unknown'})
2612
2666
  if(!reset&&Number.isFinite(history.minSeq))payload.beforeSeq=history.minSeq
2613
2667
  getConversationView().more.disabled=true
2614
2668
  getConversationView().more.textContent=getConversationView().options.loadingLabel()
@@ -2668,6 +2722,19 @@ function insertLiveEvent(event) {
2668
2722
 
2669
2723
  function isToolEvent(type) { return type === 'tool/call' || type === 'tool/result' }
2670
2724
 
2725
+ /** One collapsed row for a turn's tools and reasoning, matching the desktop conversation rhythm. */
2726
+ function activityGroupHtml(group, ctx) {
2727
+ const items = group.items || []
2728
+ if (!items.length) return ''
2729
+ const tools = items.filter(item => item.kind === 'tool').map(item => item.entry)
2730
+ const running = !!group.running
2731
+ const failed = tools.some(entry => entry.view?.toolActivity?.error || entry.event?.data?.error)
2732
+ const body = items.map(item => item.kind === 'reasoning'
2733
+ ? window.DshActivity.reasoning({ text: item.text, key: item.key })
2734
+ : eventHtml(item.entry, ctx)).join('')
2735
+ 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('activity.group', { n: items.length }))}</span>${running ? `<span class="activity-group-live"><i aria-hidden="true"></i>${esc(t('activity.groupRunning'))}</span>` : ''}<span class="activity-chevron" aria-hidden="true"></span></summary><div class="activity-group-body">${body}</div></details>`
2736
+ }
2737
+
2671
2738
  function filteredEntries() {
2672
2739
  const showTools = LS.get('showTools', '1') !== '0'
2673
2740
  const f = state.history.visible.filter(e => showTools || !isToolEvent(e.event?.type))
@@ -2680,8 +2747,23 @@ function renderHistory(reset=false,mode='auto') {
2680
2747
  for(const entry of state.history.visible){const d=entry.event?.data;if(entry.event?.type==='tool/call'&&d?.callId&&d.name)toolNames.set(d.callId,d.name)}
2681
2748
  state.history.toolNames=toolNames
2682
2749
  $('history-hint').textContent=t('history.count',{n:state.history.visible.length})
2683
- getConversationView().set(filtered,{reset,follow:mode==='bottom',live:partialReasoningHtml(),hasMore:state.history.hasMore,loading:state.history.loading,emptyLabel:t('history.empty')})
2684
- }
2750
+ let prepared=window.DshActivity?.prepare(filtered)||filtered
2751
+ // 弱网精简:尚未返回的调用在完成前不展示,只留已完成的消息与工具结果。
2752
+ if(weakStreamTrim())prepared=prepared.filter(entry=>entry.event?.type!=='tool/call'||entry.view?.toolActivity)
2753
+ // DSH 0.2.1 also embeds tool blocks in messages; the separated events own the grouped rows.
2754
+ state.history.suppressBlockTools = state.history.visible.some(entry => entry.event?.type === 'tool/call')
2755
+ if(window.DshActivity?.group)prepared=window.DshActivity.group(prepared)
2756
+ // Running is a property of the session's current turn, not of an unpaired call:
2757
+ // a finished turn may keep an unmatched call after an interrupt, and the model may be
2758
+ // thinking between tools while the last group is still the active one.
2759
+ const sessionRunning = !!state.byId.get(state.current)?.running
2760
+ const groups = prepared.filter(entry => entry.view?.activityGroup)
2761
+ const activeGroup = groups.at(-1)
2762
+ if (activeGroup) activeGroup.view.activityGroup.running = sessionRunning
2763
+ getConversationView().set(prepared,{reset,follow:mode==='bottom',live:partialReasoningHtml(),hasMore:state.history.hasMore,loading:state.history.loading,emptyLabel:t('history.empty')})
2764
+ window.DshImagePreview?.hydrate?.($('history'))
2765
+ }
2766
+ window.applyStreamPreference=()=>{if(state.current)renderHistory(false,'auto')}
2685
2767
 
2686
2768
  /* 右侧导航条: 用户发言节点 + 拖动快速定位 */
2687
2769
  let historyRailLayout=null
@@ -2776,7 +2858,9 @@ function eventHtml(entry, ctx = {}) {
2776
2858
  const ev = entry.event || {}
2777
2859
  const data = ev.data || {}
2778
2860
  const type = ev.type || 'event'
2861
+ if (entry.view?.activityGroup) return activityGroupHtml(entry.view.activityGroup, ctx)
2779
2862
  if (!shouldShowEvent(type, ev)) return ''
2863
+ if (window.DshActivity && isToolEvent(type)) return window.DshActivity.toolEvent(entry)
2780
2864
  let inner = ''
2781
2865
 
2782
2866
  if (type === 'user/message' || type === 'assistant/message') {
@@ -2789,7 +2873,11 @@ function eventHtml(entry, ctx = {}) {
2789
2873
  } else if (type === 'user/message' && !isHumanUserMessage(ev)) {
2790
2874
  return ''
2791
2875
  } else {
2792
- inner = `<div class="msg ${esc(role)}" data-seq="${seq}"><div class="role">${esc(role === 'user' ? t('role.me') : t('role.dsh'))}</div>${blocks.map(blockHtml).join('')}</div>`
2876
+ const body = blocks.map((block,index)=>blockHtml(block,index,{...data,seq,suppressBlockTools:state.history.suppressBlockTools})).join('')
2877
+ // Inline tool blocks duplicate the separated tool events; when those events exist the
2878
+ // calls live in the activity group, so an assistant message with nothing else disappears.
2879
+ if (!body) return ''
2880
+ inner = `<div class="msg ${esc(role)}" data-seq="${seq}"><div class="role">${esc(role === 'user' ? t('role.me') : t('role.dsh'))}</div>${body}</div>`
2793
2881
  }
2794
2882
  } else if (type === 'tool/call') {
2795
2883
  const name = data.name || data.toolName || t('tool.default')
@@ -2813,13 +2901,21 @@ function eventHtml(entry, ctx = {}) {
2813
2901
  return inner
2814
2902
  }
2815
2903
 
2816
- function blockHtml(b) {
2904
+ function blockHtml(b,index=0,context={}) {
2817
2905
  if (!b || typeof b !== 'object') return `<p>${esc(String(b))}</p>`
2818
- if ((b.type === 'tool-call' || b.type === 'tool-result') && LS.get('showTools', '1') === '0') return ''
2906
+ if ((b.type === 'tool-call' || b.type === 'tool-result') && (context.suppressBlockTools || LS.get('showTools', '1') === '0')) return ''
2907
+ if (typeof window !== 'undefined' && window.DshActivity) {
2908
+ const key='block:'+context.seq+':'+index
2909
+ if (b.type==='thinking'||b.type==='reasoning') return window.DshActivity.reasoning({text:b.text??b.content??'',key:window.DshActivity.reasoningKey(context,index,key)})
2910
+ 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)})})
2911
+ }
2819
2912
  switch (b.type) {
2820
- case 'text': return `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '', { fileLinks: true }) : esc(b.text ?? '')}</div>`
2913
+ case 'text': return `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '', { fileLinks: true, imageLabel: t('block.image') }) : esc(b.text ?? '')}</div>`
2821
2914
  case 'file': if (typeof window !== 'undefined' && window.DshChatFiles) return window.DshChatFiles.render(b); return `<div class="tool">📎 ${esc(b.attachment?.name || b.name || 'file')} <small>${esc(b.attachment?.bytes ?? b.bytes ?? '')} bytes</small></div>`
2822
- case 'image': return `<img alt="${t('block.image')}" src="data:${esc(b.mediaType || 'image/png')};base64,${esc(b.data || '')}">`
2915
+ case 'image': {
2916
+ const alt = b.name || b.filename || t('block.image')
2917
+ 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>`
2918
+ }
2823
2919
  case 'thinking':
2824
2920
  case 'reasoning':
2825
2921
  return `<details class="tool"><summary>${t('block.thinking')}</summary><div class="tool-text">${esc(truncate(String(b.text ?? b.content ?? safeJson(b)), 6000))}</div></details>`
@@ -2859,11 +2955,29 @@ function statsHtml(s) {
2859
2955
  }
2860
2956
 
2861
2957
  let sessionSubagentsJob = null
2958
+ function rememberSubagent(entry, parentId) {
2959
+ const childId = entry.id
2960
+ const child = state.byId.get(childId) || { sessionId: childId, cwd: state.byId.get(parentId)?.cwd || '' }
2961
+ Object.assign(child, { parentSessionId: parentId, origin: 'subagent', subagentMode: entry.mode || child.subagentMode || 'unknown' })
2962
+ if (entry.label && !child.projections?.values?.title) {
2963
+ child.projections ||= { values: {} }
2964
+ child.projections.values ||= {}
2965
+ child.projections.values.title = entry.label
2966
+ }
2967
+ state.byId.set(childId, child)
2968
+ state.subagentSessions ||= {}
2969
+ state.subagentSessions[childId] = child
2970
+ }
2971
+ async function openSubagentSession(childId, parentId, entry = {}, rootId = parentId) {
2972
+ if (!childId || childId === parentId || state.current !== rootId) return
2973
+ rememberSubagent({ ...entry, id: childId }, parentId)
2974
+ await openSession(childId)
2975
+ }
2862
2976
  async function loadSessionSubagents(sessionId) {
2863
2977
  if (sessionSubagentsJob?.sessionId === sessionId && sessionSubagentsJob.connection.valid()) return sessionSubagentsJob.promise
2864
2978
  const connection = captureConnection(), job = { sessionId, connection }
2865
2979
  job.promise = (async () => {
2866
- const value = await safeRpc('subagent.list', { parentSessionId: sessionId }, '')
2980
+ const value = await rpc('subagent.list', { parentSessionId: sessionId })
2867
2981
  return connection.valid() ? value : null
2868
2982
  })()
2869
2983
  sessionSubagentsJob = job
@@ -2924,30 +3038,15 @@ async function renderSessionCards() {
2924
3038
  }))
2925
3039
 
2926
3040
  // 子代理
2927
- const sub = await loadSessionSubagents(sessionId)
2928
3041
  if (!connection.valid() || renderGeneration !== sessionCardsRenderGeneration || state.current !== sessionId) return
2929
- if (sub?.entries?.length) {
2930
- const expanded = state.subagentExpandedSession === sessionId
2931
- const toggleLabel = expanded ? t('subagent.collapse') : t('subagent.expand')
2932
- const rows = sub.entries.map(e => {
2933
- if (e.kind === 'diagnostic') return `<div class="card-row"><span class="k">${t('subagent.diagnostic')}</span><span class="v">${esc(e.reason)}</span></div>`
2934
- const label = e.label || short(e.id)
2935
- const running = e.activity === 'running'
2936
- return `<div class="card-row"><span class="k">${running ? '▶ ' : ''}${esc(label)}</span><span class="v">${esc(e.mode)} ${running ? t('subagent.running') : ''}${e.mode === 'continuable' && running ? ` <button class="mini-btn" data-sub-interrupt="${esc(e.id)}">${t('subagent.interrupt')}</button>` : ''}</span></div>`
2937
- }).join('')
2938
- const subagentClosedIcon = 'M7 10l5 5 5-5'
2939
- const subagentOpenIcon = 'M7 14l5-5 5 5'
2940
- const subagentIcon = expanded ? subagentOpenIcon : subagentClosedIcon
2941
- box.insertAdjacentHTML('beforeend', `<div class="card subagent-card"><button type="button" class="subagent-toggle" data-subagent-toggle aria-expanded="${expanded}" aria-label="${esc(toggleLabel)}" title="${esc(toggleLabel)}"><span class="card-title">${esc(t('subagent.count', { n: sub.entries.length }))}</span><span class="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="subagent-list${expanded ? '' : ' hidden'}">${rows}</div></div>`)
2942
- box.querySelector('[data-subagent-toggle]')?.addEventListener('click', () => {
2943
- const icon = box.querySelector('[data-subagent-toggle] morph-icon')
2944
- if (icon) icon.setAttribute('data-morph-state', expanded ? 'closed' : 'open')
2945
- state.subagentExpandedSession = expanded ? '' : sessionId
2946
- setTimeout(() => renderSessionCards(), 240)
2947
- })
2948
- box.querySelectorAll('[data-sub-interrupt]').forEach(btn =>
2949
- btn.addEventListener('click', () => interruptSubagent(btn.dataset.subInterrupt)))
2950
- }
3042
+ window.DshSubagents?.configure($('btn-subagents'), {
3043
+ sessionId, title: titleOf(s), activity: s.running === true ? 'running' : s.running === false ? 'inactive' : 'unknown', parentId: s.origin === 'subagent' ? s.parentSessionId : null,
3044
+ valid: () => connection.valid() && state.current === sessionId,
3045
+ read: loadSessionSubagents, remember: rememberSubagent,
3046
+ onShow: () => conversationView?.pause(), onClose: () => conversationView?.resume(),
3047
+ open: (entry, parentId) => openSubagentSession(entry.id, parentId, entry, sessionId),
3048
+ interrupt: interruptSubagent,
3049
+ })
2951
3050
  }
2952
3051
 
2953
3052
  function setGoalPhaseLocal(phase) {
@@ -2981,10 +3080,11 @@ async function goalAction(kind) {
2981
3080
  scheduleRefresh()
2982
3081
  }
2983
3082
 
2984
- async function interruptSubagent(childId) {
3083
+ async function interruptSubagent(childId, parentId = state.current) {
3084
+ const connection = captureConnection(), rootId = state.current
2985
3085
  if (!confirm(t('subagent.confirmInterrupt'))) return
2986
- const result = await safeRpc('subagent.interrupt', { parentSessionId: state.current, childSessionId: childId, mode: 'continuable' }, t('subagent.interruptFailed'))
2987
- if (result == null) return
3086
+ const result = await safeRpc('subagent.interrupt', { parentSessionId: parentId, childSessionId: childId, mode: 'continuable' }, t('subagent.interruptFailed'))
3087
+ if (result == null || !connection.valid() || state.current !== rootId) return
2988
3088
  toast(t('subagent.interruptSubmitted'), 'ok')
2989
3089
  setTimeout(renderSessionCards, 600)
2990
3090
  }
@@ -3067,7 +3167,7 @@ async function runSlashCommand(text) {
3067
3167
  const res = await fetch(apiUrl('/remote/api/command'), {
3068
3168
  method: 'POST',
3069
3169
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() },
3070
- body: JSON.stringify({ sessionId, line: clean }),
3170
+ body: JSON.stringify({ sessionId, line: clean, async: true }),
3071
3171
  ...(signal ? { signal } : {})
3072
3172
  })
3073
3173
  if (!connection.valid()) return true
@@ -3081,7 +3181,7 @@ async function runSlashCommand(text) {
3081
3181
  if (data?.ok === false) { toast(data.message || t('send.failed'), 'err'); return true }
3082
3182
  if (data?.ok && data.executed === true) {
3083
3183
  if (data.accepted) {
3084
- if (command === 'compact') {
3184
+ if (command === 'compact' || command === 'export') {
3085
3185
  setCompactionStatus(sessionId, { ...(data.operation || data.compact), active: true, command, source: 'command' })
3086
3186
  } else {
3087
3187
  state.pendingCommands[sessionId] = command
@@ -3209,11 +3309,13 @@ function composerIsBusy() {
3209
3309
  return !!state.byId.get(state.current)?.running || (state.queues[state.current] || []).some(item => item.placement === 'queued')
3210
3310
  }
3211
3311
  function composerSendMode(alternate = false) {
3312
+ if (window.DshWorkflow?.isMounted()) return alternate && composerIsBusy() ? 'steer' : 'queue'
3212
3313
  if (!steerSendingEnabled() || !composerIsBusy()) return 'queue'
3213
3314
  const preferred = LS.get('busySendMode', 'queue') === 'steer' ? 'steer' : 'queue'
3214
3315
  return alternate ? (preferred === 'queue' ? 'steer' : 'queue') : preferred
3215
3316
  }
3216
3317
  function renderComposerSend() {
3318
+ window.DshWorkflow?.update()
3217
3319
  const enabled = steerSendingEnabled() && composerIsBusy()
3218
3320
  const mode = composerSendMode()
3219
3321
  for (const id of ['btn-send', 'btn-fs-send']) {
@@ -3232,6 +3334,7 @@ function renderComposerSend() {
3232
3334
  node.classList.toggle('hidden', !node.textContent)
3233
3335
  node.dataset.phase = feedback?.phase || 'hint'
3234
3336
  }
3337
+ window.DshWorkflow?.update()
3235
3338
  }
3236
3339
  function setComposerSendFeedback(context, key, phase, message = '') {
3237
3340
  composerSendFeedback.set(context, { key, phase, message })
@@ -3304,11 +3407,12 @@ function bindComposerSend(button) {
3304
3407
  }
3305
3408
 
3306
3409
  async function sendSessionContent(text, images, requestedMode = 'queue') {
3410
+ if (state.byId.get(state.current)?.origin === 'subagent') { toast('子代理记录为只读 / Subagent records are read only'); return false }
3307
3411
  const clean = String(text || '').trim()
3308
3412
  if ((!clean && !images.length) || !state.current || composerSending) return false
3309
3413
  const sessionId = state.current
3310
3414
  const context = composerContext()
3311
- const mode = requestedMode === 'steer' && steerSendingEnabled() && composerIsBusy() ? 'steer' : 'queue'
3415
+ const mode = requestedMode === 'steer' && (window.DshWorkflow?.isMounted() || steerSendingEnabled()) && composerIsBusy() ? 'steer' : 'queue'
3312
3416
  if (mode === 'steer' && clean.startsWith('/')) {
3313
3417
  setComposerSendFeedback(context, 'send.steerSlash', 'error')
3314
3418
  return false
@@ -3582,6 +3686,7 @@ async function newSession() {
3582
3686
  if (!workspaceItems().length) await refreshWorkbench()
3583
3687
  const preferred = workspaceById(state.workspaceFilter)?.workspaceId || LS.get('lastNewSessionWorkspaceV1', '')
3584
3688
  renderNewSessionWorkspace(preferred)
3689
+ if (workspaceById(state.workspaceFilter) || workspaceItems().length === 1) return createSessionInWorkspace()
3585
3690
  $('modal-new-session').classList.remove('hidden')
3586
3691
  }
3587
3692
  function renderNewSessionWorkspace(preferredId = '') {
@@ -3619,9 +3724,12 @@ async function createSessionInWorkspace() {
3619
3724
  LS.set('lastNewSessionWorkspaceV1', workspaceId)
3620
3725
  closeNewSessionModal()
3621
3726
  toast(t('home.created'), 'ok')
3622
- await refreshSessions()
3623
- if (!connection.valid()) return
3624
- openSession(v.sessionId)
3727
+ const workspace = workspaceById(workspaceId)
3728
+ const session = { sessionId: v.sessionId, cwd: workspace?.path || '', running: false, projections: { values: {} } }
3729
+ state.byId.set(session.sessionId, session)
3730
+ state.sessions.unshift(session)
3731
+ void openSession(session.sessionId)
3732
+ void refreshSessions()
3625
3733
  } finally { createSessionInWorkspace.busy = false; button.disabled = false }
3626
3734
  }
3627
3735
 
@@ -3759,6 +3867,7 @@ window.addEventListener('offline',()=>startOverviewDetection(true))
3759
3867
  document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible')startOverviewDetection(true);else {overviewDetector?.pause();overviewPulse?.pause()}})
3760
3868
 
3761
3869
  function renderOverview() {
3870
+ window.DshWorkflow?.update()
3762
3871
  const ring = $('overview-pulse-ring')
3763
3872
  if (!ring) return
3764
3873
  const checks = overviewChecks()
@@ -3795,7 +3904,7 @@ function renderOverview() {
3795
3904
  ...state.questions.map(q => ({ kind: 'question', item: q }))
3796
3905
  ]
3797
3906
  $('overview-attention-count').textContent = pending.length ? t('overview.pendingCount', { n: pending.length }) : '—'
3798
- $('overview-attention-list').innerHTML = pending.length ? pending.slice(0, 3).map(({ kind, item }) => {
3907
+ $('overview-attention-list').innerHTML = pending.length ? pending.map(({ kind, item }) => {
3799
3908
  const title = sessionLabelOf(state.byId.get(item.sessionId))
3800
3909
  if (kind === 'approval') return `<div class="overview-attention-item" data-overview-approval="${esc(item.approvalId)}">
3801
3910
  <span class="overview-item-mark">⌁</span><span class="overview-item-copy"><span class="overview-item-title">${esc(item.toolName || t('tool.default'))}</span><span class="overview-item-desc">${esc(approvalDetail(item))} · ${esc(title)}</span></span>
@@ -4257,6 +4366,18 @@ function fsApiUrl(sub, params = {}) {
4257
4366
  return u.href
4258
4367
  }
4259
4368
 
4369
+ /** 对话里 Markdown 图片的本地路径:相对路径按当前会话工作区解析,读取走 /fs/file。 */
4370
+ function chatImageRequest(pathValue) {
4371
+ const value = String(pathValue || '').trim()
4372
+ if (!value) return null
4373
+ let target = value
4374
+ if (!/^(?:[A-Za-z]:[\\/]|\\\\|\/|~[\\/])/.test(value)) {
4375
+ const root = state.byId.get(state.current)?.cwd || ''
4376
+ if (root) target = root.replace(/[\\/]+$/, '') + (root.includes('\\') ? '\\' : '/') + value.replace(/^\.?[\\/]+/, '')
4377
+ }
4378
+ return { url: fsApiUrl('/file', { path: target }), headers: fsHeaders() }
4379
+ }
4380
+
4260
4381
  function fsAuthError(status) {
4261
4382
  if (status === 401) authFailure()
4262
4383
  }
@@ -4534,6 +4655,8 @@ async function runFsUpload(up) {
4534
4655
  const xhr = new XMLHttpRequest()
4535
4656
  up.xhr = xhr
4536
4657
  xhr.open('POST', fsApiUrl('/upload', params))
4658
+ xhr.timeout = window.DshNetwork?.profile().weak ? 180000 : 90000
4659
+ xhr.ontimeout = () => { if (up.xhr === xhr) up.xhr = null; reject(new Error('上传等待超时,可查询进度后继续')) }
4537
4660
  xhr.setRequestHeader('authorization', 'Bearer ' + state.token)
4538
4661
  xhr.setRequestHeader('x-dsh-remote-client', CAP?.isNativePlatform?.() ? 'app' : 'web')
4539
4662
  if (CLIENT_ID) xhr.setRequestHeader('x-dsh-remote-client-id', CLIENT_ID)
@@ -4586,7 +4709,8 @@ async function runFsUpload(up) {
4586
4709
 
4587
4710
  while (up.offset < up.size) {
4588
4711
  if (up.cancelled) return
4589
- const end = Math.min(up.offset + FS_CHUNK_SIZE, up.size)
4712
+ const chunkSize = up.chunkSize || (window.DshNetwork?.profile().weak ? 256 * 1024 : FS_CHUNK_SIZE)
4713
+ const end = Math.min(up.offset + chunkSize, up.size)
4590
4714
  const blob = up.file.slice(up.offset, end)
4591
4715
  const before = hasher.clone()
4592
4716
  const chunkBytes = new Uint8Array(await blob.arrayBuffer())
@@ -4598,7 +4722,10 @@ async function runFsUpload(up) {
4598
4722
  const params = { path: up.path, name: up.name, session: up.session, offset: String(up.offset), size: String(up.size) }
4599
4723
  if (isLast) { params.finish = '1'; params.sha256 = hasher.hex() }
4600
4724
  if (overwrite) params.overwrite = '1'
4725
+ const startedAt = Date.now()
4601
4726
  const r = await uploadChunk(params, blob)
4727
+ const elapsed = Date.now() - startedAt
4728
+ up.chunkSize = elapsed > 15000 ? Math.max(65536, Math.floor(chunkSize / 2)) : elapsed < 2000 ? Math.min(FS_CHUNK_SIZE, chunkSize * 2) : chunkSize
4602
4729
  if (r.status === 401) { fsAuthError(401); return }
4603
4730
  if (r.status === 200 && r.json.offset != null) { up.offset = r.json.offset; continue }
4604
4731
  if (r.status === 201) {
@@ -4690,8 +4817,8 @@ async function runFsUpload(up) {
4690
4817
  toast(e.message, 'err')
4691
4818
  return
4692
4819
  }
4693
- hideFsProgress()
4694
- setFsButtons(false)
4820
+ up.paused = true
4821
+ setFsButtons(true, true)
4695
4822
  toast(t('fs.uploadInterrupted', { msg: e.message }), 'err')
4696
4823
  }
4697
4824
  }
@@ -5191,7 +5318,8 @@ async function fetchAnnouncements() {
5191
5318
  const seen = readSeenAnnouncements()
5192
5319
  const items = normalized.filter(item => !seen[item.id])
5193
5320
  .sort((a, b) => b.publishedAt - a.publishedAt)
5194
- if (!items.length || state.announcement) return false
5321
+ // 新旧界面均提示未读公告;拉取期间新出现的版本提醒仍优先展示。
5322
+ if (!items.length || state.announcement || isAppVersionWarningOpen()) return false
5195
5323
  openAnnouncementModal(items)
5196
5324
  return true
5197
5325
  } catch { return false }
@@ -5321,7 +5449,7 @@ async function checkUpdate(silent) {
5321
5449
  const res = await fetch(base + '/update.json?t=' + Date.now() + '&local=' + encodeURIComponent(state.localVersion))
5322
5450
  if (!res.ok) throw new Error('HTTP ' + res.status)
5323
5451
  const info = await res.json()
5324
- openNotesModal(info)
5452
+ if (!silent || !window.DshWorkflow?.isMounted()) openNotesModal(info)
5325
5453
  if (info.version && cmpVersion(info.version, state.localVersion) > 0) {
5326
5454
  state.updateInfo = info
5327
5455
  const hasNotes = !!(info.notes && String(info.notes).trim())
@@ -5379,6 +5507,7 @@ function finishUpdateDownload() {
5379
5507
  clearInterval(updateDownloadTimer)
5380
5508
  updateDownloadTimer = null
5381
5509
  $('btn-download-update').disabled = false
5510
+ const forceButton=$('btn-force-download-update');if(forceButton)forceButton.disabled=false
5382
5511
  }
5383
5512
 
5384
5513
  async function verifyUpdateApk(info, url) {
@@ -5389,7 +5518,7 @@ async function verifyUpdateApk(info, url) {
5389
5518
  const resetTimeout = () => { clearTimeout(timer); timer = setTimeout(() => controller.abort(), 60000) }
5390
5519
  try {
5391
5520
  resetTimeout()
5392
- const res = await fetch(url, { signal: controller.signal })
5521
+ const res = await fetch(url, { signal: controller.signal, cache: 'no-store' })
5393
5522
  if (!res.ok) return { ok: false, status: res.status }
5394
5523
  total = Number(res.headers.get('content-length')) || 0
5395
5524
  const chunks = []
@@ -5420,23 +5549,36 @@ async function verifyUpdateApk(info, url) {
5420
5549
  finally { clearTimeout(timer); clearInterval(progressTimer) }
5421
5550
  }
5422
5551
 
5423
- async function downloadUpdate() {
5424
- const info = state.updateInfo
5425
- if (!info || updateDownloadBusy) return
5426
- const url = new URL(info.apkUrl || 'dsh-remote.apk', updateBase() + '/').href
5427
- const sha256 = String(info.sha256 || '').trim().toLowerCase()
5428
- if (!/^[0-9a-f]{64}$/.test(sha256)) {
5429
- // 无 SHA-256 的更新包一律不下载、不安装
5430
- updateDownloadProgress({ phase: 'error', error: t('update.hashMissing') })
5431
- return
5432
- }
5552
+ async function downloadUpdate(force = false) {
5553
+ if (updateDownloadBusy || (force !== true && !state.updateInfo)) return
5554
+ const base=updateBase()
5555
+ if(!base){toast(t('update.needServer'),'err');return}
5556
+ const connection=captureConnection()
5433
5557
  updateDownloadBusy = true
5434
5558
  updateDownloadSample = null
5435
5559
  $('btn-download-update').disabled = true
5436
- updateDownloadProgress({ phase: 'downloading', received: 0, total: 0 })
5437
- if (CAP?.isNativePlatform?.() && window.NativeUpdate?.downloadVerifiedAndInstall && window.NativeUpdate?.getDownloadStatus) {
5438
- try {
5560
+ const forceButton=$('btn-force-download-update');if(forceButton)forceButton.disabled=true
5561
+ let nativePending=false
5562
+ try {
5563
+ let info=state.updateInfo
5564
+ if(force===true){
5565
+ updateDownloadProgress({phase:'checking',received:0,total:0})
5566
+ // Same-version patches deliberately bypass only version comparison. Both
5567
+ // metadata and APK bytes are fetched afresh; hash verification still applies.
5568
+ const response=await fetch(base+'/update.json?t='+Date.now()+'&local='+encodeURIComponent(state.localVersion||''),{cache:'no-store',signal:AbortSignal.timeout(15000)})
5569
+ if(!response.ok)throw new Error('HTTP '+response.status)
5570
+ info=await response.json()
5571
+ }
5572
+ if(!connection.valid())return
5573
+ const sha256=String(info?.sha256||'').trim().toLowerCase()
5574
+ if(!/^[0-9a-f]{64}$/.test(sha256))throw new Error(t('update.hashMissing'))
5575
+ const target=new URL(info.apkUrl||'dsh-remote.apk',base+'/')
5576
+ if(force===true)target.searchParams.set('dshPatch',Date.now().toString(36)+'-'+sha256.slice(0,16))
5577
+ const url=target.href
5578
+ updateDownloadProgress({ phase: 'downloading', received: 0, total: 0 })
5579
+ if (CAP?.isNativePlatform?.() && window.NativeUpdate?.downloadVerifiedAndInstall && window.NativeUpdate?.getDownloadStatus) {
5439
5580
  if (!window.NativeUpdate.downloadVerifiedAndInstall(url, sha256)) throw new Error(t('update.busy'))
5581
+ nativePending=true
5440
5582
  const poll = () => {
5441
5583
  try {
5442
5584
  const value = JSON.parse(window.NativeUpdate.getDownloadStatus())
@@ -5446,12 +5588,11 @@ async function downloadUpdate() {
5446
5588
  }
5447
5589
  updateDownloadTimer = setInterval(poll, 500)
5448
5590
  poll()
5449
- } catch (error) { updateDownloadProgress({ phase: 'error', error: error.message }); finishUpdateDownload() }
5450
- return
5451
- }
5452
- try {
5591
+ return
5592
+ }
5453
5593
  const result = await verifyUpdateApk(info, url)
5454
- if (!result.ok) throw new Error(result.corrupted ? t('update.corrupted') : result.status ? t('update.serverFileMissing') : result.msg || t('fs.networkError'))
5594
+ if(!connection.valid())return
5595
+ if (!result.ok) throw new Error(result.corrupted ? t(force===true?'update.patchMismatch':'update.corrupted') : result.status ? t('update.serverFileMissing') : result.msg || t('fs.networkError'))
5455
5596
  {
5456
5597
  // 无校验的原生安装入口已移除: 新旧壳统一走下方"下载并本地校验"路径。
5457
5598
  const objectUrl = URL.createObjectURL(result.blob)
@@ -5464,8 +5605,8 @@ async function downloadUpdate() {
5464
5605
  setTimeout(() => URL.revokeObjectURL(objectUrl), 60000)
5465
5606
  updateDownloadProgress({ phase: 'complete', received: result.blob.size, total: result.blob.size })
5466
5607
  }
5467
- } catch (error) { updateDownloadProgress({ phase: 'error', error: error.message }) }
5468
- finally { finishUpdateDownload() }
5608
+ } catch (error) { if(connection.valid())updateDownloadProgress({ phase: 'error', error: error.message }) }
5609
+ finally { if(!nativePending)finishUpdateDownload() }
5469
5610
  }
5470
5611
 
5471
5612
 
@@ -5691,8 +5832,7 @@ function deletePreset(id) {
5691
5832
  toast(t('presets.deleted'), 'ok')
5692
5833
  }
5693
5834
 
5694
- /* ---------------- 峰谷计费提醒(前台服务进程内定时, 绕开 MIUI 后台限制) ---------------- */
5695
- function peakRemindOn() { return LS.get('peakRemind', '0') === '1' }
5835
+ /* ---------------- 旧峰谷提醒清理(现由 dsh-cost-meter 管理) ---------------- */
5696
5836
  const LEGACY_PEAK_NOTIFICATION_IDS = [8801, 8802, 8803, 8804]
5697
5837
 
5698
5838
  async function cancelLegacyPeakNotifications() {
@@ -5708,32 +5848,21 @@ async function cancelLegacyPeakNotifications() {
5708
5848
  }
5709
5849
  }
5710
5850
 
5711
- async function schedulePeakReminders({ legacyCleaned = false } = {}) {
5712
- if (!CAP?.isNativePlatform?.()) return false
5713
- if (!legacyCleaned && !await cancelLegacyPeakNotifications()) return false
5714
- const b = bgBridge()
5715
- if (!b?.startPeakReminder) return false
5716
- try {
5717
- return b.startPeakReminder() !== false
5718
- } catch { return false }
5719
- }
5720
-
5721
5851
  async function cancelPeakReminders() {
5722
5852
  if (!CAP?.isNativePlatform?.()) return false
5853
+ const legacyCleaned = await cancelLegacyPeakNotifications()
5723
5854
  const b = bgBridge()
5724
5855
  if (!b?.stopPeakReminder) return false
5725
5856
  try {
5726
5857
  const stopped = b.stopPeakReminder() !== false
5727
- const legacyCleaned = await cancelLegacyPeakNotifications()
5728
5858
  return stopped && legacyCleaned
5729
5859
  } catch { return false }
5730
5860
  }
5731
5861
 
5732
5862
  async function restorePeakReminders() {
5733
- if (!CAP?.isNativePlatform?.()) return
5734
- // 旧版使用 LocalNotifications 每日调度;无论当前开关状态都先清理,防止与前台服务重复提醒。
5735
- const legacyCleaned = await cancelLegacyPeakNotifications()
5736
- if (peakRemindOn() && legacyCleaned) await schedulePeakReminders({ legacyCleaned: true })
5863
+ // dsh-cost-meter owns reminders. Retire both legacy scheduling mechanisms.
5864
+ LS.del('peakRemind')
5865
+ await cancelPeakReminders()
5737
5866
  }
5738
5867
 
5739
5868
  /* ---------------- 模型设置 ---------------- */
@@ -6289,6 +6418,10 @@ async function openModelConfigDocument() {
6289
6418
  }
6290
6419
  /* ---------------- 视图切换 ---------------- */
6291
6420
  function showView(id) {
6421
+ if (id !== 'view-session') window.DshSubagents?.close()
6422
+ document.body?.classList.toggle('viewing-subagent', id === 'view-session' && state.byId.get(state.current)?.origin === 'subagent')
6423
+ window.DshWorkflow?.close()
6424
+ if (window.DshWorkflow?.isMounted() && id === 'view-activity') id = 'view-home'
6292
6425
  if (id !== 'view-session') conversationView?.pause()
6293
6426
  if (id !== 'view-session' && document.body.classList.contains('in-session') && state.current) void archiveEmptySessionOnLeave(state.current)
6294
6427
  for (const v of ['view-home', 'view-files', 'view-session', 'view-activity', 'view-plugins', 'view-settings']) $(v).classList.toggle('hidden', v !== id)
@@ -7113,7 +7246,11 @@ function bindUi() {
7113
7246
  if (first.matches('button')) first.focus({ preventScroll: true })
7114
7247
  }
7115
7248
  })
7116
- // 会话列表点击
7249
+ // 会话列表点击与键盘激活共享目标。
7250
+ $('session-list').addEventListener('keydown', event => {
7251
+ const card = event.target.closest('[data-session-swipe]')
7252
+ if (card && event.target === card && ['Enter', ' '].includes(event.key)) { event.preventDefault(); void openSession(card.dataset.id) }
7253
+ })
7117
7254
  $('session-list').addEventListener('click', (e) => {
7118
7255
  if (swipeSuppressClickUntil > Date.now()) { swipeSuppressClickUntil = 0; return }
7119
7256
  if (e.target.closest('[data-archived-toggle]')) {
@@ -7434,7 +7571,8 @@ function bindUi() {
7434
7571
  $('btn-dsh-start')?.addEventListener('click', () => controlDsh('start'))
7435
7572
  $('btn-dsh-restart')?.addEventListener('click', () => controlDsh('restart'))
7436
7573
  $('btn-check-update').addEventListener('click', () => checkUpdate(false))
7437
- $('btn-download-update').addEventListener('click', downloadUpdate)
7574
+ $('btn-download-update').addEventListener('click', () => void downloadUpdate())
7575
+ $('btn-force-download-update').addEventListener('click', () => void downloadUpdate(true))
7438
7576
  $('btn-update-expand').addEventListener('click', toggleUpdateExpand)
7439
7577
  $('app-version-later').addEventListener('click', () => closeAppVersionWarning(false))
7440
7578
  $('app-version-update').addEventListener('click', () => closeAppVersionWarning(true))
@@ -7477,34 +7615,9 @@ function bindUi() {
7477
7615
  LS.set('notify', e.target.checked ? '1' : '0')
7478
7616
  window.NativeBackground?.setPendingNotificationsEnabled?.(e.target.checked)
7479
7617
  })
7480
- $('opt-peak-remind').checked = peakRemindOn()
7481
- $('opt-peak-remind').addEventListener('change', async (e) => {
7482
- if (e.target.checked) {
7483
- if (!CAP?.isNativePlatform?.()) {
7484
- e.target.checked = false
7485
- return toast(t('peakRemind.browserOnly'), 'err')
7486
- }
7487
- const ok = await ensureNotify()
7488
- if (!ok) { e.target.checked = false; return toast(t('settings.notifyDenied')) }
7489
- const started = await schedulePeakReminders()
7490
- if (!started) {
7491
- e.target.checked = false
7492
- return toast(t('peakRemind.failed'), 'err')
7493
- }
7494
- toast(t('peakRemind.on'), 'ok')
7495
- } else {
7496
- const stopped = await cancelPeakReminders()
7497
- if (!stopped) {
7498
- e.target.checked = true
7499
- return toast(t('peakRemind.failed'), 'err')
7500
- }
7501
- toast(t('peakRemind.off'), 'ok')
7502
- }
7503
- LS.set('peakRemind', e.target.checked ? '1' : '0')
7504
- })
7505
7618
  $('btn-test-notify').addEventListener('click', sendTestNotification)
7506
7619
  $('btn-announcement-history').addEventListener('click', openAnnouncementHistory)
7507
- // 启动时先清理旧版 LocalNotifications,再按当前开关恢复前台提醒服务。
7620
+ // 启动时清理旧版 LocalNotifications 和前台提醒服务,提醒交给 dsh-cost-meter。
7508
7621
  restorePeakReminders()
7509
7622
  applyBgConfigFromNative()
7510
7623
  $('opt-bg-poll').addEventListener('change', async (e) => {
@@ -7557,10 +7670,11 @@ function bindUi() {
7557
7670
  bindFsPullRefresh()
7558
7671
 
7559
7672
  bindRail()
7673
+ window.DshImagePreview?.configure?.({ resolvePath: chatImageRequest })
7560
7674
 
7561
7675
  for (const id of ['history', 'question-body']) window.DshChatFiles?.bind($(id), () => {
7562
7676
  const c=captureConnection(),sessionId=id==='history'?state.current:state.questionModal?.sessionId
7563
- return { ...c,sessionId,cwd:sessionCwd(state.byId.get(sessionId)),native:!!CAP?.isNativePlatform?.(),headers:{authorization:'Bearer '+c.token,...clientIdHeaders()},notice:toast,
7677
+ return { ...c,sessionId,cwd:sessionCwd(state.byId.get(sessionId)),native:!!CAP?.isNativePlatform?.(),headers:{authorization:'Bearer '+c.token,...clientIdHeaders()},notice:toast,preview:(path,name)=>window.DshWorkflow?.preview({...c,headers:{authorization:'Bearer '+c.token}},path,name),
7564
7678
  valid:()=>c.valid()&&sessionId===(id==='history'?state.current:state.questionModal?.sessionId) }
7565
7679
  })
7566
7680
  initCustomSelects()
@@ -7617,6 +7731,84 @@ async function boot() {
7617
7731
  }
7618
7732
 
7619
7733
  document.addEventListener('DOMContentLoaded', boot)
7734
+ document.addEventListener('DOMContentLoaded', mountWorkflow)
7735
+
7736
+ function mountWorkflow() {
7737
+ window.DshWorkflow?.mount({
7738
+ desktop: false,
7739
+ start: () => { if (!$('view-activity').classList.contains('hidden')) showView('view-home') },
7740
+ snapshot: () => ({ token: !!state.token, host: currentServerEntry()?.note || state.server || location.host,
7741
+ gateway: activeGatewayHealth()?.ok || !!state.streamsOk?.mux, dsh: dshReachable(),
7742
+ mux: !!state.streamsOk?.mux, hostEvents: !!state.streamsOk?.host,
7743
+ pending: state.approvals.length + state.questions.length, busy: composerIsBusy(), sending: composerSending }),
7744
+ settings: name => { showView('view-settings'); showSettingsPage(name) },
7745
+ plugins: () => showView('view-plugins'), models: loadSessionModels, send: sendMessage,
7746
+ feedback: openFeedbackModal,
7747
+ browse: () => { closeNewSessionModal(); showView('view-files') },
7748
+ register: async () => {
7749
+ const connection=captureConnection(), path=state.fs.path
7750
+ if(!path)return toast('请先选择主机目录','err')
7751
+ try {
7752
+ const value=await rpc('workspace.create',{path})
7753
+ if(!connection.valid()||!value?.workspace)return
7754
+ state.wbProjects=[...state.wbProjects.filter(w=>w.workspaceId!==value.workspace.workspaceId),value.workspace]
7755
+ state.workspaceFilter=value.workspace.workspaceId;closeWorkspaceModal();await newSession()
7756
+ }catch(error){if(connection.valid())toast(error.message,'err')}
7757
+ },
7758
+ command: runSlashCommand, refresh: refreshAll, retry: () => { startOverviewDetection(true); void refreshAll() },
7759
+ operations: () => { const connection=captureConnection(); return { url:apiUrl,headers:{authorization:'Bearer '+connection.token},valid:connection.valid } },
7760
+ relay: () => { const connection=captureConnection(); return { url:()=>adminApiUrl('/admin/api/relay'),headers:{authorization:'Bearer '+connection.token},valid:connection.valid,connected:!!connection.token } },
7761
+ discover: () => { if (confirm('登记当前绑定目录下的子目录为工作区?')) void refreshWorkbench({ discover: true }) },
7762
+ files: () => {
7763
+ const workspace = workspaceForSession(state.byId.get(state.current))
7764
+ if (workspace) return openWorkspaceFiles(workspace.workspaceId)
7765
+ const cwd = sessionCwd(state.byId.get(state.current))
7766
+ if (!cwd) return toast('当前会话没有工作目录', 'err')
7767
+ state.fs.loaded = true; showView('view-files'); void loadFs(cwd, { resetRoot: true })
7768
+ },
7769
+ clear: clearWorkflowData,
7770
+ admin: () => {
7771
+ const url = new URL(adminApiUrl('/admin/'), location.href)
7772
+ // Open authenticated management through its own login flow. No credential
7773
+ // in a newly created URL, browser history, or referrer.
7774
+ window.open(url.href, '_blank', 'noopener,noreferrer')
7775
+ },
7776
+ recover: (row, receipt) => {
7777
+ const value = receipt.result?.result?.value
7778
+ if (row.method === 'session.create' && value?.sessionId) void openSession(value.sessionId)
7779
+ if (row.sessionId === state.current) void resyncCurrentSession()
7780
+ },
7781
+ })
7782
+ }
7783
+
7784
+ async function clearWorkflowData(kind) {
7785
+ const english = window.I18N?.lang === 'en'
7786
+ const messages = { history: english ? 'Clear cached conversation history on this device?' : '清除这台设备的会话历史缓存?主机记录保留。',
7787
+ connection: english ? 'Remove the current address and its saved credential? Other addresses remain.' : '移除当前地址和保存的凭证?其他连接条目保留。',
7788
+ all: english ? 'Clear all Remote settings and credentials on this device and stop background reminders?' : '清除本机全部 Remote 配置与凭证,并停止后台轮询和提醒?主机数据保留。' }
7789
+ if (!confirm(messages[kind])) return
7790
+ if (kind === 'history') {
7791
+ clearTimeout(scheduleHistoryCacheSave._t)
7792
+ await window.DshHistory.cacheClear()
7793
+ for (let i=localStorage.length-1;i>=0;i--) { const key=localStorage.key(i); if (/^dsh-remote-(?:sessions|history)/.test(key)) localStorage.removeItem(key) }
7794
+ return toast(english ? 'History cache cleared' : '历史缓存已清除', 'ok')
7795
+ }
7796
+ window.NativeBackground?.saveBackgroundConfig?.(JSON.stringify({ enabled:false, base:'', token:'', clientId:'', intervalMin:1, notifyTaskDone:false }))
7797
+ window.NativeBackground?.setPendingNotificationsEnabled?.(false)
7798
+ if (kind === 'connection') {
7799
+ const current = currentServerEntry()
7800
+ if (current) state.servers = state.servers.filter(server => server.id !== current.id)
7801
+ state.groupActive[state.activeGroup] = ''
7802
+ state.token = ''; state.server = ''; LS.del('token'); LS.del('server'); saveServers()
7803
+ closeStream('mux'); closeStream('host'); stopPolling(); renderServers(); showView('view-settings'); showSettingsPage('servers')
7804
+ return
7805
+ }
7806
+ await cancelPeakReminders()
7807
+ clearTimeout(scheduleHistoryCacheSave._t)
7808
+ await window.DshHistory.cacheClear()
7809
+ window.DshWorkflow.clearStorage()
7810
+ location.reload()
7811
+ }
7620
7812
 
7621
7813
  function openPluginPage(route = 'manage') {
7622
7814
  const connection = captureConnection()
@@ -7626,6 +7818,7 @@ function openPluginPage(route = 'manage') {
7626
7818
  }
7627
7819
  window.DshExtensions.mount({
7628
7820
  connection, getSession: () => state.byId.get(state.current), getTitle: () => sessionTitleValue(state.byId.get(state.current)),
7821
+ back: () => showView('view-settings'),
7629
7822
  openContext: () => void openInsights('context', true),
7630
7823
  returnToSession: () => showView('view-session'), scrollTop: () => window.scrollTo(0,0),
7631
7824
  url: path => connection.server + path,