dsh-remote-plugin 0.7.2 → 0.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -52,7 +52,7 @@ themeApply()
52
52
 
53
53
  /* ---------------- 状态 ---------------- */
54
54
  function emptyDesktopHistory() {
55
- return { seqs: new Set(), visible: [], hasMore: false, loading: false, minSeq: Infinity, partialReasoning: new Map() }
55
+ return { seqs: new Set(), visible: [], hasMore: false, loading: false, minSeq: Infinity, partialReasoning: new Map(), loaded:false, cached:false, tailEvicted:false }
56
56
  }
57
57
  const state = {
58
58
  token: LS.get('token', ''),
@@ -113,13 +113,30 @@ for (const key of ['server', 'token']) {
113
113
  set(next) {
114
114
  if (next === value) return
115
115
  value = next; connectionGeneration++
116
+ clearTimeout(state.refreshTimer); state.refreshTimer = null
116
117
  state.sessions = []; state.byId.clear(); state.pendingProjections.clear()
118
+ state.hostInfo = null
119
+ if(typeof closeStream==='function'&&typeof streamMeta!=='undefined'){closeStream('mux');closeStream('host')}
117
120
  state.current = null; state.history = emptyDesktopHistory()
121
+ state.models = { loaded: false, loading: false, groups: [], current: null, failures: [] }
122
+ state.approvals = []; state.questions = []; state.questionModal = null
123
+ state.queues = {}; state.queueSteering = {}; state.compactions = {}; state.pendingCommands = {}; state.sessionTurnTimes = {}
124
+ state.sessionActivity = new Set()
118
125
  state.fs.path = null; state.fs.initial = null; state.fs.loaded = false; state.fs.roots = []; state.fs.rootIndex = 0
119
126
  state.workspaces = []; state.archivedIds = []; state.wb = { bound: false, path: '', projects: null }
120
127
  window.DshPluginCenter?.close()
121
128
  window.DshInsights?.close()
122
- if (typeof document !== 'undefined') document.getElementById('modal-workspace')?.classList.add('hidden')
129
+ if(typeof document!=='undefined') {
130
+ const identityGeneration=connectionGeneration
131
+ queueMicrotask(()=>{if(identityGeneration===connectionGeneration&&typeof startOverviewDetection==='function')startOverviewDetection(true,true)})
132
+ document.getElementById('history')?.replaceChildren?.()
133
+ const generation=connectionGeneration
134
+ queueMicrotask(()=>{if(generation!==connectionGeneration)return;if(typeof conversationView!=='undefined')conversationView?.reset();restoreCachedSessionList()})
135
+ }
136
+ if (typeof document !== 'undefined') {
137
+ for (const id of ['modal-workspace', 'modal-workbench', 'modal-question', 'modal-new-session', 'modal-rename']) document.getElementById(id)?.classList.add('hidden')
138
+ if (typeof renderNotifStack === 'function') renderNotifStack()
139
+ }
123
140
  },
124
141
  })
125
142
  }
