dsh-remote-plugin 0.7.3 → 0.7.5

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
@@ -75,6 +75,7 @@ const state = {
75
75
  questions: [], // 待处理提问
76
76
  queues: {}, // sessionId -> queue items
77
77
  queueSteering: {}, // sessionId:itemId -> pending steer request
78
+ compactionBootAt: Date.now(),
78
79
  compactions: {}, // sessionId -> {active, phase, startedAt, message, source}
79
80
  pendingCommands: {}, // sessionId -> command name; waits briefly before showing generic progress
80
81
  compactionPollTimer: null,
@@ -115,14 +116,24 @@ for (const key of ['server', 'token']) {
115
116
  set(next) {
116
117
  if (next === value) return
117
118
  value = next; connectionGeneration++
119
+ clearTimeout(state.refreshTimer); state.refreshTimer = null
118
120
  state.sessions = []; state.byId.clear(); state.pendingProjections.clear()
119
121
  state.hostInfo = null
120
122
  if(typeof closeStream==='function'&&typeof streamMeta!=='undefined'){closeStream('mux');closeStream('host')}
121
123
  state.current = null; state.history = emptyHistory()
124
+ state.models = { loaded: false, loading: false, groups: [], current: null, failures: [] }
125
+ state.modelSettings = { status: 'idle', error: '', writable: false, hasDocument: false, providers: [], namespaces: [], credentials: {} }; state.modelEditor = null
126
+ state.goalEdit = null; state.goalEditContext = null
127
+ state.approvals = []; state.questions = []; state.questionModal = null
128
+ state.queues = {}; state.jobs = {}; state.queueSteering = {}; state.compactions = {}; state.compactionTerminals = {}; state.compactionSeqs = {}; state.compactionBootAt = Date.now(); state.pendingCommands = {}; state.sessionTurnTimes = {}
129
+ state.sessionActivity = new Set(); state.pendingPrompts = new Set()
122
130
  state.fs.path = null; state.fs.initial = null; state.fs.loaded = false; state.fs.roots = []; state.fs.rootIndex = 0
123
131
  state.wb = null; state.wbProjects = []; state.wbArchived = []; state.workspaceFilter = ''; state.fs.workspaceId = ''; clearTimeout(scheduleHistoryCacheSave._t)
124
132
  window.DshPluginCenter?.close()
125
133
  window.DshInsights?.close()
134
+ window.DshExtensions?.close()
135
+ window.DshExtensions?.invalidateCapabilities()
136
+ if (typeof document !== 'undefined') document.getElementById('btn-insights')?.classList.add('hidden')
126
137
  if(typeof document!=='undefined') {
127
138
  const identityGeneration=connectionGeneration
128
139
  queueMicrotask(()=>{if(identityGeneration===connectionGeneration&&typeof startOverviewDetection==='function')startOverviewDetection(true,true)})
@@ -132,6 +143,9 @@ for (const key of ['server', 'token']) {
132
143
  }
133
144
  if (typeof document !== 'undefined') {
134
145
  document.getElementById('modal-workspace')?.classList.add('hidden')
146
+ for (const id of ['modal-question', 'modal-new-session', 'modal-rename', 'modal-archive', 'modal-goal']) document.getElementById(id)?.classList.add('hidden')
147
+ if (typeof renderPending === 'function') renderPending()
148
+ if (typeof renderModelSettings === 'function') renderModelSettings()
135
149
  const generation = connectionGeneration
136
150
  queueMicrotask(() => {
137
151
  if (generation === connectionGeneration && document.getElementById('view-plugins')?.classList.contains('hidden') === false) openPluginPage()
@@ -433,14 +447,16 @@ function apiUrl(path) {
433
447
  }
434
448
 
435
449
  let wsTicketPromise = null
450
+ let wsTicketConnection = null
436
451
  async function getWsTicket() {
437
452
  const now = Date.now()
438
453
  if (state.wsTicket.token === state.token && state.wsTicket.server === state.server &&
439
454
  state.wsTicket.value && state.wsTicket.expiresAt > now + 15000) return state.wsTicket.value
440
- if (wsTicketPromise) return wsTicketPromise
455
+ if (wsTicketPromise && wsTicketConnection?.valid()) return wsTicketPromise
456
+ const connection = captureConnection()
441
457
  const token = state.token
442
458
  const server = state.server
443
- wsTicketPromise = (async () => {
459
+ const job = (async () => {
444
460
  if (activeGatewayCapability('wsTicket') === false) throw new Error('ws ticket unsupported')
445
461
  const res = await fetch(apiUrl('/api/ws-ticket'), {
446
462
  method: 'POST',
@@ -452,11 +468,14 @@ async function getWsTicket() {
452
468
  })
453
469
  if (!res.ok) throw new Error('ws ticket HTTP ' + res.status)
454
470
  const data = await res.json()
471
+ if (!connection.valid()) throw new Error('stale ws ticket')
455
472
  if (!data?.ticket || !Number(data.expiresAt)) throw new Error('invalid ws ticket')
456
473
  state.wsTicket = { token, server, value: data.ticket, expiresAt: Number(data.expiresAt) }
457
474
  return data.ticket
458
475
  })()
459
- try { return await wsTicketPromise } finally { wsTicketPromise = null }
476
+ wsTicketPromise = job
477
+ wsTicketConnection = connection
478
+ try { return await job } finally { if (wsTicketPromise === job) { wsTicketPromise = null; wsTicketConnection = null } }
460
479
  }
461
480
 
462
481
  function updateBase() {
@@ -525,7 +544,7 @@ async function respond(rpcId, value) {
525
544
 
526
545
  async function safeRpc(method, payload, errText) {
527
546
  const connection = captureConnection()
528
- try { return await rpc(method, payload) }
547
+ try { const value = await rpc(method, payload); return connection.valid() ? value : null }
529
548
  catch (e) {
530
549
  if (!connection.valid()) return null
531
550
  if (e.message === 'AUTH') authFailure()
@@ -718,7 +737,7 @@ async function pingServer(base) {
718
737
  const ctrl = new AbortController()
719
738
  const timer = setTimeout(() => ctrl.abort(), 3500)
720
739
  try {
721
- const res = await fetch(u + '/health?t=' + Date.now(), { signal: ctrl.signal, cache: 'no-store' })
740
+ const res = await fetch(u + '/health?probe=live&t=' + Date.now(), { signal: ctrl.signal, cache: 'no-store' })
722
741
  if (!res.ok) return Infinity
723
742
  const health = await res.json().catch(() => null)
724
743
  if (health && typeof health === 'object') {
@@ -751,7 +770,10 @@ function dshReachable() {
751
770
  }
752
771
 
753
772
  async function selectFastestServer({ silent = false, reconnect = true } = {}) {
754
- if (state.selectingServer) return null
773
+ const request = selectFastestServer.request = (selectFastestServer.request || 0) + 1
774
+ const connection = captureConnection(), group = state.activeGroup
775
+ const policy = JSON.stringify([state.autoSelect[group], state.groupActive[group], state.servers])
776
+ const valid = () => connection.valid() && request === selectFastestServer.request && state.activeGroup === group && policy === JSON.stringify([state.autoSelect[group], state.groupActive[group], state.servers])
755
777
  state.selectingServer = true
756
778
  try {
757
779
  if (!silent) toast(t('speed.testing'))
@@ -763,6 +785,7 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
763
785
 
764
786
  if (state.autoSelect[state.activeGroup] !== false) {
765
787
  const measured = await Promise.all(candidates.map(async (server) => [server, await pingServer(server.url)]))
788
+ if (!valid()) return null
766
789
  for (const [server, latency] of measured) state.serverLatency[serverKey(server)] = latency
767
790
  best = candidates
768
791
  .filter(server => Number.isFinite(state.serverLatency[serverKey(server)]))
@@ -783,6 +806,8 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
783
806
  }
784
807
  }
785
808
 
809
+ if (!valid()) return null
810
+ if (typeof window !== 'undefined') window.DshNetwork?.observeLatency(ms)
786
811
  renderServers()
787
812
  if (chosen !== state.server || chosenToken !== state.token) {
788
813
  state.hostInfo = null
@@ -813,7 +838,7 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
813
838
  await maybeWarnAppBehindGateway()
814
839
  return chosen
815
840
  } finally {
816
- state.selectingServer = false
841
+ if (request === selectFastestServer.request) state.selectingServer = false
817
842
  }
818
843
  }
819
844
 
@@ -1345,43 +1370,46 @@ function enterPollMode() {
1345
1370
  }
1346
1371
 
1347
1372
  function stopPolling() {
1348
- clearInterval(pollTimer)
1349
- pollTimer = null
1350
- clearTimeout(wsRetryTimer)
1351
- wsRetryTimer = null
1373
+ pollInFlight?.stop()
1374
+ pollInFlight = null
1375
+ clearInterval(pollTimer); pollTimer = null
1376
+ clearInterval(wsRetryTimer); wsRetryTimer = null
1352
1377
  }
1353
-
1354
1378
  function startPolling() {
1355
1379
  stopPolling()
1356
1380
  pollTimer = setInterval(pollOnce, 4000)
1357
1381
  wsRetryTimer = setInterval(tryRestoreWs, 30000)
1358
- pollOnce()
1382
+ void pollOnce()
1359
1383
  }
1360
-
1361
- let pollInFlight = false
1384
+ let pollInFlight = null
1362
1385
  async function pollOnce() {
1363
- if (state.streamMode !== 'poll' || pollInFlight) return
1364
- pollInFlight = true
1365
- try {
1366
- await Promise.all([pollKind('mux'), pollKind('host')])
1367
- } finally {
1368
- pollInFlight = false
1369
- }
1386
+ if (state.streamMode !== 'poll') return
1387
+ if (!pollInFlight) pollInFlight = new window.DshNetwork.PollLoop({
1388
+ active: () => state.streamMode === 'poll' && !!state.token,
1389
+ capture: () => { const connection = captureConnection(), cursors = state.pollSeq; return { valid: () => connection.valid() && state.pollSeq === cursors } },
1390
+ read: pollKind
1391
+ })
1392
+ return pollInFlight.tick()
1370
1393
  }
1371
1394
 
1372
- async function pollKind(kind) {
1395
+ async function pollKind(kind, cancellation) {
1373
1396
  if (state.streamMode !== 'poll') return
1397
+ const connection = captureConnection(), cursors = state.pollSeq
1398
+ const valid = () => connection.valid() && state.streamMode === 'poll' && state.pollSeq === cursors && !cancellation?.aborted
1374
1399
  const since = state.pollSeq[kind] || 0
1375
1400
  let res
1376
1401
  try {
1377
- const signal = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(30000) : undefined
1402
+ const timeout = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(window.DshNetwork?.profile().pollTimeout || 30000) : undefined
1403
+ const signal = cancellation && timeout && typeof AbortSignal.any === 'function' ? AbortSignal.any([cancellation, timeout]) : timeout || cancellation
1378
1404
  const headers = { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }
1379
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 })
1380
1406
  } catch { return }
1407
+ if (!valid()) return
1381
1408
  if (res.status === 401) { authFailure(); return }
1382
1409
  if (!res.ok) return
1383
1410
  let data
1384
1411
  try { data = await res.json() } catch { return }
1412
+ if (!valid()) return
1385
1413
  if (!data || !Array.isArray(data.events)) return
1386
1414
  // 网关重启或客户端离线过久后,游标可能落后于内存环形缓冲;
1387
1415
  // 从当前缓冲重新接收,并刷新权威会话列表,避免静默漏事件。
@@ -1403,6 +1431,7 @@ async function pollKind(kind) {
1403
1431
  else onHostFrame(item.event)
1404
1432
  }
1405
1433
  }
1434
+ return data.waitSupported === true ? 100 : 4000
1406
1435
  }
1407
1436
 
1408
1437
  function tryRestoreWs() {
@@ -1470,7 +1499,7 @@ function onMuxFrame(full) {
1470
1499
  if (f.sessionId === state.current) { applyReasoningBaseline(f.partialReasoning); scheduleReasoningRender() }
1471
1500
  return
1472
1501
  }
1473
- if (f.type === 'session/event') return onSessionEvent(f.sessionId, f.event)
1502
+ if (f.type === 'session/event') return onSessionEvent(f.sessionId, f.event, { replay: f.replay === true })
1474
1503
  if (f.type === 'session/subscribed') return
1475
1504
  if (f.type === 'approval/requested') {
1476
1505
  state.approvals = state.approvals.filter(a => a.approvalId !== f.approvalId)
@@ -1527,6 +1556,7 @@ function compactElapsed(startedAt) {
1527
1556
  }
1528
1557
 
1529
1558
  function setCompactionStatus(sessionId, next) {
1559
+ state.compactionTerminals ||= {}
1530
1560
  if (!sessionId) return
1531
1561
  const previous = state.compactions[sessionId]
1532
1562
  const active = next?.active === true
@@ -1538,10 +1568,15 @@ function setCompactionStatus(sessionId, next) {
1538
1568
  startedAt: Number(next.startedAt) || previous?.startedAt || Date.now(),
1539
1569
  message: String(next.message || ''),
1540
1570
  source: next.source || previous?.source || 'event',
1571
+ compactionId: next.compactionId || previous?.compactionId || '',
1572
+ notify: next.notify ?? previous?.notify ?? (next.source === 'command'),
1541
1573
  }
1542
1574
  } else {
1543
1575
  delete state.compactions[sessionId]
1544
1576
  if (previous?.active) {
1577
+ state.compactionTerminals[sessionId] = { startedAt: previous.startedAt, compactionId: previous.compactionId }
1578
+ }
1579
+ if (previous?.active && previous.notify && next?.notify !== false && ['complete', 'failed'].includes(next?.phase)) {
1545
1580
  const command = previous.command || 'compact'
1546
1581
  if (next?.phase === 'failed') toast(command === 'compact'
1547
1582
  ? t('session.compactFailed', { msg: next.message || t('send.failed') })
@@ -1555,18 +1590,25 @@ function setCompactionStatus(sessionId, next) {
1555
1590
 
1556
1591
  async function refreshCompactionStatus(sessionId = state.current) {
1557
1592
  if (!sessionId) return
1593
+ const connection = captureConnection()
1558
1594
  try {
1559
1595
  const signal = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(8000) : undefined
1560
- const url = new URL(apiUrl('/remote/api/command-status'), location.href)
1596
+ const url = new URL(connection.server + '/remote/api/command-status', location.href)
1561
1597
  url.searchParams.set('sessionId', sessionId)
1562
- const res = await fetch(url, { headers: { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }, ...(signal ? { signal } : {}) })
1598
+ const res = await fetch(url, { headers: { authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }, ...(signal ? { signal } : {}) })
1599
+ if (!connection.valid()) return
1563
1600
  if (res.status === 401) { authFailure(); return }
1564
1601
  if (!res.ok) return
1602
+ if (!connection.valid()) return
1565
1603
  const body = await res.json().catch(() => null)
1604
+ if (!connection.valid()) return
1566
1605
  const operation = body?.operation || body?.compact
1567
1606
  if (!operation) return
1607
+ if (operation.startedAt && activeCompaction(sessionId)?.startedAt > Number(operation.startedAt)) return
1568
1608
  const pending = state.pendingCommands[sessionId]
1569
- if (operation.active) {
1609
+ if (operation.active === true) {
1610
+ const terminal = state.compactionTerminals?.[sessionId]
1611
+ if (terminal && Number(operation.startedAt) <= terminal.startedAt) return
1570
1612
  delete state.pendingCommands[sessionId]
1571
1613
  setCompactionStatus(sessionId, { ...operation, source: 'status' })
1572
1614
  } else if (activeCompaction(sessionId) && activeCompaction(sessionId).source !== 'event') {
@@ -1600,18 +1642,29 @@ function ensureCompactionMonitoring() {
1600
1642
  }
1601
1643
  }
1602
1644
 
1603
- function observeCompactionEvent(sessionId, event) {
1604
- if (event?.type === 'compaction/start') {
1605
- setCompactionStatus(sessionId, { active: true, phase: 'running', startedAt: activeCompaction(sessionId)?.startedAt || Date.now(), source: activeCompaction(sessionId)?.source || 'event' })
1606
- } else if (event?.type === 'compaction/end' && activeCompaction(sessionId)?.source === 'event') {
1607
- setCompactionStatus(sessionId, { active: false, phase: 'complete' })
1645
+ function observeCompactionEvent(sessionId, event, meta = {}) {
1646
+ if (!event || !sessionId || !['compaction/start','compaction/end','session/end-seed'].includes(event.type)) return
1647
+ state.compactionSeqs ||= {}; state.compactionBootAt ||= Date.now()
1648
+ const seq = Number(event.seq), previous = activeCompaction(sessionId)
1649
+ if (seq > 0 && seq <= (state.compactionSeqs[sessionId] || 0)) return
1650
+ const id = event.data?.compactionId || ''
1651
+ if (event.type === 'compaction/end' && previous?.compactionId && previous.compactionId !== id) return
1652
+ if (seq > 0) state.compactionSeqs[sessionId] = seq
1653
+ const time = typeof event.time === 'number' ? event.time : Date.parse(event.time)
1654
+ if (event.type === 'compaction/start') {
1655
+ setCompactionStatus(sessionId, { active: true, phase: 'running', compactionId: id,
1656
+ startedAt: previous?.startedAt || (Number.isFinite(time) ? time : Date.now()), source: previous?.source || 'event',
1657
+ notify: meta.replay ? false : previous?.notify || Number.isFinite(time) && time >= state.compactionBootAt })
1658
+ } else {
1659
+ setCompactionStatus(sessionId, { active: false, phase: event.type === 'session/end-seed' ? 'interrupted' : event.data?.error ? 'failed' : 'complete',
1660
+ message: event.data?.error || '', ...(meta.replay || event.type === 'session/end-seed' ? { notify: false } : {}) })
1608
1661
  }
1609
1662
  }
1610
1663
 
1611
- function onSessionEvent(sessionId, event) {
1664
+ function onSessionEvent(sessionId, event, meta = {}) {
1612
1665
  if (!event) return
1613
1666
  const s = state.byId.get(sessionId)
1614
- observeCompactionEvent(sessionId, event)
1667
+ observeCompactionEvent(sessionId, event, meta)
1615
1668
  if (event.type === 'turn/start' || event.type === 'turn/end') {
1616
1669
  noteSessionTurnTime(sessionId, event)
1617
1670
  renderSessions()
@@ -1630,8 +1683,9 @@ function onSessionEvent(sessionId, event) {
1630
1683
 
1631
1684
  /* ---------------- 数据刷新 ---------------- */
1632
1685
  function scheduleRefresh() {
1633
- clearTimeout(state.refreshTimer)
1634
- state.refreshTimer = setTimeout(refreshAll, 700)
1686
+ if (state.refreshTimer) return
1687
+ const connection = captureConnection()
1688
+ state.refreshTimer = setTimeout(() => { state.refreshTimer = null; if (connection.valid()) void refreshAll() }, 700)
1635
1689
  }
1636
1690
 
1637
1691
  async function refreshAll() {
@@ -1681,9 +1735,37 @@ function removeLocalSessionRecord(sessionId) {
1681
1735
  }
1682
1736
 
1683
1737
  function proj(s, key, d) { return s?.projections?.values?.[key] ?? d }
1684
- function openInsights(tab = 'context') {
1685
- window.DshInsights?.open({ tab, connection: captureConnection(), url: apiUrl,
1686
- getSession: () => state.byId.get(state.current), getTitle: () => sessionTitleValue(state.byId.get(state.current)) })
1738
+ function optionalPluginConfig(connection = captureConnection()) {
1739
+ return { connection, valid: connection.valid, url: path => connection.server + path,
1740
+ headers: { authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() } }
1741
+ }
1742
+ function availableInsightTabs(capabilities, session) {
1743
+ const context = capabilities.context
1744
+ return [...(context ? ['context'] : []), ...(capabilities.cost ? ['cost'] : [])]
1745
+ }
1746
+ async function refreshInsightEntry() {
1747
+ const control = $('btn-insights'), id = state.current, connection = captureConnection()
1748
+ if (!control || !id || !connection.token || !window.DshExtensions) { control?.classList.add('hidden'); return }
1749
+ const capabilities = await window.DshExtensions.getCapabilities(optionalPluginConfig(connection))
1750
+ if (!connection.valid() || state.current !== id) return
1751
+ const tabs = availableInsightTabs(capabilities, state.byId.get(id))
1752
+ control.classList.toggle('hidden', !tabs.length)
1753
+ const label = t(tabs.length === 2 ? 'insights.title' : tabs[0] === 'cost' ? 'insights.costTitle' : 'insights.contextTitle')
1754
+ control.textContent = label; control.title = label; control.setAttribute('aria-label', label)
1755
+ }
1756
+ async function openInsights(tab = 'context', fullPage = false) {
1757
+ const connection = captureConnection(), id = state.current
1758
+ const capabilities = await window.DshExtensions.getCapabilities(optionalPluginConfig(connection))
1759
+ if (!connection.valid() || state.current !== id || !id) return
1760
+ const allowedTabs = availableInsightTabs(capabilities, state.byId.get(id))
1761
+ if (!allowedTabs.length) { void refreshInsightEntry(); return }
1762
+ window.DshInsights?.close()
1763
+ const view = fullPage ? getConversationView() : null, wasPaused = view?.paused
1764
+ view?.pause()
1765
+ window.DshInsights?.open({ tab, fullPage, allowedTabs, connection, url: path => connection.server + path,
1766
+ getSession: () => state.byId.get(state.current), getTitle: () => sessionTitleValue(state.byId.get(state.current)),
1767
+ onFullPage: selected => void openInsights(selected, true),
1768
+ onClose: () => { if (view && !wasPaused && connection.valid() && state.current === id) view.resume() } })
1687
1769
  }
1688
1770
  function hydrateSessionProjections(sessionId, projections) {
1689
1771
  const s = state.byId.get(sessionId)
@@ -2446,9 +2528,7 @@ function scheduleReasoningRender() {
2446
2528
  reasoningRenderTimer = setTimeout(() => {
2447
2529
  reasoningRenderTimer = null
2448
2530
  if (!state.current) return
2449
- const box = $('history')
2450
- const nearBottom = box.scrollHeight - box.scrollTop - box.clientHeight < 240
2451
- renderHistory(false, nearBottom ? 'bottom' : 'fixed')
2531
+ renderHistory(false, 'fixed')
2452
2532
  }, 80)
2453
2533
  }
2454
2534
 
@@ -2477,7 +2557,7 @@ function getConversationView() {
2477
2557
  if(!conversationView)conversationView=new window.DshHistory.HistoryView($('history'),{
2478
2558
  html:entry=>eventHtml(entry, {toolNames:state.history.toolNames}),
2479
2559
  older:()=>loadHistory(false),olderLabel:()=>t('history.earlier'),loadingLabel:()=>t('history.loadingEarlier'),live:partialReasoningHtml,
2480
- 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);updateRail(view.domChanged)},
2560
+ 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)},
2481
2561
  scrolled:()=>{updateRail()}
2482
2562
  })
2483
2563
  return conversationView
@@ -2520,12 +2600,13 @@ async function loadHistory(reset = true) {
2520
2600
  const reasoningVersion=history.reasoningVersion||0,hadContent=history.visible.length>0
2521
2601
  history.loading=true
2522
2602
  if(reset){if(hadContent)historySource('syncing');else setSessionRecovery('loading')}
2523
- const payload={sessionId:id,maxMessages:60}
2603
+ const network=window.DshNetwork?.profile() || {historyPageSize:60,readTimeout:45000}
2604
+ const payload={sessionId:id,maxMessages:network.historyPageSize}
2524
2605
  if(!reset&&Number.isFinite(history.minSeq))payload.beforeSeq=history.minSeq
2525
2606
  getConversationView().more.disabled=true
2526
2607
  getConversationView().more.textContent=getConversationView().options.loadingLabel()
2527
2608
  let v
2528
- try{v=await rpc('session.history',payload)}catch(error){
2609
+ try{v=await rpc('session.history',payload,network.readTimeout)}catch(error){
2529
2610
  if(!connection.valid()||state.current!==id||state.history!==history)return
2530
2611
  history.loading=false;history.retryAfter=Date.now()+1500
2531
2612
  if(error.message==='AUTH'){authFailure();return}
@@ -2572,8 +2653,7 @@ function insertLiveEvent(event) {
2572
2653
  return
2573
2654
  }
2574
2655
  h.seqs.add(seq)
2575
- h.visible.push({ seq, event })
2576
- h.visible.sort((a, b) => a.seq - b.seq)
2656
+ window.DshHistory.insertSorted(h.visible, { seq, event })
2577
2657
  trimVisible()
2578
2658
  renderHistory(false, 'fixed')
2579
2659
  scheduleHistoryCacheSave()
@@ -2730,8 +2810,8 @@ function blockHtml(b) {
2730
2810
  if (!b || typeof b !== 'object') return `<p>${esc(String(b))}</p>`
2731
2811
  if ((b.type === 'tool-call' || b.type === 'tool-result') && LS.get('showTools', '1') === '0') return ''
2732
2812
  switch (b.type) {
2733
- case 'text': return `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '') : esc(b.text ?? '')}</div>`
2734
- case 'file': return `<div class="tool">📎 ${esc(b.attachment?.name || b.name || 'file')} <small>${esc(b.attachment?.bytes ?? b.bytes ?? '')} bytes</small></div>`
2813
+ case 'text': return `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '', { fileLinks: true }) : esc(b.text ?? '')}</div>`
2814
+ 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>`
2735
2815
  case 'image': return `<img alt="${t('block.image')}" src="data:${esc(b.mediaType || 'image/png')};base64,${esc(b.data || '')}">`
2736
2816
  case 'thinking':
2737
2817
  case 'reasoning':
@@ -2771,9 +2851,22 @@ function statsHtml(s) {
2771
2851
  return html || '<div class="empty">' + t('stats.empty') + '</div>'
2772
2852
  }
2773
2853
 
2854
+ let sessionSubagentsJob = null
2855
+ async function loadSessionSubagents(sessionId) {
2856
+ if (sessionSubagentsJob?.sessionId === sessionId && sessionSubagentsJob.connection.valid()) return sessionSubagentsJob.promise
2857
+ const connection = captureConnection(), job = { sessionId, connection }
2858
+ job.promise = (async () => {
2859
+ const value = await safeRpc('subagent.list', { parentSessionId: sessionId }, '')
2860
+ return connection.valid() ? value : null
2861
+ })()
2862
+ sessionSubagentsJob = job
2863
+ try { return await job.promise } finally { if (sessionSubagentsJob === job) sessionSubagentsJob = null }
2864
+ }
2774
2865
  let sessionCardsRenderGeneration = 0
2775
2866
  async function renderSessionCards() {
2867
+ const connection = captureConnection()
2776
2868
  window.DshInsights?.update()
2869
+ void refreshInsightEntry()
2777
2870
  const renderGeneration = ++sessionCardsRenderGeneration
2778
2871
  const sessionId = state.current
2779
2872
  const s = state.byId.get(sessionId)
@@ -2824,8 +2917,8 @@ async function renderSessionCards() {
2824
2917
  }))
2825
2918
 
2826
2919
  // 子代理
2827
- const sub = await safeRpc('subagent.list', { parentSessionId: sessionId })
2828
- if (renderGeneration !== sessionCardsRenderGeneration || state.current !== sessionId) return
2920
+ const sub = await loadSessionSubagents(sessionId)
2921
+ if (!connection.valid() || renderGeneration !== sessionCardsRenderGeneration || state.current !== sessionId) return
2829
2922
  if (sub?.entries?.length) {
2830
2923
  const expanded = state.subagentExpandedSession === sessionId
2831
2924
  const toggleLabel = expanded ? t('subagent.collapse') : t('subagent.expand')
@@ -2861,6 +2954,8 @@ function setGoalPhaseLocal(phase) {
2861
2954
  }
2862
2955
 
2863
2956
  async function goalAction(kind) {
2957
+ const connection = captureConnection(), sessionId = state.current, history = state.history
2958
+ const valid = () => connection.valid() && state.current === sessionId && state.history === history
2864
2959
  const s = state.byId.get(state.current)
2865
2960
  const goal = goalOf(s)
2866
2961
  if (!goal) return toast(t('goal.none'))
@@ -2871,8 +2966,8 @@ async function goalAction(kind) {
2871
2966
  if (!method) return
2872
2967
  if (kind === 'clear' && !confirm(t('goal.confirmClear'))) return
2873
2968
  if (kind === 'complete' && !confirm(t('goal.confirmComplete'))) return
2874
- const result = await safeRpc(method, { sessionId: state.current, ref }, t('goal.actionFailed'))
2875
- if (result == null) return
2969
+ const result = await safeRpc(method, { sessionId, ref }, t('goal.actionFailed'))
2970
+ if (result == null || !valid()) return
2876
2971
  if (kind === 'complete') setGoalPhaseLocal('complete')
2877
2972
  if (kind === 'clear') setGoalPhaseLocal('cleared')
2878
2973
  toast(t('goal.actionSubmitted'), 'ok')
@@ -2913,19 +3008,22 @@ function sessionLogExportUrl(sessionId, includeToken = false) {
2913
3008
  }
2914
3009
 
2915
3010
  async function downloadSessionExport(sessionId) {
3011
+ const connection = captureConnection()
2916
3012
  const nativePlatform = !!CAP?.isNativePlatform?.()
2917
3013
  const nativeDownload = !!(nativePlatform && window.NativeFile?.downloadToDownloads)
2918
3014
  if (nativePlatform && !nativeDownload) {
2919
3015
  toast(t('fs.downloadUnsupported'), 'err')
2920
3016
  return
2921
3017
  }
2922
- const url = sessionLogExportUrl(sessionId, !nativeDownload && !!state.server)
3018
+ const pluginOrigin = location.pathname === '/remote' || location.pathname.startsWith('/remote/')
3019
+ const url = sessionLogExportUrl(sessionId, !nativeDownload && (!!state.server || !pluginOrigin))
2923
3020
  const headers = state.token ? { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() } : {}
2924
3021
  try {
2925
3022
  const signal = typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'
2926
3023
  ? AbortSignal.timeout(LONG_RUNNING_SLASH_COMMAND_TIMEOUT_MS)
2927
3024
  : undefined
2928
3025
  const preflight = await fetch(url, { method: 'HEAD', headers, ...(signal ? { signal } : {}) })
3026
+ if (!connection.valid()) return
2929
3027
  if (preflight.status === 401) { authFailure(); return }
2930
3028
  if (!preflight.ok) throw new Error('HTTP ' + preflight.status)
2931
3029
  const filename = sessionLogFilename(sessionId)
@@ -2951,6 +3049,7 @@ async function downloadSessionExport(sessionId) {
2951
3049
  async function runSlashCommand(text) {
2952
3050
  const clean = String(text || '').trim()
2953
3051
  if (!clean.startsWith('/') || !state.current) return false
3052
+ const sessionId = state.current, connection = captureConnection()
2954
3053
  const command = slashCommandName(clean)
2955
3054
  const noFallback = NO_FALLBACK_SLASH_COMMANDS.has(command)
2956
3055
  const longRunning = command === 'export'
@@ -2961,37 +3060,39 @@ async function runSlashCommand(text) {
2961
3060
  const res = await fetch(apiUrl('/remote/api/command'), {
2962
3061
  method: 'POST',
2963
3062
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() },
2964
- body: JSON.stringify({ sessionId: state.current, line: clean }),
3063
+ body: JSON.stringify({ sessionId, line: clean }),
2965
3064
  ...(signal ? { signal } : {})
2966
3065
  })
3066
+ if (!connection.valid()) return true
2967
3067
  if (res.status === 401) { authFailure(); return true }
2968
3068
  if (!res.ok) {
2969
3069
  if (noFallback) toast(t('session.commandTimedOut'), 'err')
2970
3070
  return noFallback
2971
3071
  }
2972
3072
  const data = await res.json().catch(() => null)
3073
+ if (!connection.valid()) return true
2973
3074
  if (data?.ok === false) { toast(data.message || t('send.failed'), 'err'); return true }
2974
3075
  if (data?.ok && data.executed === true) {
2975
3076
  if (data.accepted) {
2976
3077
  if (command === 'compact') {
2977
- setCompactionStatus(state.current, { ...(data.operation || data.compact), active: true, command, source: 'command' })
3078
+ setCompactionStatus(sessionId, { ...(data.operation || data.compact), active: true, command, source: 'command' })
2978
3079
  } else {
2979
- const sessionId = state.current
2980
3080
  state.pendingCommands[sessionId] = command
2981
- setTimeout(() => { if (state.current === sessionId) void refreshCompactionStatus(sessionId) }, 600)
3081
+ setTimeout(() => { if (connection.valid() && state.current === sessionId) void refreshCompactionStatus(sessionId) }, 600)
2982
3082
  }
2983
- } else if (command === 'export') await downloadSessionExport(state.current)
3083
+ } else if (command === 'export') await downloadSessionExport(sessionId)
2984
3084
  else toast(t('send.commandExecuted'), 'ok')
2985
3085
  return true
2986
3086
  }
2987
3087
  } catch (e) {
3088
+ if (!connection.valid() || state.current !== sessionId) return true
2988
3089
  console.error('slash command bridge failed', e)
2989
3090
  if (noFallback) {
2990
3091
  toast(t('session.commandTimedOut'), 'err')
2991
3092
  return true
2992
3093
  }
2993
3094
  }
2994
- return false
3095
+ return !connection.valid() || state.current !== sessionId
2995
3096
  }
2996
3097
 
2997
3098
  function bytesToBase64(bytes) {
@@ -3208,12 +3309,13 @@ async function sendSessionContent(text, images, requestedMode = 'queue') {
3208
3309
  composerSending = true
3209
3310
  const buttons = [$('btn-send'), $('btn-fs-send')].filter(Boolean)
3210
3311
  buttons.forEach(button => { button.disabled = true })
3211
- state.pendingPrompts.add(sessionId)
3312
+ const pendingPrompts = state.pendingPrompts, sessionActivity = state.sessionActivity
3313
+ pendingPrompts.add(sessionId)
3212
3314
  try {
3213
3315
  if (mode === 'steer') setComposerSendFeedback(context, 'send.steerPending', 'pending')
3214
3316
  else { composerSendFeedback.delete(context); renderComposerSend() }
3215
3317
  if (images.length === 0 && clean && await runSlashCommand(clean)) {
3216
- state.sessionActivity.add(sessionId)
3318
+ sessionActivity.add(sessionId)
3217
3319
  return true
3218
3320
  }
3219
3321
  const content = [...await encodeComposerImagesFor(images)]
@@ -3257,7 +3359,7 @@ async function sendSessionContent(text, images, requestedMode = 'queue') {
3257
3359
  }
3258
3360
  return false
3259
3361
  } finally {
3260
- state.pendingPrompts.delete(sessionId)
3362
+ pendingPrompts.delete(sessionId)
3261
3363
  composerSending = false
3262
3364
  buttons.forEach(button => { button.disabled = false })
3263
3365
  renderComposerSend()
@@ -3309,16 +3411,21 @@ function mobileEnterAction() {
3309
3411
 
3310
3412
  async function loadSessionModels() {
3311
3413
  if (!state.current || state.models.loading) return
3312
- state.models.loading = true
3414
+ const connection = captureConnection(), sessionId = state.current, models = state.models
3415
+ const request = models.request = (models.request || 0) + 1
3416
+ const valid = () => connection.valid() && state.current === sessionId && state.models === models && models.request === request
3417
+ models.loading = true
3313
3418
  renderModelMenu()
3314
3419
  try {
3315
- const v = await rpc('session.models', { sessionId: state.current })
3316
- state.models.groups = v.groups || []
3317
- state.models.current = v.current || null
3318
- state.models.failures = v.failures || []
3319
- state.models.loaded = true
3420
+ const v = await rpc('session.models', { sessionId })
3421
+ if (!valid()) return
3422
+ models.groups = v.groups || []
3423
+ models.current = v.current || null
3424
+ models.failures = v.failures || []
3425
+ models.loaded = true
3320
3426
  } catch (e) {
3321
- if (e.message === 'AUTH') { authFailure(); return }
3427
+ if (!valid()) return
3428
+ if (e.message === 'AUTH') { models.loading = false; renderModelMenu(); authFailure(); return }
3322
3429
  toast(t('models.loadFailed', { msg: e.message }), 'err')
3323
3430
  }
3324
3431
  state.models.loading = false
@@ -3391,9 +3498,12 @@ function reasoningEffortOptions(model) {
3391
3498
  async function selectSessionEffort(effortId) {
3392
3499
  const cur = state.models.current
3393
3500
  if (!state.current || !cur) return
3501
+ const connection = captureConnection(), sessionId = state.current, models = state.models
3502
+ const request = models.request = (models.request || 0) + 1
3394
3503
  const v = await safeRpc('session.selectModel', {
3395
- sessionId: state.current, provider: cur.provider, model: cur.model, reasoningEffort: effortId
3504
+ sessionId, provider: cur.provider, model: cur.model, reasoningEffort: effortId
3396
3505
  }, t('models.effortFailed'))
3506
+ if (!connection.valid() || state.current !== sessionId || state.models !== models || models.request !== request) return
3397
3507
  if (v?.selected) {
3398
3508
  state.models.current = v.selected
3399
3509
  renderEffortMenu()
@@ -3403,12 +3513,15 @@ async function selectSessionEffort(effortId) {
3403
3513
 
3404
3514
  async function selectSessionModel(provider, modelId) {
3405
3515
  if (!state.current) return
3516
+ const connection = captureConnection(), sessionId = state.current, models = state.models
3517
+ const request = models.request = (models.request || 0) + 1
3406
3518
  const group = (state.models.groups || []).find(g => g.id === provider)
3407
3519
  const model = (group?.models || []).find(m => m.id === modelId)
3408
- const payload = { sessionId: state.current, provider, model: modelId }
3520
+ const payload = { sessionId, provider, model: modelId }
3409
3521
  const effort = model?.reasoning?.defaultEffort || model?.reasoning?.efforts?.[0]?.id
3410
3522
  if (effort) payload.reasoningEffort = effort
3411
3523
  const v = await safeRpc('session.selectModel', payload, t('models.switchFailed'))
3524
+ if (!connection.valid() || state.current !== sessionId || state.models !== models || models.request !== request) return
3412
3525
  if (v?.selected) {
3413
3526
  state.models.current = v.selected
3414
3527
  renderModelMenu()
@@ -3482,22 +3595,27 @@ function closeNewSessionModal() {
3482
3595
  $('modal-new-session').classList.add('hidden')
3483
3596
  }
3484
3597
  async function createSessionInWorkspace() {
3598
+ if (createSessionInWorkspace.busy) return
3599
+ const connection = captureConnection()
3485
3600
  const workspaceId = $('new-session-workspace').value
3486
3601
  if (!workspaceById(workspaceId)) return toast(t('newSession.chooseWorkspace'), 'err')
3487
3602
  const button = $('new-session-create')
3603
+ createSessionInWorkspace.busy = true
3488
3604
  button.disabled = true
3489
- const v = await safeRpc('session.create', { workspaceId: workspaceId }, t('home.createFailed'))
3490
- button.disabled = false
3491
- if (!v?.sessionId) return
3492
- state.workspaceFilter = workspaceId
3493
- state.fs.workspaceId = workspaceId
3494
- LS.set('workspaceFilterV1', workspaceId)
3495
- LS.set('fsWorkspaceIdV1', workspaceId)
3496
- LS.set('lastNewSessionWorkspaceV1', workspaceId)
3497
- closeNewSessionModal()
3498
- toast(t('home.created'), 'ok')
3499
- await refreshSessions()
3500
- openSession(v.sessionId)
3605
+ try {
3606
+ const v = await safeRpc('session.create', { workspaceId: workspaceId }, t('home.createFailed'))
3607
+ if (!connection.valid() || !v?.sessionId) return
3608
+ state.workspaceFilter = workspaceId
3609
+ state.fs.workspaceId = workspaceId
3610
+ LS.set('workspaceFilterV1', workspaceId)
3611
+ LS.set('fsWorkspaceIdV1', workspaceId)
3612
+ LS.set('lastNewSessionWorkspaceV1', workspaceId)
3613
+ closeNewSessionModal()
3614
+ toast(t('home.created'), 'ok')
3615
+ await refreshSessions()
3616
+ if (!connection.valid()) return
3617
+ openSession(v.sessionId)
3618
+ } finally { createSessionInWorkspace.busy = false; button.disabled = false }
3501
3619
  }
3502
3620
 
3503
3621
  let archivePendingSessionId = null
@@ -3608,7 +3726,7 @@ async function probeOverviewLinks(signal) {
3608
3726
  const controller=new AbortController(),cancel=()=>controller.abort()
3609
3727
  signal.addEventListener('abort',cancel,{once:true});if(signal.aborted)controller.abort()
3610
3728
  timer=setTimeout(cancel,4000)
3611
- const healthRequest=fetch(base+'/health?t='+Date.now(),{signal:controller.signal,cache:'no-store'}).then(async response=>{
3729
+ const healthRequest=fetch(base+'/health?probe=live&t='+Date.now(),{signal:controller.signal,cache:'no-store'}).then(async response=>{
3612
3730
  if(!response.ok)throw Error('health')
3613
3731
  const health=await response.json();if(health?.ok!==true)throw Error('health')
3614
3732
  return health
@@ -3801,18 +3919,21 @@ function renderSessionPending() {
3801
3919
  }
3802
3920
 
3803
3921
  async function approveApproval(id, allow) {
3922
+ const connection = captureConnection()
3804
3923
  const a = state.approvals.find(x => x.approvalId === id)
3805
3924
  if (!a) return
3806
3925
  let ok
3807
3926
  try {
3808
3927
  ok = await respond(a.rpcId, { sessionId: a.sessionId, approvalId: a.approvalId, outcome: allow ? 'allowed-once' : 'rejected' })
3809
3928
  } catch (e) {
3929
+ if (!connection.valid()) return
3810
3930
  if (e.message === 'AUTH') authFailure()
3811
3931
  else toast(t('pending.submitFailed', { msg: e.message || t('fs.networkError') }), 'err')
3812
3932
  return
3813
3933
  }
3934
+ if (!connection.valid()) return
3814
3935
  toast(ok ? (allow ? t('pending.allowed') : t('pending.rejected')) : t('pending.stale'), ok ? 'ok' : 'err')
3815
- state.approvals = state.approvals.filter(x => x.approvalId !== id)
3936
+ state.approvals = state.approvals.filter(x => x.rpcId !== a.rpcId)
3816
3937
  renderPending()
3817
3938
  }
3818
3939
 
@@ -3830,6 +3951,7 @@ function openQuestionModal(q) {
3830
3951
  }
3831
3952
 
3832
3953
  async function submitQuestion() {
3954
+ const connection = captureConnection()
3833
3955
  const q = state.questionModal
3834
3956
  if (!q) return
3835
3957
  const answers = q.questions.map((item, i) => {
@@ -3845,11 +3967,18 @@ async function submitQuestion() {
3845
3967
  try {
3846
3968
  ok = await respond(q.rpcId, { sessionId: q.sessionId, answer: { answers } })
3847
3969
  } catch (e) {
3970
+ if (!connection.valid()) return
3848
3971
  if (e.message === 'AUTH') authFailure()
3849
3972
  else toast(t('question.submitFailed', { msg: e.message || t('fs.networkError') }), 'err')
3850
3973
  return
3851
3974
  }
3852
- if (ok) { toast(t('question.submitted'), 'ok'); $('modal-question').classList.add('hidden'); state.questions = state.questions.filter(x => x.rpcId !== q.rpcId); renderPending() }
3975
+ if (!connection.valid()) return
3976
+ if (ok) {
3977
+ toast(t('question.submitted'), 'ok')
3978
+ if (state.questionModal === q) { $('modal-question').classList.add('hidden'); state.questionModal = null }
3979
+ state.questions = state.questions.filter(x => x.rpcId !== q.rpcId)
3980
+ renderPending()
3981
+ }
3853
3982
  else toast(t('question.stale'), 'err')
3854
3983
  }
3855
3984
 
@@ -4047,7 +4176,6 @@ async function createWorkspace() {
4047
4176
  button.disabled = true
4048
4177
  try {
4049
4178
  const res = await fetch(fsApiUrl('/mkdir', { path: parent, name }), { method: 'POST', headers: fsHeaders() })
4050
- if (!connection.valid()) return
4051
4179
  if (res.status === 401) { fsAuthError(401); return }
4052
4180
  const data = await res.json().catch(() => ({}))
4053
4181
  if (!connection.valid()) return
@@ -4580,6 +4708,7 @@ function bindFsPullRefresh() {
4580
4708
  /* ---------------- goal 编辑 ---------------- */
4581
4709
  function openGoalModal(goal) {
4582
4710
  state.goalEdit = goal
4711
+ state.goalEditContext = { connection: captureConnection(), sessionId: state.current, history: state.history }
4583
4712
  $('goal-body').innerHTML = `
4584
4713
  <div class="kv"><span class="k">phase</span><span class="v">${esc(goal.phase || '?')}</span></div>
4585
4714
  <div class="kv"><span class="k">revision</span><span class="v">${goal.revision ?? '?'}</span></div>
@@ -4591,10 +4720,13 @@ function openGoalModal(goal) {
4591
4720
  async function submitGoalEdit() {
4592
4721
  const goal = state.goalEdit
4593
4722
  if (!goal) return
4723
+ const context = state.goalEditContext
4724
+ const valid = () => context?.connection.valid() && state.current === context.sessionId && state.history === context.history && state.goalEdit === goal
4725
+ if (!valid()) { $('modal-goal').classList.add('hidden'); return }
4594
4726
  const objective = $('goal-edit-text')?.value?.trim()
4595
4727
  if (!objective) return toast(t('goal.cannotEmpty'), 'err')
4596
- const result = await safeRpc('goal.edit', { sessionId: state.current, ref: { id: goal.id, revision: goal.revision }, objective }, t('goal.updateFailed'))
4597
- if (result == null) return
4728
+ const result = await safeRpc('goal.edit', { sessionId: context.sessionId, ref: { id: goal.id, revision: goal.revision }, objective }, t('goal.updateFailed'))
4729
+ if (result == null || !valid()) return
4598
4730
  $('modal-goal').classList.add('hidden')
4599
4731
  toast(t('goal.updated'), 'ok')
4600
4732
  scheduleRefresh()
@@ -5646,6 +5778,7 @@ function modelReasoningError(models) {
5646
5778
  }
5647
5779
 
5648
5780
  async function loadModelSettings(force = false) {
5781
+ const connection = captureConnection()
5649
5782
  if (!state.token) {
5650
5783
  state.modelSettings = { ...state.modelSettings, status: 'error', error: t('token.notSetHint') }
5651
5784
  renderModelSettings()
@@ -5660,6 +5793,7 @@ async function loadModelSettings(force = false) {
5660
5793
  rpc('llm.providers', {}),
5661
5794
  rpc('settings.describe', {})
5662
5795
  ])
5796
+ if (!connection.valid()) return
5663
5797
  const namespaces = Array.isArray(settingsValue?.namespaces) ? settingsValue.namespaces : []
5664
5798
  const providers = Array.isArray(providersValue?.providers) ? providersValue.providers : []
5665
5799
  const rows = providers.map(entry => {
@@ -5681,6 +5815,7 @@ async function loadModelSettings(force = false) {
5681
5815
  let credentials = {}
5682
5816
  if (refs.length > 0) {
5683
5817
  const value = await rpc('credentials.describe', { refs })
5818
+ if (!connection.valid()) return
5684
5819
  credentials = value?.credentials && typeof value.credentials === 'object' ? value.credentials : {}
5685
5820
  }
5686
5821
  state.modelSettings = {
@@ -5694,6 +5829,7 @@ async function loadModelSettings(force = false) {
5694
5829
  }
5695
5830
  state.modelEditor = null
5696
5831
  } catch (error) {
5832
+ if (!connection.valid()) return
5697
5833
  state.modelSettings = { ...state.modelSettings, status: 'error', error: error?.message || String(error) }
5698
5834
  }
5699
5835
  renderModelSettings()
@@ -5897,6 +6033,7 @@ function setModelEditorError(message) {
5897
6033
  async function discoverModelSettings() {
5898
6034
  const editor = state.modelEditor
5899
6035
  if (!editor || editor.busy) return
6036
+ const connection = captureConnection(), valid = () => connection.valid() && state.modelEditor === editor
5900
6037
  collectModelEditorForm()
5901
6038
  editor.busy = true
5902
6039
  editor.error = ''
@@ -5908,17 +6045,19 @@ async function discoverModelSettings() {
5908
6045
  if (editor.api) payload.api = editor.api
5909
6046
  if (editor.keyDraft.trim()) payload.apiKey = editor.keyDraft.trim()
5910
6047
  const value = await rpc('llm.discoverModels', payload)
6048
+ if (!valid()) return
5911
6049
  const found = Array.isArray(value?.models) ? value.models.filter(model => model && typeof model.id === 'string' && model.id.trim()) : []
5912
6050
  if (!found.length) throw new Error(t('settings.modelFetchEmpty'))
5913
6051
  const known = new Set(editor.models.map(model => model.id))
5914
6052
  editor.discovered = found
5915
6053
  editor.discoverySelected = new Set(found.filter(model => !known.has(model.id)).map(model => model.id))
5916
6054
  } catch (error) {
6055
+ if (!valid()) return
5917
6056
  editor.error = t('settings.modelFetchFailed', { msg: error?.message || String(error) })
5918
6057
  } finally {
5919
6058
  editor.busy = false
5920
6059
  }
5921
- renderModelSettings()
6060
+ if (valid()) renderModelSettings()
5922
6061
  }
5923
6062
 
5924
6063
  function addDiscoveredModels() {
@@ -5940,6 +6079,7 @@ function addDiscoveredModels() {
5940
6079
  async function saveModelEditor() {
5941
6080
  const editor = state.modelEditor
5942
6081
  if (!editor || editor.busy) return
6082
+ const connection = captureConnection(), valid = () => connection.valid() && state.modelEditor === editor
5943
6083
  collectModelEditorForm()
5944
6084
  if (!state.modelSettings.writable) return setModelEditorError(t('settings.modelReadOnly'))
5945
6085
  const models = editor.models || []
@@ -5970,6 +6110,7 @@ async function saveModelEditor() {
5970
6110
  })
5971
6111
  if (ops.length) {
5972
6112
  const value = await rpc('settings.mutate', { ns: editor.settingsNs, ops, expectedRevision: editor.namespace.revision })
6113
+ if (!valid()) return
5973
6114
  editor.namespace = value
5974
6115
  }
5975
6116
  if (editor.keyDraft.trim()) {
@@ -5977,10 +6118,13 @@ async function saveModelEditor() {
5977
6118
  } else if (editor.clearKey && editor.keyConfigured && editor.keyRef) {
5978
6119
  await rpc('credentials.unset', { ref: editor.keyRef })
5979
6120
  }
6121
+ if (!valid()) return
5980
6122
  state.modelEditor = null
5981
6123
  await loadModelSettings(true)
6124
+ if (!connection.valid()) return
5982
6125
  toast(t('settings.modelSaved'), 'ok')
5983
6126
  } catch (error) {
6127
+ if (!valid()) return
5984
6128
  editor.error = t('settings.modelSaveFailed', { msg: error?.message || String(error) })
5985
6129
  } finally {
5986
6130
  if (state.modelEditor === editor) {
@@ -6066,10 +6210,12 @@ async function openModelConfigDocument() {
6066
6210
  }
6067
6211
  /* ---------------- 视图切换 ---------------- */
6068
6212
  function showView(id) {
6213
+ if (id !== 'view-session') conversationView?.pause()
6069
6214
  if (id !== 'view-session' && document.body.classList.contains('in-session') && state.current) void archiveEmptySessionOnLeave(state.current)
6070
6215
  for (const v of ['view-home', 'view-files', 'view-session', 'view-activity', 'view-plugins', 'view-settings']) $(v).classList.toggle('hidden', v !== id)
6071
6216
  // 离开会话页必须清掉 in-session, 否则其他页面顶栏被 body 样式隐藏
6072
6217
  document.body.classList.toggle('in-session', id === 'view-session')
6218
+ if (id === 'view-session') conversationView?.resume()
6073
6219
  $('session-actions')?.close()
6074
6220
  $('session-info')?.close()
6075
6221
  document.querySelectorAll('.nav-btn').forEach(b => b.classList.toggle('active', b.dataset.view === id))
@@ -6082,7 +6228,7 @@ function showView(id) {
6082
6228
  loadFs(workspace?.path || null, { silent: true, resetRoot: true })
6083
6229
  }
6084
6230
  if (id === 'view-plugins') openPluginPage()
6085
- else window.DshPluginCenter?.close()
6231
+ else window.DshExtensions?.close()
6086
6232
  if (id === 'view-settings') showSettingsHome()
6087
6233
  if(id==='view-activity')startOverviewDetection(true);else {overviewDetector?.pause();overviewPulse?.pause()}
6088
6234
  }
@@ -7329,6 +7475,7 @@ function bindUi() {
7329
7475
 
7330
7476
  bindRail()
7331
7477
 
7478
+ window.DshChatFiles?.bind($('history'), () => { const c=captureConnection(); return { ...c,sessionId:state.current,cwd:sessionCwd(state.byId.get(state.current)),native:!!CAP?.isNativePlatform?.(),headers:{authorization:'Bearer '+c.token,...clientIdHeaders()},notice:toast } })
7332
7479
  initCustomSelects()
7333
7480
 
7334
7481
  $('btn-history-latest').addEventListener('click',()=>{getConversationView().latest();if(state.history.tailEvicted)void loadHistory(true)})
@@ -7341,11 +7488,14 @@ function applyNativeInsets() {
7341
7488
  const raw = window.NativeUpdate?.getInsets?.()
7342
7489
  if (!raw) return
7343
7490
  const ins = JSON.parse(raw)
7491
+ if (ins.mode === 'overlap') document.documentElement.dataset.nativeInsets = 'overlap'
7344
7492
  document.documentElement.style.setProperty('--native-top', (ins.top || 0) + 'px')
7345
7493
  document.documentElement.style.setProperty('--native-bottom', (ins.bottom || 0) + 'px')
7346
7494
  } catch {}
7347
7495
  }
7348
7496
 
7497
+ window.addEventListener('dsh-native-insets', applyNativeInsets)
7498
+
7349
7499
  async function boot() {
7350
7500
  initToken()
7351
7501
  bindUi()
@@ -7379,15 +7529,18 @@ async function boot() {
7379
7529
 
7380
7530
  document.addEventListener('DOMContentLoaded', boot)
7381
7531
 
7382
- function openPluginPage() {
7532
+ function openPluginPage(route = 'manage') {
7383
7533
  const connection = captureConnection()
7384
7534
  if (!connection.token) {
7385
7535
  $('plugin-page').textContent = '请先在设置中连接 DSH 主机。'
7386
7536
  return
7387
7537
  }
7388
- window.DshPluginCenter.mount({
7538
+ window.DshExtensions.mount({
7539
+ connection, getSession: () => state.byId.get(state.current), getTitle: () => sessionTitleValue(state.byId.get(state.current)),
7540
+ openContext: () => void openInsights('context', true),
7541
+ returnToSession: () => showView('view-session'), scrollTop: () => window.scrollTo(0,0),
7389
7542
  url: path => connection.server + path,
7390
7543
  headers: { authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() },
7391
7544
  valid: connection.valid,
7392
- }, $('plugin-page'))
7545
+ }, $('plugin-page'), route)
7393
7546
  }