@@ -280,15 +297,20 @@ function toggleModelMenuDesktop() {
280
297
 
281
298
  async function loadSessionModels() {
282
299
  if (!state.current || state.models.loading) return
283
- state.models.loading = true
300
+ const connection = captureConnection(), sessionId = state.current, models = state.models
301
+ const request = models.request = (models.request || 0) + 1
302
+ const valid = () => connection.valid() && state.current === sessionId && state.models === models && models.request === request
303
+ models.loading = true
284
304
  renderModelMenu()
285
305
  try {
286
- const v = await rpc('session.models', { sessionId: state.current })
287
- state.models.groups = v.groups || []
288
- state.models.current = v.current || null
289
- state.models.failures = v.failures || []
290
- state.models.loaded = true
306
+ const v = await rpc('session.models', { sessionId })
307
+ if (!valid()) return
308
+ models.groups = v.groups || []
309
+ models.current = v.current || null
310
+ models.failures = v.failures || []
311
+ models.loaded = true
291
312
  } catch (e) {
313
+ if (!valid()) return
292
314
  if (e.message === 'AUTH') { toast(t('ds.toastAuth'), 'err'); state.models.loading = false; renderModelMenu(); return }
293
315
  toast(t('models.loadFailed', { msg: e.message }), 'err')
294
316
  }
@@ -302,7 +324,7 @@ function renderModelMenu() {
302
324
  if (state.models.loading) { box.innerHTML = `<div class="ds-model-head">${t('menu.modelTitle')}</div><span>${t('models.loading')}</span>`; return }
303
325
  const groups = state.models.groups || []
304
326
  if (!groups.length) {
305
- box.innerHTML = `<div class="ds-model-head">${t('menu.modelTitle')}</div><span>${(state.models.failures || []).map(f => f.name + ' ' + t('models.unavailable')).join(';') || t('models.none')}</span>`
327
+ box.innerHTML = `<div class="ds-model-head">${t('menu.modelTitle')}</div><span>${(state.models.failures || []).map(f => esc(f.name) + ' ' + t('models.unavailable')).join(';') || t('models.none')}</span>`
306
328
  return
307
329
  }
308
330
  const cur = state.models.current
@@ -354,9 +376,12 @@ function reasoningEffortOptions(model) {
354
376
  async function selectSessionEffort(effortId) {
355
377
  const cur = state.models.current
356
378
  if (!state.current || !cur) return
379
+ const connection = captureConnection(), sessionId = state.current, models = state.models
380
+ const request = models.request = (models.request || 0) + 1
357
381
  const v = await safeRpc('session.selectModel', {
358
- sessionId: state.current, provider: cur.provider, model: cur.model, reasoningEffort: effortId
382
+ sessionId, provider: cur.provider, model: cur.model, reasoningEffort: effortId
359
383
  }, t('models.effortFailed'))
384
+ if (!connection.valid() || state.current !== sessionId || state.models !== models || models.request !== request) return
360
385
  if (v?.selected) {
361
386
  state.models.current = v.selected
362
387
  renderEffortMenu()
@@ -366,12 +391,15 @@ async function selectSessionEffort(effortId) {
366
391
 
367
392
  async function selectSessionModel(provider, modelId) {
368
393
  if (!state.current) return
394
+ const connection = captureConnection(), sessionId = state.current, models = state.models
395
+ const request = models.request = (models.request || 0) + 1
369
396
  const group = (state.models.groups || []).find(g => g.id === provider)
370
397
  const model = (group?.models || []).find(m => m.id === modelId)
371
- const payload = { sessionId: state.current, provider, model: modelId }
398
+ const payload = { sessionId, provider, model: modelId }
372
399
  const effort = model?.reasoning?.defaultEffort || model?.reasoning?.efforts?.[0]?.id
373
400
  if (effort) payload.reasoningEffort = effort
374
401
  const v = await safeRpc('session.selectModel', payload, t('models.switchFailed'))
402
+ if (!connection.valid() || state.current !== sessionId || state.models !== models || models.request !== request) return
375
403
  if (v?.selected) {
376
404
  state.models.current = v.selected
377
405
  renderModelMenu()
@@ -414,6 +442,9 @@ function openFeedbackModal() {
414
442
  $('fb-msg').value = ''
415
443
  $('fb-contact').value = ''
416
444
  $('fb-include-diagnostics').checked = false
445
+ $('fb-include-crashes').checked = false
446
+ $('fb-crash-details').open = false
447
+ void loadCrashPreview()
417
448
  $('modal-feedback').classList.remove('hidden')
418
449
  setTimeout(() => $('fb-msg').focus(), 50)
419
450
  }
@@ -534,11 +565,22 @@ async function checkNotesOnStart() {
534
565
  openNotesModal(info)
535
566
  } catch {}
536
567
  }
568
+ async function loadCrashPreview() {
569
+ const connection=captureConnection(),preview=$('fb-crash-preview')
570
+ preview.textContent=t('ds.feedbackCrashLoading')
571
+ try {
572
+ const response=await fetch(apiUrl('/crash-logs'),{headers:{authorization:'Bearer '+connection.token},signal:AbortSignal.timeout(5000),cache:'no-store'})
573
+ if(!response.ok)throw new Error('unavailable')
574
+ const data=await response.json()
575
+ if(connection.valid())preview.textContent=JSON.stringify(data.upload,null,2)
576
+ }catch{if(connection.valid())preview.textContent=t('ds.feedbackCrashUnavailable')}
577
+ }
537
578
  async function submitFeedback() {
538
579
  const type = document.querySelector('#fb-chips .ds-fb-chip.current')?.dataset.fbType || 'bug'
539
580
  const message = $('fb-msg').value.trim()
540
581
  const contact = $('fb-contact').value.trim()
541
582
  const includeDiagnostics = $('fb-include-diagnostics').checked
583
+ const includeCrashLogs = $('fb-include-crashes').checked
542
584
  if (!message) { toast(t('ds.feedbackEmpty'), 'err'); return }
543
585
  if (message.length > 2000) { toast(t('ds.feedbackTooLong'), 'err'); return }
544
586
  const btn = $('fb-submit')
@@ -547,7 +589,7 @@ async function submitFeedback() {
547
589
  const res = await fetch(apiUrl('/feedback'), {
548
590
  method: 'POST',
549
591
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token },
550
- body: JSON.stringify({ type, message, contact, appVersion: '', includeDiagnostics })
592
+ body: JSON.stringify({ type, message, contact, appVersion: '', includeDiagnostics, includeCrashLogs })
551
593
  })
552
594
  let json = {}
553
595
  try { json = await res.json() } catch {}
@@ -580,14 +622,16 @@ function hideTip() { const tip = $('ds-tip'); if (tip) tip.classList.add('hidden
580
622
  /* ---------------- API ---------------- */
581
623
  function apiUrl(path) { return (state.server || '') + path }
582
624
  let wsTicketPromise = null
625
+ let wsTicketConnection = null
583
626
  async function getWsTicket() {
584
627
  const now = Date.now()
585
628
  if (state.wsTicket.token === state.token && state.wsTicket.server === state.server &&
586
629
  state.wsTicket.value && state.wsTicket.expiresAt > now + 15000) return state.wsTicket.value
587
- if (wsTicketPromise) return wsTicketPromise
630
+ if (wsTicketPromise && wsTicketConnection?.valid()) return wsTicketPromise
631
+ const connection = captureConnection()
588
632
  const token = state.token
589
633
  const server = state.server
590
- wsTicketPromise = (async () => {
634
+ const job = (async () => {
591
635
  if (activeGatewayCapability('wsTicket') === false) throw new Error('ws ticket unsupported')
592
636
  const res = await fetch(apiUrl('/api/ws-ticket'), {
593
637
  method: 'POST',
@@ -595,11 +639,14 @@ async function getWsTicket() {
595
639
  })
596
640
  if (!res.ok) throw new Error('ws ticket HTTP ' + res.status)
597
641
  const data = await res.json()
642
+ if (!connection.valid()) throw new Error('stale ws ticket')
598
643
  if (!data?.ticket || !Number(data.expiresAt)) throw new Error('invalid ws ticket')
599
644
  state.wsTicket = { token, server, value: data.ticket, expiresAt: Number(data.expiresAt) }
600
645
  return data.ticket
601
646
  })()
602
- try { return await wsTicketPromise } finally { wsTicketPromise = null }
647
+ wsTicketPromise = job
648
+ wsTicketConnection = connection
649
+ try { return await job } finally { if (wsTicketPromise === job) { wsTicketPromise = null; wsTicketConnection = null } }
603
650
  }
604
651
  async function rpc(method, payload = {}, timeoutMs = 45000) {
605
652
  const opts = {
@@ -634,7 +681,7 @@ async function respond(rpcId, value) {
634
681
  }
635
682
  async function safeRpc(method, payload, errText) {
636
683
  const connection = captureConnection()
637
- try { return await rpc(method, payload) }
684
+ try { const value = await rpc(method, payload); return connection.valid() ? value : null }
638
685
  catch (e) {
639
686
  if (!connection.valid()) return null
640
687
  if (e.message === 'AUTH') { toast(t('ds.toastAuth'), 'err'); return null }
@@ -643,6 +690,7 @@ async function safeRpc(method, payload, errText) {
643
690
  }
644
691
  }
645
692
  let hostDescribePromise = null
693
+ let hostDescribeConnection = null
646
694
  let hostDescribeRetryTimer = null
647
695
  let hostDescribeFailures = 0
648
696
 
@@ -658,12 +706,13 @@ function scheduleHostDescribeRetryDesktop() {
658
706
 
659
707
  async function refreshHostDescriptionDesktop({ notify = false } = {}) {
660
708
  if (!state.token) return null
661
- if (hostDescribePromise) return hostDescribePromise
662
- const server = state.server
663
- hostDescribePromise = (async () => {
709
+ if (hostDescribePromise && hostDescribeConnection?.valid()) return hostDescribePromise
710
+ const connection = captureConnection()
711
+ hostDescribeConnection = connection
712
+ const job = (async () => {
664
713
  try {
665
714
  const host = await rpc('host.describe', {}, 5000)
666
- if (server !== state.server) return null
715
+ if (!connection.valid()) return null
667
716
  state.hostInfo = host
668
717
  const health = activeGatewayHealth()
669
718
  if (health) health.upstreamReachable = true
@@ -673,17 +722,17 @@ async function refreshHostDescriptionDesktop({ notify = false } = {}) {
673
722
  renderOverviewDesktop()
674
723
  return host
675
724
  } catch (error) {
676
- if (server !== state.server) return null
725
+ if (!connection.valid()) return null
677
726
  hostDescribeFailures++
678
727
  scheduleHostDescribeRetryDesktop()
679
728
  if (notify) toast(error.message === 'AUTH' ? t('ds.toastAuth') : error.message, 'err')
680
729
  return null
681
730
  } finally {
682
- hostDescribePromise = null
683
- if (server !== state.server) scheduleHostDescribeRetryDesktop()
731
+ if (hostDescribePromise === job) { hostDescribePromise = null; hostDescribeConnection = null }
684
732
  }
685
733
  })()
686
- return hostDescribePromise
734
+ hostDescribePromise = job
735
+ return job
687
736
  }
688
737
  function uuid() {
689
738
  try { return crypto.randomUUID() } catch { return 'id-' + Date.now() + '-' + Math.random().toString(36).slice(2) }
@@ -782,7 +831,7 @@ async function pingServer(base) {
782
831
  const ctrl = new AbortController()
783
832
  const timer = setTimeout(() => ctrl.abort(), 3500)
784
833
  try {
785
- const res = await fetch(u + '/health?t=' + Date.now(), { signal: ctrl.signal, cache: 'no-store' })
834
+ const res = await fetch(u + '/health?probe=live&t=' + Date.now(), { signal: ctrl.signal, cache: 'no-store' })
786
835
  if (!res.ok) return Infinity
787
836
  const health = await res.json().catch(() => null)
788
837
  if (health && typeof health === 'object') {
@@ -809,7 +858,10 @@ function dshReachable() {
809
858
  return !!state.hostInfo
810
859
  }
811
860
  async function selectFastestServer({ silent = false, reconnect = true } = {}) {
812
- if (state.selectingServer) return null
861
+ const request = selectFastestServer.request = (selectFastestServer.request || 0) + 1
862
+ const connection = captureConnection(), group = state.activeGroup
863
+ const policy = JSON.stringify([state.autoSelect[group], state.groupActive[group], state.servers])
864
+ const valid = () => connection.valid() && request === selectFastestServer.request && state.activeGroup === group && policy === JSON.stringify([state.autoSelect[group], state.groupActive[group], state.servers])
813
865
  state.selectingServer = true
814
866
  try {
815
867
  if (!silent) toast(t('ds.speedTesting'))
@@ -820,6 +872,7 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
820
872
  let ms = Infinity
821
873
  if (state.autoSelect[state.activeGroup] !== false) {
822
874
  const measured = await Promise.all(candidates.map(async (server) => [server, await pingServer(server.url)]))
875
+ if (!valid()) return null
823
876
  for (const [server, latency] of measured) state.serverLatency[serverKey(server)] = latency
824
877
  best = candidates.filter(server => Number.isFinite(state.serverLatency[serverKey(server)])).sort((a, b) => state.serverLatency[serverKey(a)] - state.serverLatency[serverKey(b)])[0] || null
825
878
  const sameOrigin = best?.url === location.origin && best.origin
@@ -837,6 +890,8 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
837
890
  ms = state.serverLatency[key]
838
891
  }
839
892
  }
893
+ if (!valid()) return null
894
+ if (typeof window !== 'undefined') window.DshNetwork?.observeLatency(ms)
840
895
  renderServers()
841
896
  if (chosen !== state.server || chosenToken !== state.token) {
842
897
  state.hostInfo = null
@@ -860,7 +915,7 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
860
915
  else toast(t('ds.speedAllDown'), 'err')
861
916
  }
862
917
  return chosen
863
- } finally { state.selectingServer = false }
918
+ } finally { if (request === selectFastestServer.request) state.selectingServer = false }
864
919
  }
865
920
 
866
921
  function serverTitle(s) { return s.note || s.url }
@@ -1192,12 +1247,12 @@ function openStreams() {
1192
1247
  function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1193
1248
  if (!state.token) return
1194
1249
  if (ticket === null) {
1195
- const token = state.token
1250
+ const token = state.token, connection=captureConnection()
1196
1251
  void getWsTicket().then((value) => {
1197
- if (state.token === token) openStream(kind, handler, refreshOnOpen, isRestore, value)
1252
+ if (connection.valid()) openStream(kind, handler, refreshOnOpen, isRestore, value)
1198
1253
  }).catch(() => {
1199
1254
  // 兼容旧网关/插件副本: ticket 接口不可用时临时回退旧 token 握手。
1200
- if (state.token === token) openStream(kind, handler, refreshOnOpen, isRestore, '')
1255
+ if (connection.valid()) openStream(kind, handler, refreshOnOpen, isRestore, '')
1201
1256
  })
1202
1257
  return
1203
1258
  }
@@ -1299,43 +1354,46 @@ function enterPollMode() {
1299
1354
  }
1300
1355
 
1301
1356
  function stopPolling() {
1302
- clearInterval(pollTimer)
1303
- pollTimer = null
1304
- clearTimeout(wsRetryTimer)
1305
- wsRetryTimer = null
1357
+ pollInFlight?.stop()
1358
+ pollInFlight = null
1359
+ clearInterval(pollTimer); pollTimer = null
1360
+ clearInterval(wsRetryTimer); wsRetryTimer = null
1306
1361
  }
1307
-
1308
1362
  function startPolling() {
1309
1363
  stopPolling()
1310
1364
  pollTimer = setInterval(pollOnce, 4000)
1311
1365
  wsRetryTimer = setInterval(tryRestoreWs, 30000)
1312
- pollOnce()
1366
+ void pollOnce()
1313
1367
  }
1314
-
1315
- let pollInFlight = false
1368
+ let pollInFlight = null
1316
1369
  async function pollOnce() {
1317
- if (state.streamMode !== 'poll' || pollInFlight) return
1318
- pollInFlight = true
1319
- try {
1320
- await Promise.all([pollKind('mux'), pollKind('host')])
1321
- } finally {
1322
- pollInFlight = false
1323
- }
1370
+ if (state.streamMode !== 'poll') return
1371
+ if (!pollInFlight) pollInFlight = new window.DshNetwork.PollLoop({
1372
+ active: () => state.streamMode === 'poll' && !!state.token,
1373
+ capture: () => { const connection = captureConnection(), cursors = state.pollSeq; return { valid: () => connection.valid() && state.pollSeq === cursors } },
1374
+ read: pollKind
1375
+ })
1376
+ return pollInFlight.tick()
1324
1377
  }
1325
1378
 
1326
- async function pollKind(kind) {
1379
+ async function pollKind(kind, cancellation) {
1327
1380
  if (state.streamMode !== 'poll') return
1381
+ const connection = captureConnection(), cursors = state.pollSeq
1382
+ const valid = () => connection.valid() && state.streamMode === 'poll' && state.pollSeq === cursors && !cancellation?.aborted
1328
1383
  const since = state.pollSeq[kind] || 0
1329
1384
  let res
1330
1385
  try {
1331
- const signal = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(5000) : undefined
1386
+ const timeout = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(window.DshNetwork?.profile().pollTimeout || 30000) : undefined
1387
+ const signal = cancellation && timeout && typeof AbortSignal.any === 'function' ? AbortSignal.any([cancellation, timeout]) : timeout || cancellation
1332
1388
  const headers = { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }
1333
- res = signal ? await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}`), { signal, headers }) : await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}`), { headers })
1389
+ 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 })
1334
1390
  } catch { return }
1391
+ if (!valid()) return
1335
1392
  if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
1336
1393
  if (!res.ok) return
1337
1394
  let data
1338
1395
  try { data = await res.json() } catch { return }
1396
+ if (!valid()) return
1339
1397
  if (!data || !Array.isArray(data.events)) return
1340
1398
  const reset = data.truncated === true || (typeof data.latestSeq === 'number' && data.latestSeq < since)
1341
1399
  if (reset) {
@@ -1351,6 +1409,7 @@ async function pollKind(kind) {
1351
1409
  else onHostFrame(item.event)
1352
1410
  }
1353
1411
  }
1412
+ return data.waitSupported === true ? 100 : 4000
1354
1413
  }
1355
1414
 
1356
1415
  function tryRestoreWs() {
@@ -1378,7 +1437,7 @@ window.addEventListener('online', () => {
1378
1437
  document.addEventListener('visibilitychange', () => {
1379
1438
  if (document.visibilityState === 'visible' && state.token &&
1380
1439
  (streams.mux?.readyState !== WebSocket.OPEN || streams.host?.readyState !== WebSocket.OPEN)) {
1381
- openStreams()
1440
+ repairMissingStreams()
1382
1441
  }
1383
1442
  })
1384
1443
 
@@ -1411,7 +1470,7 @@ function onMuxFrame(full) {
1411
1470
  function onHostFrame(full) {
1412
1471
  const f = full.payload
1413
1472
  if (!f) return
1414
- if (['host/session-added', 'host/session-removed', 'host/workspace-changed', 'host/workspace-removed', 'host/workspace-order-changed', 'host/archived-sessions-changed'].includes(f.type)) refreshSessions()
1473
+ if (['host/session-added', 'host/session-removed', 'host/workspace-changed', 'host/workspace-removed', 'host/workspace-order-changed', 'host/archived-sessions-changed'].includes(f.type)) scheduleSessionsRefresh()
1415
1474
  if (f.type === 'host/session-activity') {
1416
1475
  const session = state.byId.get(f.sessionId)
1417
1476
  if (session) { session.updatedAt = Number(f.updatedAt) || Date.now(); renderSessions(); renderOverviewDesktop() }
@@ -1543,7 +1602,7 @@ function applyProjection(sessionId, key, value, seq) {
1543
1602
  window.DshInsights?.update()
1544
1603
  if (['goal', 'todos'].includes(key)) renderSessionCards()
1545
1604
  }
1546
- if (['title', 'goal', 'todos', 'plan', 'sessionListMetadata'].includes(key)) refreshSessions()
1605
+ if (['title', 'goal', 'todos', 'plan', 'sessionListMetadata'].includes(key)) scheduleSessionsRefresh()
1547
1606
  }
1548
1607
  function setSessionRecovery(status, error = '') {
1549
1608
  state.sessionRecovery = { status, error: String(error || '') }
@@ -1585,7 +1644,11 @@ function sessionLabelOf(s) {
1585
1644
  function isTopLevelSession(session) {
1586
1645
  return !!session && !session.parentSessionId && session.origin !== 'subagent'
1587
1646
  }
1588
- function topLevelSessions() { return state.sessions.filter(isTopLevelSession) }
1647
+ // DSH marks sessions created via "new session" but never prompted as blank and hides
1648
+ // them in its own UI; keep the same semantics here so they do not occupy the list,
1649
+ // the workspace tree or the home stats.
1650
+ function isVisibleSession(session) { return isTopLevelSession(session) && !session?.blank }
1651
+ function topLevelSessions() { return state.sessions.filter(isVisibleSession) }
1589
1652
  const GOAL_TERMINAL_PHASES = new Set(['complete', 'cleared'])
1590
1653
  function isGoalTerminal(goal) {
1591
1654
  return !!goal && GOAL_TERMINAL_PHASES.has(goal.phase)
@@ -1620,6 +1683,7 @@ function onSessionEvent(sessionId, event) {
1620
1683
  renderSessions()
1621
1684
  }
1622
1685
  const session = state.byId.get(sessionId)
1686
+ if((event?.type==='session/title'||event?.type==='title')&&event.data?.title&&session){session.projections??={values:{}};session.projections.values??={};session.projections.values.title=event.data.title;if(state.current===sessionId)updateSessionActions()}
1623
1687
  if (event?.type === 'agent/status' && session) {
1624
1688
  session.running = !!event.data?.running
1625
1689
  if (state.current === sessionId) { renderQueue(); updateComposerStatus() }
@@ -1634,16 +1698,23 @@ function onSessionEvent(sessionId, event) {
1634
1698
  const seq = event.seq
1635
1699
  if (seq != null && !h.seqs.has(seq) && shouldShowEvent(event.type, event)) {
1636
1700
  h.seqs.add(seq)
1637
- h.visible.push({ seq, event })
1638
- h.visible.sort((a, b) => a.seq - b.seq)
1701
+ window.DshHistory.insertSorted(h.visible, { seq, event })
1702
+ trimVisible()
1639
1703
  renderHistory()
1704
+ scheduleHistoryCacheSave()
1640
1705
  }
1641
1706
  if (String(event.type || '').startsWith('goal/') || String(event.type || '').startsWith('todo/')) renderSessionCards()
1642
1707
  }
1643
1708
  }
1644
1709
 
1645
1710
  /* ---------------- 会话 ---------------- */
1711
+ function scheduleSessionsRefresh() {
1712
+ if (state.refreshTimer) return
1713
+ const connection = captureConnection()
1714
+ state.refreshTimer = setTimeout(() => { state.refreshTimer = null; if (connection.valid()) void refreshSessions() }, 150)
1715
+ }
1646
1716
  async function refreshSessions() {
1717
+ if(typeof restoreCachedSessionList==='function')restoreCachedSessionList()
1647
1718
  const connection = captureConnection(), request = ++sessionsRequest
1648
1719
  const v = await safeRpc('session.list', {}, '')
1649
1720
  if (!connection.valid() || request !== sessionsRequest) return
@@ -1651,6 +1722,7 @@ async function refreshSessions() {
1651
1722
  state.sessions = v.items || []
1652
1723
  state.byId = new Map(state.sessions.map(s => [s.sessionId, s]))
1653
1724
  applyPendingProjections()
1725
+ try{LS.set(historyCacheScope()+':sessions',JSON.stringify(state.sessions.slice(0,80)))}catch{}
1654
1726
  renderSessions()
1655
1727
  scheduleWorkbenchRefresh()
1656
1728
  renderOverviewDesktop()
@@ -1771,9 +1843,9 @@ function renderSessions() {
1771
1843
  }
1772
1844
 
1773
1845
  const emptySessionCleanup = new Set()
1774
- async function archiveEmptySessionOnLeave(sessionId) {
1775
- const base = state.server
1776
- const protectedSession = () => state.server !== base || state.current !== sessionId
1846
+ async function archiveEmptySessionOnLeave(sessionId, leaving = false) {
1847
+ const base = state.server, connection=captureConnection()
1848
+ const protectedSession = () => !connection.valid() || state.server !== base || (!leaving && state.current !== sessionId)
1777
1849
  || !state.byId.has(sessionId) || state.byId.get(sessionId)?.running
1778
1850
  || state.sessionActivity?.has(sessionId) || state.pendingPrompts?.has(sessionId)
1779
1851
  || (state.queues[sessionId] || []).length > 0
@@ -1794,14 +1866,16 @@ async function archiveEmptySessionOnLeave(sessionId) {
1794
1866
  }
1795
1867
 
1796
1868
  async function openSession(id) {
1797
- if (state.current && state.current !== id) await archiveEmptySessionOnLeave(state.current)
1869
+ if (state.current && state.current !== id) void archiveEmptySessionOnLeave(state.current,true)
1798
1870
  state.current = id
1799
1871
  setSessionRecovery('loading')
1800
1872
  state.history = emptyDesktopHistory()
1873
+ const openingHistory=state.history, openingConnection=captureConnection()
1801
1874
  state.models = { loaded: false, loading: false, groups: [], current: null, failures: [] }
1802
1875
  showView('view-chat')
1803
1876
  $('ds-title').textContent = titleOf(state.byId.get(id)) || t('ds.sessions')
1804
1877
  updateSessionActions()
1878
+ getConversationView().reset()
1805
1879
  $('history').innerHTML = `<div class="ds-empty">${t('ds.historyLoading')}</div>`
1806
1880
  renderSessions()
1807
1881
  renderSessionCards()
@@ -1809,6 +1883,8 @@ async function openSession(id) {
1809
1883
  renderSessionPendingDesktop()
1810
1884
  updateComposerStatus()
1811
1885
  void refreshCompactionStatus(id)
1886
+ await restoreCachedHistory()
1887
+ if(state.current!==id||state.history!==openingHistory||!openingConnection.valid())return
1812
1888
  await loadHistory()
1813
1889
  }
1814
1890
  async function closeSession() {
@@ -1826,53 +1902,113 @@ async function closeSession() {
1826
1902
  updateSessionActions()
1827
1903
  showView('view-sessions')
1828
1904
  }
1829
- async function loadHistory() {
1830
- const connection = captureConnection()
1831
- const id = state.current
1832
- if (!id || state.history.loading) return
1833
- const history = state.history
1834
- const reasoningVersion = history.reasoningVersion || 0
1835
- state.history.loading = true
1836
- setSessionRecovery('loading')
1905
+
1906
+ function restoreCachedSessionList() {
1907
+ if(state.sessions.length)return
1908
+ try{const items=JSON.parse(LS.get(historyCacheScope()+':sessions',''));if(!Array.isArray(items))return;state.sessions=items.filter(item=>typeof item?.sessionId==='string').slice(0,80);state.byId=new Map(state.sessions.map(item=>[item.sessionId,item]));renderSessions()}catch{}
1909
+ }
1910
+
1911
+ let conversationView = null
1912
+ function historyCacheScope() { const hash=new SHA256();hash.update(new TextEncoder().encode(JSON.stringify([state.server||location.origin,state.token])));return 'historyCacheV2:'+hash.hex() }
1913
+ function historySource(value) {
1914
+ state.history.source=value
1915
+ const el=$('history-source')
1916
+ if(el)el.textContent=t(({cache:'ds.historyCached',syncing:'ds.historySyncing',synced:'ds.historySynced',saved:'ds.historySaved',offline:'ds.historyOffline',saveFailed:'ds.historyCacheFailed'})[value]||'ds.historySynced')
1917
+ }
1918
+ function getConversationView() {
1919
+ if(!conversationView)conversationView=new window.DshHistory.HistoryView($('history'),{
1920
+ html:entry=>eventHtml(entry),
1921
+ older:()=>loadHistory(false),olderLabel:()=>t('ds.historyEarlier'),loadingLabel:()=>t('ds.historyLoadingEarlier'),live:partialReasoningHtml,
1922
+ 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);},
1923
+ scrolled:()=>{}
1924
+ })
1925
+ return conversationView
1926
+ }
1927
+ function scheduleHistoryCacheSave() {
1928
+ clearTimeout(scheduleHistoryCacheSave._t)
1929
+ const connection=captureConnection(),id=state.current,history=state.history,scope=historyCacheScope()
1930
+ scheduleHistoryCacheSave._t=setTimeout(()=>{if(connection.valid()&&state.current===id&&state.history===history)void saveHistoryCache(scope,id,history)},500)
1931
+ }
1932
+ async function saveHistoryCache(scope=historyCacheScope(),id=state.current,history=state.history) {
1933
+ if(!id||!history.visible.length||history.tailEvicted)return
1934
+ const saved=await window.DshHistory.cacheSave(scope,id,{title:titleOf(state.byId.get(id)),events:history.visible.slice(-250),minSeq:history.visible.slice(-250)[0]?.seq??history.minSeq,hasMore:history.hasMore||history.visible.length>250,partialReasoning:[...history.partialReasoning.values()]})
1935
+ if(!saved&&state.current===id&&state.history===history&&scope===historyCacheScope())historySource('saveFailed')
1936
+ if(saved&&state.current===id&&state.history===history&&scope===historyCacheScope()&&['synced','saveFailed'].includes(history.source))historySource('saved')
1937
+ }
1938
+ async function restoreCachedHistory() {
1939
+ const connection=captureConnection(),id=state.current,history=state.history,scope=historyCacheScope()
1940
+ if(!id)return false
1941
+ const cached=await window.DshHistory.cacheLoad(scope,id,legacyId=>window.DshHistory.decodeLegacy(LS.get(scope,''),legacyId))
1942
+ if(!connection.valid()||state.current!==id||state.history!==history||!cached?.events?.length)return false
1943
+ history.visible=cached.events.slice(-250).filter(entry=>entry?.seq!=null&&shouldShowEvent(entry.event?.type,entry.event)).sort((a,b)=>a.seq-b.seq)
1944
+ history.seqs=new Set(history.visible.map(entry=>entry.seq));history.loaded=true;history.cached=true;history.hasMore=cached.events.length>250||cached.hasMore!==false;history.minSeq=cached.events.length>250?(history.visible[0]?.seq??Infinity):Number.isFinite(cached.minSeq)?cached.minSeq:history.visible[0]?.seq??Infinity
1945
+ if(cached.title&&!hasSessionTitle(state.byId.get(id)))hydrateSessionProjections(id,{values:{title:cached.title},asOfSeq:0})
1946
+ applyReasoningBaseline(cached.partialReasoning||[]);historySource('cache');setSessionRecovery('cached');renderHistory(true)
1947
+ return true
1948
+ }
1949
+ function trimVisible(direction='tail') {
1950
+ const h=state.history,excess=h.visible.length-5000
1951
+ if(excess<=0)return
1952
+ const older=direction==='older'||conversationView?.reading
1953
+ const removed=older?h.visible.splice(5000):h.visible.splice(0,excess)
1954
+ for(const entry of removed)h.seqs.delete(entry.seq)
1955
+ if(older)h.tailEvicted=true
1956
+ else{h.minSeq=h.visible[0]?.seq??Infinity;h.headEvicted=true;h.hasMore=true}
1957
+ }
1958
+
1959
+ async function loadHistory(reset = true) {
1960
+ const connection=captureConnection(),id=state.current,history=state.history
1961
+ if(!id||history.loading||(!reset&&Date.now()<(history.retryAfter||0)))return
1962
+ const reasoningVersion=history.reasoningVersion||0,hadContent=history.visible.length>0
1963
+ history.loading=true
1964
+ if(reset){if(hadContent)historySource('syncing');else setSessionRecovery('loading')}
1965
+ const network=window.DshNetwork?.profile() || {historyPageSize:60,readTimeout:45000}
1966
+ const payload={sessionId:id,maxMessages:network.historyPageSize}
1967
+ if(!reset&&Number.isFinite(history.minSeq))payload.beforeSeq=history.minSeq
1968
+ getConversationView().more.disabled=true
1969
+ getConversationView().more.textContent=getConversationView().options.loadingLabel()
1837
1970
  let v
1838
- try { v = await rpc('session.history', { sessionId: id, maxMessages: 60 }) }
1839
- catch (e) {
1840
- if (!connection.valid() || state.current !== id || state.history !== history) return
1841
- state.history.loading = false
1842
- if (e.message === 'AUTH') return
1843
- setSessionRecovery('error', e.message)
1844
- $('history').innerHTML = `<div class="ds-empty">${e.message}</div>`
1971
+ try{v=await rpc('session.history',payload,network.readTimeout)}catch(error){
1972
+ if(!connection.valid()||state.current!==id||state.history!==history)return
1973
+ history.loading=false;history.retryAfter=Date.now()+1500
1974
+ if(error.message==='AUTH'){return}
1975
+ if(hadContent){historySource('offline');setSessionRecovery('cached',error.message);renderHistory(false,'fixed');return}
1976
+ setSessionRecovery('error',error.message)
1977
+ $('history').innerHTML='<div class="history-empty">'+esc(error.message)+'</div>'
1978
+ const retry=document.createElement('button');retry.type='button';retry.className='history-page-control';retry.textContent=t('ds.historyRetry');retry.addEventListener('click',()=>{void loadHistory(true)});$('history').append(retry)
1845
1979
  return
1846
1980
  }
1847
- if (!connection.valid() || state.current !== id || state.history !== history) return
1848
- const liveReasoning = (history.reasoningVersion || 0) !== reasoningVersion ? new Map(history.partialReasoning) : null
1849
- hydrateSessionProjections(id, v.projections)
1981
+ if(!connection.valid()||state.current!==id||state.history!==history)return
1982
+ const liveReasoning=(history.reasoningVersion||0)!==reasoningVersion?new Map(history.partialReasoning):null
1983
+ hydrateSessionProjections(id,v.projections);history.loaded=true
1984
+ const incoming=v.events||[],prepared=[]
1850
1985
  for (const entry of v.events || []) {
1851
- const ev = entry?.event
1852
- const seq = ev?.seq
1853
- if (ev?.type === 'turn/start' || ev?.type === 'turn/end') noteSessionTurnTime(id, ev)
1986
+ const ev=entry?.event
1854
1987
  applyReasoningStreamEvent(ev)
1855
- if (seq == null || state.history.seqs.has(seq)) continue
1856
- if (!shouldShowEvent(ev.type, ev)) continue
1857
- state.history.seqs.add(seq)
1858
- state.history.visible.push({ seq, event: ev })
1859
- }
1860
- state.history.visible.sort((a, b) => a.seq - b.seq)
1861
- if (liveReasoning) history.partialReasoning = liveReasoning
1862
- else applyReasoningBaseline(v.partialReasoning)
1863
- state.history.hasMore = !!v.hasMore
1864
- state.history.loading = false
1865
- setSessionRecovery('ready')
1866
- updateSessionActions()
1867
- renderHistory()
1988
+ if(ev?.type==='turn/start'||ev?.type==='turn/end')noteSessionTurnTime(id,ev)
1989
+ if(ev?.seq==null||!shouldShowEvent(ev.type,ev))continue
1990
+ prepared.push({seq:ev.seq,event:ev,view:entry.view})
1991
+ }
1992
+ const rawSeqs=incoming.map(entry=>entry?.event?.seq).filter(Number.isFinite),floor=rawSeqs.length?Math.min(...rawSeqs):Infinity
1993
+ if(reset){const retainedOlder=!!v.hasMore&&history.visible.some(entry=>entry.seq<floor);const ceiling=rawSeqs.length?Math.max(...rawSeqs)+1:Infinity;history.visible=rawSeqs.length?window.DshHistory.reconcile(history.visible,prepared,floor,!!v.hasMore,ceiling):[];history.minSeq=retainedOlder?Math.min(history.minSeq,floor):floor;history.tailEvicted=false}
1994
+ else{history.visible=window.DshHistory.reconcile(history.visible,prepared,floor,true,payload.beforeSeq);history.minSeq=Math.min(history.minSeq,floor)}
1995
+ history.seqs=new Set(history.visible.map(entry=>entry.seq));history.headEvicted=false;trimVisible(reset?'tail':'older')
1996
+ if(liveReasoning)history.partialReasoning=liveReasoning;else applyReasoningBaseline(v.partialReasoning)
1997
+ history.hasMore=(!!v.hasMore||(reset&&history.headEvicted)) && rawSeqs.length>0 && (reset || floor<payload.beforeSeq)
1998
+ history.loading=false;history.cached=false;historySource('synced');setSessionRecovery('ready')
1999
+ updateSessionActions();renderSessionCards()
2000
+ renderHistory(!hadContent,reset?'fixed':'keep')
2001
+
2002
+ scheduleHistoryCacheSave()
1868
2003
  }
1869
2004
 
2005
+
1870
2006
  const INTERESTING_EVENTS = new Set([
1871
2007
  'user/message', 'assistant/message', 'tool/call', 'tool/result',
1872
2008
  'agent/status', 'checkpoint/created', 'compaction/complete', 'compaction/summary',
1873
2009
  'goal/created', 'goal/updated', 'goal/completed', 'goal/cleared',
1874
2010
  'todo/updated', 'plan/updated', 'question/asked', 'question/resolved',
1875
- 'approval/asked', 'approval/resolved', 'session/title', 'title'
2011
+ 'approval/asked', 'approval/resolved'
1876
2012
  ])
1877
2013
  function messageSource(data) {
1878
2014
  const source = data?.source ?? data?.message?.source
@@ -1997,17 +2133,25 @@ function eventHtml(entry) {
1997
2133
  if (type === 'question/asked') return `<div class="ds-tool">❓ ${esc(data.question || '')}</div>`
1998
2134
  return `<div class="ds-tool">${esc(type)}</div>`
1999
2135
  }
2000
- function renderHistory() {
2001
- const box = $('history')
2002
- const items = state.history.visible
2003
- const html = items.map(eventHtml).join('') + partialReasoningHtml()
2004
- box.innerHTML = html || `<div class="ds-empty">${t('ds.historyEmpty')}</div>`
2005
- box.scrollTop = box.scrollHeight
2136
+ function renderHistory(reset=false, mode='auto') {
2137
+ getConversationView().set(state.history.visible,{reset,follow:mode==='bottom',live:partialReasoningHtml(),hasMore:state.history.hasMore,loading:state.history.loading,emptyLabel:t('ds.historyEmpty')})
2006
2138
  }
2007
2139
 
2008
2140
  /* ---------------- 会话信息卡(goal / todo / 子代理) ---------------- */
2141
+ let sessionSubagentsJob = null
2142
+ async function loadSessionSubagents(sessionId) {
2143
+ if (sessionSubagentsJob?.sessionId === sessionId && sessionSubagentsJob.connection.valid()) return sessionSubagentsJob.promise
2144
+ const connection = captureConnection(), job = { sessionId, connection }
2145
+ job.promise = (async () => {
2146
+ const value = await safeRpc('subagent.list', { parentSessionId: sessionId }, '')
2147
+ return connection.valid() ? value : null
2148
+ })()
2149
+ sessionSubagentsJob = job
2150
+ try { return await job.promise } finally { if (sessionSubagentsJob === job) sessionSubagentsJob = null }
2151
+ }
2009
2152
  let sessionCardsRenderGeneration = 0
2010
2153
  async function renderSessionCards() {
2154
+ const connection = captureConnection()
2011
2155
  window.DshInsights?.update()
2012
2156
  $('btn-insights')?.classList.toggle('hidden', !state.current)
2013
2157
  const renderGeneration = ++sessionCardsRenderGeneration
@@ -2056,8 +2200,8 @@ async function renderSessionCards() {
2056
2200
  requestAnimationFrame(() => box.querySelector(`[data-goal-collapse="${collapse ? '0' : '1'}"]`)?.focus())
2057
2201
  }))
2058
2202
 
2059
- const sub = await safeRpc('subagent.list', { parentSessionId: sessionId }, '')
2060
- if (renderGeneration !== sessionCardsRenderGeneration || state.current !== sessionId) return
2203
+ const sub = await loadSessionSubagents(sessionId)
2204
+ if (!connection.valid() || renderGeneration !== sessionCardsRenderGeneration || state.current !== sessionId) return
2061
2205
  if (sub?.entries?.length) {
2062
2206
  const expanded = state.subagentExpandedSession === sessionId
2063
2207
  const toggleLabel = expanded ? t('subagent.collapse') : t('subagent.expand')
@@ -2093,6 +2237,8 @@ function setGoalPhaseLocal(phase) {
2093
2237
  }
2094
2238
 
2095
2239
  async function goalAction(kind) {
2240
+ const connection = captureConnection(), sessionId = state.current, history = state.history
2241
+ const valid = () => connection.valid() && state.current === sessionId && state.history === history
2096
2242
  const s = state.byId.get(state.current)
2097
2243
  const goal = goalOf(s)
2098
2244
  if (!goal) return toast(t('goal.none'), 'err')
@@ -2101,8 +2247,8 @@ async function goalAction(kind) {
2101
2247
  const objective = prompt(t('goal.editPrompt'), goal.objective || '')
2102
2248
  if (objective === null) return
2103
2249
  if (!objective.trim()) return toast(t('goal.cannotEmpty'), 'err')
2104
- const result = await safeRpc('goal.edit', { sessionId: state.current, ref, objective: objective.trim() }, t('goal.updateFailed'))
2105
- if (result == null) return
2250
+ const result = await safeRpc('goal.edit', { sessionId, ref, objective: objective.trim() }, t('goal.updateFailed'))
2251
+ if (result == null || !valid()) return
2106
2252
  toast(t('goal.updated'), 'ok')
2107
2253
  refreshSessions()
2108
2254
  renderSessionCards()
@@ -2113,8 +2259,8 @@ async function goalAction(kind) {
2113
2259
  if (!method) return
2114
2260
  if (kind === 'clear' && !confirm(t('goal.confirmClear'))) return
2115
2261
  if (kind === 'complete' && !confirm(t('goal.confirmComplete'))) return
2116
- const result = await safeRpc(method, { sessionId: state.current, ref }, t('goal.actionFailed'))
2117
- if (result == null) return
2262
+ const result = await safeRpc(method, { sessionId, ref }, t('goal.actionFailed'))
2263
+ if (result == null || !valid()) return
2118
2264
  if (kind === 'complete') setGoalPhaseLocal('complete')
2119
2265
  if (kind === 'clear') setGoalPhaseLocal('cleared')
2120
2266
  toast(t('goal.actionSubmitted'), 'ok')
@@ -2145,16 +2291,18 @@ function sessionLogFilename(sessionId) {
2145
2291
  }
2146
2292
 
2147
2293
  async function downloadSessionExport(sessionId) {
2294
+ const connection = captureConnection()
2148
2295
  const url = new URL(apiUrl('/api/session.export'), location.href)
2149
2296
  url.searchParams.set('sessionId', sessionId)
2150
2297
  url.searchParams.set('includeDescendants', 'true')
2151
- if (state.server && state.token) url.searchParams.set('token', state.token)
2298
+ if (state.token && (state.server || !(location.pathname === '/remote' || location.pathname.startsWith('/remote/')))) url.searchParams.set('token', state.token)
2152
2299
  const headers = state.token ? { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() } : {}
2153
2300
  try {
2154
2301
  const signal = typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'
2155
2302
  ? AbortSignal.timeout(LONG_RUNNING_SLASH_COMMAND_TIMEOUT_MS)
2156
2303
  : undefined
2157
2304
  const preflight = await fetch(url, { method: 'HEAD', headers, ...(signal ? { signal } : {}) })
2305
+ if (!connection.valid()) return
2158
2306
  if (preflight.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
2159
2307
  if (!preflight.ok) throw new Error('HTTP ' + preflight.status)
2160
2308
  const anchor = document.createElement('a')
@@ -2173,6 +2321,7 @@ async function downloadSessionExport(sessionId) {
2173
2321
  async function runSlashCommand(text) {
2174
2322
  const clean = String(text || '').trim()
2175
2323
  if (!clean.startsWith('/') || !state.current) return false
2324
+ const sessionId = state.current, connection = captureConnection()
2176
2325
  const command = slashCommandName(clean)
2177
2326
  const noFallback = NO_FALLBACK_SLASH_COMMANDS.has(command)
2178
2327
  const longRunning = command === 'export'
@@ -2183,59 +2332,74 @@ async function runSlashCommand(text) {
2183
2332
  const res = await fetch(apiUrl('/remote/api/command'), {
2184
2333
  method: 'POST',
2185
2334
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() },
2186
- body: JSON.stringify({ sessionId: state.current, line: clean }),
2335
+ body: JSON.stringify({ sessionId, line: clean }),
2187
2336
  ...(signal ? { signal } : {})
2188
2337
  })
2338
+ if (!connection.valid()) return true
2189
2339
  if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return true }
2190
2340
  if (!res.ok) {
2191
2341
  if (noFallback) toast(t('ds.commandTimedOut'), 'err')
2192
2342
  return noFallback
2193
2343
  }
2194
2344
  const data = await res.json().catch(() => null)
2345
+ if (!connection.valid()) return true
2195
2346
  if (data?.ok === false) return true
2196
2347
  if (data?.ok === true && data.executed === true) {
2197
2348
  if (data.accepted) {
2198
2349
  if (command === 'compact') {
2199
- setCompactionStatus(state.current, { ...(data.operation || data.compact), active: true, command, source: 'command' })
2350
+ setCompactionStatus(sessionId, { ...(data.operation || data.compact), active: true, command, source: 'command' })
2200
2351
  } else {
2201
- const sessionId = state.current
2202
2352
  state.pendingCommands[sessionId] = command
2203
- setTimeout(() => { if (state.current === sessionId) void refreshCompactionStatus(sessionId) }, 600)
2353
+ setTimeout(() => { if (connection.valid() && state.current === sessionId) void refreshCompactionStatus(sessionId) }, 600)
2204
2354
  }
2205
- } else if (command === 'export') await downloadSessionExport(state.current)
2355
+ } else if (command === 'export') await downloadSessionExport(sessionId)
2206
2356
  return true
2207
2357
  }
2208
2358
  } catch (e) {
2359
+ if (!connection.valid() || state.current !== sessionId) return true
2209
2360
  console.error('slash command bridge failed', e)
2210
2361
  if (noFallback) {
2211
2362
  toast(t('ds.commandTimedOut'), 'err')
2212
2363
  return true
2213
2364
  }
2214
2365
  }
2215
- return false
2366
+ return !connection.valid() || state.current !== sessionId
2216
2367
  }
2217
2368
 
2218
2369
  async function sendMessage() {
2219
2370
  const input = $('composer')
2220
- const text = input.value.trim()
2371
+ const originalText = input.value, text = originalText.trim()
2221
2372
  if (!text || !state.current) return
2222
- state.sessionActivity.add(state.current)
2223
- if (await runSlashCommand(text)) { input.value = ''; return }
2224
- input.value = ''
2225
- setSessionRecovery('resuming')
2226
- const v = await safeRpc('session.prompt', {
2227
- sessionId: state.current,
2228
- mode: 'queue',
2229
- content: [{ type: 'text', text }]
2230
- }, '')
2231
- if (v) { setSessionRecovery('ready'); noteSessionTurnTime(state.current, Date.now()); renderSessions(); toast(t('ds.toastSent'), 'ok') }
2232
- else setSessionRecovery('error')
2373
+ const sessionId = state.current, connection = captureConnection(), history = state.history
2374
+ const pending = sendMessage.pending ||= new Set()
2375
+ if (pending.has(history)) return
2376
+ pending.add(history)
2377
+ const valid = () => connection.valid() && state.current === sessionId && state.history === history
2378
+ try {
2379
+ state.sessionActivity.add(sessionId)
2380
+ if (await runSlashCommand(text)) { if (valid() && input.value === originalText) input.value = ''; return }
2381
+ if (!valid()) return
2382
+ setSessionRecovery('resuming')
2383
+ const v = await safeRpc('session.prompt', {
2384
+ sessionId,
2385
+ mode: 'queue',
2386
+ content: [{ type: 'text', text }]
2387
+ }, '')
2388
+ if (!valid()) return
2389
+ if (v?.accepted) {
2390
+ if (input.value === originalText) input.value = ''
2391
+ setSessionRecovery('ready'); noteSessionTurnTime(sessionId, Date.now()); renderSessions(); toast(t('ds.toastSent'), 'ok')
2392
+ }
2393
+ else setSessionRecovery('error')
2394
+ } finally { pending.delete(history) }
2233
2395
  }
2234
2396
 
2235
2397
  async function cancelSession() {
2236
2398
  if (!state.current) return
2237
2399
  if (!confirm(t('ds.sessionStopConfirm'))) return
2238
- const v = await safeRpc('session.cancel', { sessionId: state.current }, t('ds.sessionStopFailed'))
2400
+ const sessionId = state.current, connection = captureConnection()
2401
+ const v = await safeRpc('session.cancel', { sessionId }, t('ds.sessionStopFailed'))
2402
+ if (!connection.valid() || state.current !== sessionId) return
2239
2403
  if (v?.accepted) { setSessionRecovery('ready'); toast(t('ds.sessionStopRequested'), 'ok') }
2240
2404
  }
2241
2405
 
@@ -2255,6 +2419,7 @@ function closeRenameSession() {
2255
2419
  async function confirmRenameSession() {
2256
2420
  const sessionId = renamePendingSessionId
2257
2421
  if (!sessionId) return
2422
+ const connection = captureConnection()
2258
2423
  const title = $('rename-session-input').value.trim()
2259
2424
  if (!title) return toast(t('ds.sessionRenameEmpty'), 'err')
2260
2425
  const button = $('rename-confirm')
@@ -2262,6 +2427,7 @@ async function confirmRenameSession() {
2262
2427
  setSessionRecovery('resuming')
2263
2428
  try {
2264
2429
  const value = await safeRpc('session.rename', { sessionId, title }, t('ds.sessionRenameFailed'))
2430
+ if (!connection.valid() || renamePendingSessionId !== sessionId) return
2265
2431
  if (value == null) { setSessionRecovery('error'); return }
2266
2432
  if (value.title) applyProjection(sessionId, 'title', value.title, value.seq)
2267
2433
  closeRenameSession()
@@ -2276,11 +2442,12 @@ async function confirmRenameSession() {
2276
2442
  async function archiveCurrentSession() {
2277
2443
  const sessionId = state.current
2278
2444
  if (!sessionId || !confirm(t('ds.sessionArchiveConfirm'))) return
2445
+ const connection = captureConnection()
2279
2446
  const value = await safeRpc('workspace.archiveSession', { sessionId }, t('ds.toastOpFailed'))
2280
- if (!value) return
2447
+ if (!value || !connection.valid()) return
2281
2448
  if (Array.isArray(value.archivedSessionIds)) state.archivedIds = value.archivedSessionIds
2282
2449
  toast(t('ds.sessionArchived'), 'ok')
2283
- closeSession()
2450
+ if (state.current === sessionId) await closeSession()
2284
2451
  await refreshSessions()
2285
2452
  }
2286
2453
 
@@ -2420,18 +2587,21 @@ function renderNotifStack() {
2420
2587
  renderOverviewDesktop()
2421
2588
  }
2422
2589
  async function approveApproval(id, allow) {
2590
+ const connection = captureConnection()
2423
2591
  const a = state.approvals.find(x => x.approvalId === id)
2424
2592
  if (!a) return
2425
2593
  let ok
2426
2594
  try {
2427
2595
  ok = await respond(a.rpcId, { sessionId: a.sessionId, approvalId: a.approvalId, outcome: allow ? 'allowed-once' : 'rejected' })
2428
2596
  } catch (e) {
2597
+ if (!connection.valid()) return
2429
2598
  if (e.message === 'AUTH') toast(t('ds.toastAuth'), 'err')
2430
2599
  else toast(t('ds.pendingSubmitFailed', { msg: e.message || t('ds.feedbackNetworkError') }), 'err')
2431
2600
  return
2432
2601
  }
2602
+ if (!connection.valid()) return
2433
2603
  toast(ok ? (allow ? t('ds.allowed') : t('ds.rejected')) : t('ds.stale'), ok ? 'ok' : 'err')
2434
- state.approvals = state.approvals.filter(x => x.approvalId !== id)
2604
+ state.approvals = state.approvals.filter(x => x.rpcId !== a.rpcId)
2435
2605
  renderNotifStack()
2436
2606
  }
2437
2607
  function openQuestionModal(q) {
@@ -2447,6 +2617,7 @@ function openQuestionModal(q) {
2447
2617
  $('modal-question').classList.remove('hidden')
2448
2618
  }
2449
2619
  async function submitQuestion() {
2620
+ const connection = captureConnection()
2450
2621
  const q = state.questionModal
2451
2622
  if (!q) return
2452
2623
  const answers = q.questions.map((item, i) => {
@@ -2462,13 +2633,15 @@ async function submitQuestion() {
2462
2633
  try {
2463
2634
  ok = await respond(q.rpcId, { sessionId: q.sessionId, answer: { answers } })
2464
2635
  } catch (e) {
2636
+ if (!connection.valid()) return
2465
2637
  if (e.message === 'AUTH') toast(t('ds.toastAuth'), 'err')
2466
2638
  else toast(t('ds.pendingSubmitFailed', { msg: e.message || t('ds.feedbackNetworkError') }), 'err')
2467
2639
  return
2468
2640
  }
2641
+ if (!connection.valid()) return
2469
2642
  if (ok) {
2470
2643
  toast(t('ds.questionSubmitted'), 'ok')
2471
- $('modal-question').classList.add('hidden')
2644
+ if (state.questionModal === q) { $('modal-question').classList.add('hidden'); state.questionModal = null }
2472
2645
  state.questions = state.questions.filter(x => x.rpcId !== q.rpcId)
2473
2646
  renderNotifStack()
2474
2647
  } else toast(t('ds.stale'), 'err')
@@ -2888,7 +3061,7 @@ function renderWorkbench() {
2888
3061
  let html = `<div class="ds-wb-panel-title">${esc(t('wb.projects'))}</div>`
2889
3062
  html += projects.length ? projects.map(w => {
2890
3063
  const id = String(w.workspaceId || '')
2891
- const sessions = orderedWorkspaceSessions(id, (w.sessionIds || []).map(sid => state.byId.get(sid)).filter(isTopLevelSession).filter(s => !archivedSet.has(s.sessionId)).sort((a, b) => sessionSortTime(b) - sessionSortTime(a)))
3064
+ const sessions = orderedWorkspaceSessions(id, (w.sessionIds || []).map(sid => state.byId.get(sid)).filter(isVisibleSession).filter(s => !archivedSet.has(s.sessionId)).sort((a, b) => sessionSortTime(b) - sessionSortTime(a)))
2892
3065
  const open = state.wb.open === id
2893
3066
  return `<div class="ds-wb-project ${open ? 'open' : ''}" data-wb-project="${esc(id)}" data-motion-key="${esc(id)}">
2894
3067
  <button type="button" class="ds-wb-project-head" data-wb-head="${esc(id)}">
@@ -2952,6 +3125,7 @@ async function openNewSessionModal() {
2952
3125
  function closeNewSessionModal() { $('modal-new-session').classList.add('hidden') }
2953
3126
  async function createSessionInWorkspace() {
2954
3127
  if (createSessionInWorkspace.busy) return
3128
+ const connection = captureConnection()
2955
3129
  const workspaceId = $('new-session-workspace').value
2956
3130
  if (!workspaceById(workspaceId)) return toast(t('ds.newSessionChooseWorkspace'), 'err')
2957
3131
  createSessionInWorkspace.busy = true
@@ -2959,10 +3133,11 @@ async function createSessionInWorkspace() {
2959
3133
  button.disabled = true
2960
3134
  try {
2961
3135
  const value = await safeRpc('session.create', { workspaceId }, '')
2962
- if (!value?.sessionId) return
3136
+ if (!connection.valid() || !value?.sessionId) return
2963
3137
  LS.set('lastNewSessionWorkspaceV1', workspaceId)
2964
3138
  closeNewSessionModal()
2965
3139
  await refreshSessions()
3140
+ if (!connection.valid()) return
2966
3141
  openSession(value.sessionId)
2967
3142
  } finally {
2968
3143
  createSessionInWorkspace.busy = false
@@ -2977,8 +3152,10 @@ function openWorkbenchModal() {
2977
3152
  wbFsLoad(null)
2978
3153
  setTimeout(() => $('wb-path-input').focus(), 50)
2979
3154
  }
2980
- function closeWorkbenchModal() { $('modal-workbench').classList.add('hidden') }
3155
+ function closeWorkbenchModal() { wbFs.request = (wbFs.request || 0) + 1; $('modal-workbench').classList.add('hidden') }
2981
3156
  async function wbFsLoad(dir) {
3157
+ const connection = captureConnection(), request = wbFs.request = (wbFs.request || 0) + 1
3158
+ const valid = () => connection.valid() && request === wbFs.request
2982
3159
  const box = $('wb-fs-list')
2983
3160
  const target = dir ?? wbFs.path ?? ''
2984
3161
  box.innerHTML = `<div class="ds-empty">${esc(t('ds.loading'))}</div>`
@@ -2986,6 +3163,7 @@ async function wbFsLoad(dir) {
2986
3163
  try {
2987
3164
  const res = await fetch(fsApiUrl('/list', target ? { path: target } : {}), { headers: fsHeaders() })
2988
3165
  const data = await res.json().catch(() => ({}))
3166
+ if (!valid()) return
2989
3167
  if (!res.ok || !Array.isArray(data.entries)) throw new Error(data.error || ('HTTP ' + res.status))
2990
3168
  wbFs.path = data.path
2991
3169
  if (!wbFs.initial) wbFs.initial = data.path
@@ -2998,6 +3176,7 @@ async function wbFsLoad(dir) {
2998
3176
  box.querySelectorAll('[data-wb-dir]').forEach(row => row.addEventListener('click', e => { if (!e.target.closest('[data-wb-select]')) wbFsLoad(row.dataset.wbDir) }))
2999
3177
  box.querySelectorAll('[data-wb-select]').forEach(button => button.addEventListener('click', () => bindWorkbench(button.dataset.wbSelect)))
3000
3178
  } catch (e) {
3179
+ if (!valid()) return
3001
3180
  $('wb-fs-path').textContent = target || '~'
3002
3181
  box.innerHTML = `<div class="ds-empty">${esc(e.message || t('ds.toastConnFailed'))}</div>`
3003
3182
  }
@@ -3009,38 +3188,49 @@ function wbFsUp() {
3009
3188
  }
3010
3189
  }
3011
3190
  async function bindWorkbench(rawPath) {
3191
+ const connection = captureConnection()
3012
3192
  const value = String(rawPath || '').trim()
3013
3193
  if (!value) return toast(t('wb.pathEmpty'), 'err')
3014
3194
  try {
3015
3195
  const wb = await wbGateway('POST', '/workbench/bind', { path: value })
3196
+ if (!connection.valid()) return
3016
3197
  state.wb = { bound: true, path: wb.path || value, title: wb.title || '', expanded: true, projects: null, open: null, apiMissing: false }
3017
3198
  const paths = [state.wb.path]
3018
3199
  try {
3019
3200
  const res = await fetch(fsApiUrl('/list', { path: state.wb.path }), { headers: fsHeaders() })
3020
3201
  const data = await res.json().catch(() => ({}))
3202
+ if (!connection.valid()) return
3021
3203
  for (const e of data.entries || []) if (e.type === 'dir') paths.push(wbJoin(state.wb.path, e.name))
3022
3204
  } catch {}
3023
3205
  for (const projectPath of paths) {
3206
+ if (!connection.valid()) return
3024
3207
  try { await rpc('workspace.create', { path: projectPath }) } catch {}
3025
3208
  }
3209
+ if (!connection.valid()) return
3026
3210
  closeWorkbenchModal()
3027
3211
  await refreshWorkbench({ silent: true })
3212
+ if (!connection.valid()) return
3028
3213
  await refreshSessions()
3214
+ if (!connection.valid()) return
3029
3215
  toast(t('wb.boundOk', { path: state.wb.path }), 'ok')
3030
3216
  } catch (e) {
3217
+ if (!connection.valid()) return
3031
3218
  if (e.message === 'AUTH') return toast(t('ds.toastAuth'), 'err')
3032
3219
  toast(t('wb.bindFailed', { msg: e.message }), 'err')
3033
3220
  }
3034
3221
  }
3035
3222
  async function unbindWorkbench() {
3036
3223
  if (!confirm(t('wb.unbindConfirm'))) return
3224
+ const connection = captureConnection()
3037
3225
  try {
3038
3226
  await wbGateway('POST', '/workbench/unbind')
3227
+ if (!connection.valid()) return
3039
3228
  state.wb = { bound: false, path: '', title: '', expanded: false, projects: null, open: null, apiMissing: false }
3040
3229
  renderWorkbench()
3041
3230
  renderSessions()
3042
3231
  toast(t('wb.unboundOk'), 'ok')
3043
3232
  } catch (e) {
3233
+ if (!connection.valid()) return
3044
3234
  if (e.message === 'AUTH') return toast(t('ds.toastAuth'), 'err')
3045
3235
  toast(t('wb.unbindFailed', { msg: e.message }), 'err')
3046
3236
  }
@@ -3133,35 +3323,88 @@ function renderStats(days) {
3133
3323
  }
3134
3324
 
3135
3325
  /* ---------------- 视图与连接状态 ---------------- */
3326
+ let overviewDetector = null
3327
+ let overviewPulse = null
3328
+ function setOverviewText(id,value){const node=$(id);if(overviewPulse)overviewPulse.text(node,value);else if(node)node.textContent=value}
3329
+ let overviewStarting = true
3330
+ function overviewChecks() {
3331
+ const confirmed=overviewDetector?.model.gateway===true,health=activeGatewayHealth()
3332
+ return {
3333
+ gateway: !!state.token && (!!state.server || /^https?:$/.test(location.protocol)) && confirmed,
3334
+ dsh: dshReachable() && confirmed,
3335
+ mux: !!state.streamsOk?.mux && confirmed && health?.events?.mux?.connected!==false,
3336
+ host: !!state.streamsOk?.host && confirmed && health?.events?.host?.connected!==false
3337
+ }
3338
+ }
3339
+ function repairMissingStreams() {
3340
+ if(!state.token||!navigator.onLine||state.selectingServer||overviewStarting)return
3341
+ if(state.streamMode==='poll'){tryRestoreWs();return}
3342
+ for(const [kind,handler,refresh] of [['mux',onMuxFrame,true],['host',onHostFrame,false]]) {
3343
+ const ws=streams[kind]
3344
+ if((!ws||ws.readyState===WebSocket.CLOSED)&&!streamMeta[kind].retryTimer)openStream(kind,handler,refresh)
3345
+ }
3346
+ }
3347
+ async function probeOverviewLinks(signal) {
3348
+ const connection=captureConnection(),base=String(connection.server||location.origin).replace(/\/+$/,'')
3349
+ let timer
3350
+ const controller=new AbortController(),cancel=()=>controller.abort()
3351
+ signal.addEventListener('abort',cancel,{once:true});if(signal.aborted)controller.abort()
3352
+ timer=setTimeout(cancel,4000)
3353
+ const healthRequest=fetch(base+'/health?probe=live&t='+Date.now(),{signal:controller.signal,cache:'no-store'}).then(async response=>{
3354
+ if(!response.ok)throw Error('health')
3355
+ const health=await response.json();if(health?.ok!==true)throw Error('health')
3356
+ return health
3357
+ }).catch(()=>null).finally(()=>{clearTimeout(timer);signal.removeEventListener('abort',cancel)})
3358
+ const [health,host]=await Promise.all([healthRequest,refreshHostDescriptionDesktop()])
3359
+ if(!connection.valid()||signal.aborted)throw Error('stale check')
3360
+ if(health){if(host)health.upstreamReachable=true;state.gatewayHealth[base]=health}
3361
+ else delete state.gatewayHealth[base]
3362
+ return {gateway:!!health}
3363
+ }
3364
+ function startOverviewDetection(force=false,identityChanged=false) {
3365
+ if(identityChanged)overviewDetector?.pause()
3366
+ if(!window.DshLinkCheck)return
3367
+ if(!overviewDetector)overviewDetector=new window.DshLinkCheck.LinkCheck({
3368
+ active:()=>document.visibilityState==='visible'&&!$('view-overview').classList.contains('hidden'),
3369
+ configured:()=>!!state.token&&(!!state.server||/^https?:$/.test(location.protocol)),online:()=>navigator.onLine,
3370
+ snapshot:overviewChecks,repair:repairMissingStreams,probe:probeOverviewLinks,changed:renderOverviewDesktop
3371
+ })
3372
+ overviewDetector.start(force)
3373
+ }
3374
+ window.addEventListener('online',()=>startOverviewDetection(true))
3375
+ window.addEventListener('offline',()=>startOverviewDetection(true))
3376
+ document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible')startOverviewDetection(true);else {overviewDetector?.pause();overviewPulse?.pause()}})
3377
+
3136
3378
  function renderOverviewDesktop() {
3137
3379
  const ring = $('ds-overview-pulse-ring')
3138
3380
  if (!ring) return
3139
- const checks = {
3140
- // 桌面独立页面默认使用当前 origin,state.server 为空不代表网关离线。
3141
- gateway: !!state.token && (!!state.server || /^https?:$/.test(location.protocol)),
3142
- dsh: dshReachable(),
3143
- mux: !!state.streamsOk?.mux,
3144
- host: !!state.streamsOk?.host
3145
- }
3381
+ const checks = overviewChecks()
3382
+ const detection=overviewDetector?.model,checking=detection?.phase==='checking'||(detection?.phase==='degraded'&&detection?.probing===true)
3146
3383
  const online = Object.values(checks).filter(Boolean).length
3384
+ $('ds-overview-refresh').disabled=detection?.probing===true
3147
3385
  const status = online === 4 ? 'Nominal' : online > 0 ? 'Degraded' : 'Offline'
3148
3386
  const pulseCard = document.querySelector('.ds-overview-pulse-card')
3149
3387
  if (pulseCard) {
3388
+ if(!overviewPulse&&window.DshLinkCheck?.PulseVisual)overviewPulse=new window.DshLinkCheck.PulseVisual({card:pulseCard,active:()=>document.visibilityState==='visible'&&!$('view-overview').classList.contains('hidden')})
3389
+ overviewPulse?.setChecking(checking)
3390
+ overviewPulse?.setLinks(checks)
3150
3391
  pulseCard.classList.remove('status-nominal', 'status-degraded', 'status-offline')
3392
+ pulseCard.classList.toggle('status-checking',checking)
3393
+ pulseCard.setAttribute('aria-busy',String(checking))
3151
3394
  pulseCard.classList.add('status-' + status.toLowerCase())
3152
3395
  }
3153
- ring.style.setProperty('--pulse-pct', `${online / 4 * 100}%`)
3154
- $('ds-overview-health').textContent = online === 4 ? t('ds.live') : online ? `${online}/4` : t('ds.offlineCore')
3155
- $('ds-overview-health-caption').textContent = online === 4 ? t('ds.allLinked') : online ? t('ds.components', { n: online }) : t('ds.offlineShort')
3156
- $('ds-overview-status').textContent = t(`ds.system${status}`)
3157
- $('ds-overview-status-desc').textContent = t('ds.components', { n: online })
3396
+ setOverviewText('ds-overview-health',checking ? t('ds.checking') : online === 4 ? t('ds.live') : online ? `${online}/4` : t('ds.offlineCore'))
3397
+ setOverviewText('ds-overview-health-caption',checking ? `${online}/4` : online === 4 ? t('ds.allLinked') : online ? t('ds.confirmedShort') : t('ds.offlineShort'))
3398
+ setOverviewText('ds-overview-status',checking ? t('ds.checking') : t(`ds.system${status}`))
3399
+ setOverviewText('ds-overview-status-desc',checking ? t('ds.autoChecking',{n:online}) : detection?.phase==='degraded' ? t('ds.autoRetry',{n:online}) : t('ds.components',{n:online}))
3158
3400
  for (const [name, ok] of Object.entries(checks)) {
3159
3401
  const item = document.querySelector(`[data-ds-overview-link="${name}"]`)
3160
3402
  if (!item) continue
3161
3403
  item.classList.toggle('ok', ok)
3162
- item.classList.toggle('off', !ok)
3404
+ item.classList.toggle('off', !ok&&!checking)
3405
+ item.classList.toggle('pending',!ok&&checking)
3163
3406
  const value = item.querySelector('b')
3164
- if (value) value.textContent = ok ? t('ds.online') : t('ds.offlineShort')
3407
+ if (value) setOverviewText(value.id || (value.id=`ds-overview-link-${name}`), ok ? t('ds.online') : checking ? t('ds.checkingShort') : t('ds.offlineShort'))
3165
3408
  }
3166
3409
 
3167
3410
  const pending = [
@@ -3233,19 +3476,28 @@ function setMobileSidebar(open) {
3233
3476
  $('ds-app')?.classList.toggle('mobile-nav-open', visible)
3234
3477
  }
3235
3478
 
3479
+ function openDesktopPlugins() {
3480
+ const connection=captureConnection()
3481
+ if(!connection.token){$('desktop-plugin-page').textContent=t('ds.toastAuth');return}
3482
+ window.DshPluginCenter.mount({url:path=>connection.server+path,headers:{authorization:'Bearer '+connection.token,'x-dsh-remote-client':'web',...clientIdHeaders()},valid:connection.valid},$('desktop-plugin-page'))
3483
+ }
3484
+
3236
3485
  function showView(id) {
3237
3486
  if (state.view === 'view-chat' && id !== 'view-chat' && state.current) void archiveEmptySessionOnLeave(state.current)
3238
3487
  state.view = id
3239
- for (const v of ['view-overview', 'view-sessions', 'view-chat', 'view-files', 'view-settings']) $(v).classList.toggle('hidden', v !== id)
3488
+ for (const v of ['view-overview', 'view-sessions', 'view-chat', 'view-files', 'view-plugins', 'view-settings']) $(v).classList.toggle('hidden', v !== id)
3240
3489
  document.querySelectorAll('.ds-nav-item').forEach(b => b.classList.toggle('active', b.dataset.view === id))
3241
3490
  if (narrowSidebarQuery.matches) setMobileSidebar(false)
3242
3491
  window.DshMotion?.view($(id))
3243
- const titles = { 'view-overview': 'ds.overview', 'view-sessions': 'ds.sessions', 'view-chat': 'ds.sessions', 'view-files': 'ds.files', 'view-settings': 'ds.settings' }
3492
+ const titles = { 'view-overview': 'ds.overview', 'view-sessions': 'ds.sessions', 'view-chat': 'ds.sessions', 'view-files': 'ds.files', 'view-settings': 'ds.settings', 'view-plugins': 'ds.plugins' }
3244
3493
  if (id === 'view-chat') { const s = state.byId.get(state.current); $('ds-title').textContent = s ? titleOf(s) : t('ds.sessions') }
3245
3494
  else $('ds-title').textContent = t(titles[id])
3246
- if (id === 'view-overview') renderOverviewDesktop()
3495
+ if (id === 'view-overview') {startOverviewDetection(true);renderOverviewDesktop()}
3496
+ else {overviewDetector?.pause();overviewPulse?.pause()}
3247
3497
  if (id === 'view-files' && !state.fs.loaded) loadFs(null, true)
3248
3498
  if (id === 'view-settings') showSettingsHome()
3499
+ if (id === 'view-plugins') openDesktopPlugins()
3500
+ else window.DshPluginCenter?.close()
3249
3501
  updateSessionActions()
3250
3502
  }
3251
3503
 
@@ -3254,9 +3506,14 @@ function updateSessionActions() {
3254
3506
  $('btn-rename-session')?.classList.toggle('hidden', !active)
3255
3507
  $('btn-archive-session')?.classList.toggle('hidden', !active || state.archivedIds.includes(state.current))
3256
3508
  $('ds-session-status')?.classList.toggle('hidden', !active || !recoveryLabel())
3509
+ if (!active) $('ds-workspace')?.classList.add('hidden')
3257
3510
  if (active) {
3258
3511
  const s = state.byId.get(state.current)
3259
3512
  $('ds-title').textContent = s ? titleOf(s) : t('ds.sessions')
3513
+ const workspace = s?.cwd || ''
3514
+ $('ds-workspace').textContent = '📁 ' + (workspace.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || t('ds.noWorkspace')) + ' ›'
3515
+ $('ds-workspace').title = workspace
3516
+ $('ds-workspace').classList.remove('hidden')
3260
3517
  $('ds-session-status').textContent = recoveryLabel()
3261
3518
  }
3262
3519
  const running = !!state.byId.get(state.current)?.running || (state.queues[state.current] || []).some(i => i.placement !== 'context')
@@ -3278,6 +3535,7 @@ function showSettingsPage(name) {
3278
3535
  if (name === 'general') renderPresetSummary()
3279
3536
  }
3280
3537
  function updateConn() {
3538
+ overviewDetector?.observe()
3281
3539
  const el = $('conn-badge')
3282
3540
  // 双实时通道可能按任意顺序打开,连接刷新必须同时刷新系统总览。
3283
3541
  renderOverviewDesktop()
@@ -3323,7 +3581,23 @@ function updateConn() {
3323
3581
  }
3324
3582
 
3325
3583
  /* ---------------- 初始化 ---------------- */
3584
+
3585
+ function bindSessionDialogs() {
3586
+ const actions=$('session-actions'), info=$('session-info');
3587
+ $('btn-session-more').addEventListener('click',()=>actions.showModal());
3588
+ actions.addEventListener('click',e=>{if(e.target===actions)actions.close();else if(e.target.closest('button'))actions.close()},true);
3589
+ const openInfo=()=>{const s=state.byId.get(state.current);if(!s)return; $('session-info-name').textContent=titleOf(s);$('session-info-path').textContent=s.cwd||t('ds.noWorkspace');$('session-info-id').textContent=s.sessionId;$('btn-copy-session-workspace').disabled=!s.cwd;info.showModal()};
3590
+ $('ds-title').addEventListener('click',openInfo);
3591
+ $('ds-workspace').addEventListener('click',openInfo);
3592
+ $('btn-session-info').addEventListener('click',openInfo);
3593
+ info.addEventListener('click',e=>{if(e.target===info||e.target.closest('[data-session-dialog-close]'))info.close()});
3594
+ $('btn-copy-session-workspace').addEventListener('click',async()=>{const value=state.byId.get(state.current)?.cwd;if(value&&await copyText(value))toast(t('ds.copied'),'ok')});
3595
+ }
3596
+
3326
3597
  function bindUi() {
3598
+ bindSessionDialogs()
3599
+ getConversationView()
3600
+ $('btn-history-latest').addEventListener('click',()=>{getConversationView().latest();if(state.history.tailEvicted)void loadHistory(true)})
3327
3601
  $('btn-new-session').addEventListener('click', openNewSessionModal)
3328
3602
  $('btn-new-workspace').addEventListener('click', openWorkspaceModal)
3329
3603
  $('session-sort')?.addEventListener('change', (e) => {
@@ -3341,14 +3615,7 @@ function bindUi() {
3341
3615
  }
3342
3616
  })
3343
3617
  document.querySelectorAll('.ds-nav-item').forEach(b => b.addEventListener('click', () => showView(b.dataset.view)))
3344
- $('ds-overview-refresh').addEventListener('click', async () => {
3345
- toast(t('ds.loading'))
3346
- if (state.token) {
3347
- await refreshSessions()
3348
- await refreshHostDescriptionDesktop({ notify: true })
3349
- }
3350
- renderOverviewDesktop()
3351
- })
3618
+ $('ds-overview-refresh').addEventListener('click',()=>{startOverviewDetection(true);if(state.token)void refreshSessions()})
3352
3619
  $('ds-overview-primary-action').addEventListener('click', () => {
3353
3620
  const button = $('ds-overview-primary-action')
3354
3621
  const action = button.dataset.dsOverviewAction
@@ -3524,6 +3791,10 @@ function bindUi() {
3524
3791
  try { await navigator.clipboard.writeText(state.token); toast(t('ds.toastCopied'), 'ok') }
3525
3792
  catch { toast(t('ds.toastOpFailed'), 'err') }
3526
3793
  })
3794
+ $('desktop-token-save').addEventListener('click', () => void saveAccessTokenDesktop())
3795
+ $('desktop-token-input').addEventListener('keydown', event => {
3796
+ if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); void saveAccessTokenDesktop() }
3797
+ })
3527
3798
  $('btn-theme').addEventListener('click', () => {
3528
3799
  const cur = themeGet() || 'default'
3529
3800
  const idx = THEME_META.findIndex(m => m.id === cur)
@@ -3547,6 +3818,19 @@ function bindUi() {
3547
3818
  $('btn-question-cancel').addEventListener('click', () => { $('modal-question').classList.add('hidden'); toast(t('ds.ignored'), 'ok') })
3548
3819
  }
3549
3820
 
3821
+ async function saveAccessTokenDesktop() {
3822
+ const value = $('desktop-token-input').value.trim()
3823
+ if (!value) return
3824
+ state.token = value; LS.set('token', value)
3825
+ const current = state.servers.find(s => s.id === state.groupActive[state.activeGroup]) || state.servers.find(s => s.url === (state.server || location.origin))
3826
+ if (current) current.token = value
3827
+ saveServers(); $('desktop-token-input').value = ''
3828
+ $('token-desc').textContent = '● ' + value.slice(0, 12) + '…'
3829
+ showView('view-overview'); openStreams()
3830
+ await Promise.all([refreshSessions(), refreshHostDescriptionDesktop()])
3831
+ void refreshWorkbench({ silent: true })
3832
+ }
3833
+
3550
3834
  async function start() {
3551
3835
  const urlToken = new URLSearchParams(location.search).get('token')?.trim() || ''
3552
3836
  if (urlToken) {
@@ -3565,35 +3849,21 @@ async function start() {
3565
3849
  LS.set('token', urlToken)
3566
3850
  saveServers()
3567
3851
  }
3568
- if (!state.token) {
3569
- const input = prompt(t('ds.tokenTitle'))
3570
- if (input && input.trim()) { state.token = input.trim(); LS.set('token', state.token) }
3571
- }
3572
3852
  $('token-desc').textContent = state.token ? '● ' + state.token.slice(0, 12) + '…' : t('ds.toastAuth')
3573
3853
  bindUi()
3854
+ if (!state.token) { showView('view-settings'); $('desktop-token-input').focus() }
3574
3855
  renderWorkbench()
3575
3856
  updateConn()
3576
3857
  checkNotesOnStart()
3577
3858
  if (state.token) {
3578
3859
  await selectFastestServer({ silent: true, reconnect: false })
3860
+ overviewStarting=false
3579
3861
  openStreams()
3580
- await refreshSessions()
3581
- await refreshHostDescriptionDesktop()
3862
+ await Promise.all([refreshSessions(),refreshHostDescriptionDesktop()])
3582
3863
  refreshWorkbench({ silent: true })
3583
3864
  }
3865
+ overviewStarting=false
3584
3866
  renderOverviewDesktop()
3585
3867
  }
3586
3868
 
3587
3869
  start()
3588
-
3589
- // Capture the connection so switching servers cannot redirect a plugin mutation.
3590
- document.getElementById('btn-plugin-center')?.addEventListener('click', () => {
3591
- const connection = captureConnection()
3592
- const server = connection.server || ''
3593
- const token = connection.token
3594
- window.DshPluginCenter.open({
3595
- url: path => server + path,
3596
- headers: { authorization: 'Bearer ' + token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() },
3597
- valid: connection.valid,
3598
- })
3599
- })