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.
@@ -80,6 +80,7 @@ const state = {
80
80
  queues: {},
81
81
  sessionActivity: new Set(),
82
82
  queueSteering: {},
83
+ compactionBootAt: Date.now(),
83
84
  compactions: {},
84
85
  pendingCommands: {},
85
86
  compactionPollTimer: null,
@@ -113,14 +114,22 @@ for (const key of ['server', 'token']) {
113
114
  set(next) {
114
115
  if (next === value) return
115
116
  value = next; connectionGeneration++
117
+ clearTimeout(state.refreshTimer); state.refreshTimer = null
116
118
  state.sessions = []; state.byId.clear(); state.pendingProjections.clear()
117
119
  state.hostInfo = null
118
120
  if(typeof closeStream==='function'&&typeof streamMeta!=='undefined'){closeStream('mux');closeStream('host')}
119
121
  state.current = null; state.history = emptyDesktopHistory()
122
+ state.models = { loaded: false, loading: false, groups: [], current: null, failures: [] }
123
+ state.approvals = []; state.questions = []; state.questionModal = null
124
+ state.queues = {}; state.queueSteering = {}; state.compactions = {}; state.compactionTerminals = {}; state.compactionSeqs = {}; state.compactionBootAt = Date.now(); state.pendingCommands = {}; state.sessionTurnTimes = {}
125
+ state.sessionActivity = new Set()
120
126
  state.fs.path = null; state.fs.initial = null; state.fs.loaded = false; state.fs.roots = []; state.fs.rootIndex = 0
121
127
  state.workspaces = []; state.archivedIds = []; state.wb = { bound: false, path: '', projects: null }
122
128
  window.DshPluginCenter?.close()
123
129
  window.DshInsights?.close()
130
+ window.DshExtensions?.close()
131
+ window.DshExtensions?.invalidateCapabilities()
132
+ if (typeof document !== 'undefined') document.getElementById('btn-insights')?.classList.add('hidden')
124
133
  if(typeof document!=='undefined') {
125
134
  const identityGeneration=connectionGeneration
126
135
  queueMicrotask(()=>{if(identityGeneration===connectionGeneration&&typeof startOverviewDetection==='function')startOverviewDetection(true,true)})
@@ -128,7 +137,10 @@ for (const key of ['server', 'token']) {
128
137
  const generation=connectionGeneration
129
138
  queueMicrotask(()=>{if(generation!==connectionGeneration)return;if(typeof conversationView!=='undefined')conversationView?.reset();restoreCachedSessionList()})
130
139
  }
131
- if (typeof document !== 'undefined') document.getElementById('modal-workspace')?.classList.add('hidden')
140
+ if (typeof document !== 'undefined') {
141
+ for (const id of ['modal-workspace', 'modal-workbench', 'modal-question', 'modal-new-session', 'modal-rename']) document.getElementById(id)?.classList.add('hidden')
142
+ if (typeof renderNotifStack === 'function') renderNotifStack()
143
+ }
132
144
  },
133
145
  })
134
146
  }
@@ -289,15 +301,20 @@ function toggleModelMenuDesktop() {
289
301
 
290
302
  async function loadSessionModels() {
291
303
  if (!state.current || state.models.loading) return
292
- state.models.loading = true
304
+ const connection = captureConnection(), sessionId = state.current, models = state.models
305
+ const request = models.request = (models.request || 0) + 1
306
+ const valid = () => connection.valid() && state.current === sessionId && state.models === models && models.request === request
307
+ models.loading = true
293
308
  renderModelMenu()
294
309
  try {
295
- const v = await rpc('session.models', { sessionId: state.current })
296
- state.models.groups = v.groups || []
297
- state.models.current = v.current || null
298
- state.models.failures = v.failures || []
299
- state.models.loaded = true
310
+ const v = await rpc('session.models', { sessionId })
311
+ if (!valid()) return
312
+ models.groups = v.groups || []
313
+ models.current = v.current || null
314
+ models.failures = v.failures || []
315
+ models.loaded = true
300
316
  } catch (e) {
317
+ if (!valid()) return
301
318
  if (e.message === 'AUTH') { toast(t('ds.toastAuth'), 'err'); state.models.loading = false; renderModelMenu(); return }
302
319
  toast(t('models.loadFailed', { msg: e.message }), 'err')
303
320
  }
@@ -363,9 +380,12 @@ function reasoningEffortOptions(model) {
363
380
  async function selectSessionEffort(effortId) {
364
381
  const cur = state.models.current
365
382
  if (!state.current || !cur) return
383
+ const connection = captureConnection(), sessionId = state.current, models = state.models
384
+ const request = models.request = (models.request || 0) + 1
366
385
  const v = await safeRpc('session.selectModel', {
367
- sessionId: state.current, provider: cur.provider, model: cur.model, reasoningEffort: effortId
386
+ sessionId, provider: cur.provider, model: cur.model, reasoningEffort: effortId
368
387
  }, t('models.effortFailed'))
388
+ if (!connection.valid() || state.current !== sessionId || state.models !== models || models.request !== request) return
369
389
  if (v?.selected) {
370
390
  state.models.current = v.selected
371
391
  renderEffortMenu()
@@ -375,12 +395,15 @@ async function selectSessionEffort(effortId) {
375
395
 
376
396
  async function selectSessionModel(provider, modelId) {
377
397
  if (!state.current) return
398
+ const connection = captureConnection(), sessionId = state.current, models = state.models
399
+ const request = models.request = (models.request || 0) + 1
378
400
  const group = (state.models.groups || []).find(g => g.id === provider)
379
401
  const model = (group?.models || []).find(m => m.id === modelId)
380
- const payload = { sessionId: state.current, provider, model: modelId }
402
+ const payload = { sessionId, provider, model: modelId }
381
403
  const effort = model?.reasoning?.defaultEffort || model?.reasoning?.efforts?.[0]?.id
382
404
  if (effort) payload.reasoningEffort = effort
383
405
  const v = await safeRpc('session.selectModel', payload, t('models.switchFailed'))
406
+ if (!connection.valid() || state.current !== sessionId || state.models !== models || models.request !== request) return
384
407
  if (v?.selected) {
385
408
  state.models.current = v.selected
386
409
  renderModelMenu()
@@ -603,14 +626,16 @@ function hideTip() { const tip = $('ds-tip'); if (tip) tip.classList.add('hidden
603
626
  /* ---------------- API ---------------- */
604
627
  function apiUrl(path) { return (state.server || '') + path }
605
628
  let wsTicketPromise = null
629
+ let wsTicketConnection = null
606
630
  async function getWsTicket() {
607
631
  const now = Date.now()
608
632
  if (state.wsTicket.token === state.token && state.wsTicket.server === state.server &&
609
633
  state.wsTicket.value && state.wsTicket.expiresAt > now + 15000) return state.wsTicket.value
610
- if (wsTicketPromise) return wsTicketPromise
634
+ if (wsTicketPromise && wsTicketConnection?.valid()) return wsTicketPromise
635
+ const connection = captureConnection()
611
636
  const token = state.token
612
637
  const server = state.server
613
- wsTicketPromise = (async () => {
638
+ const job = (async () => {
614
639
  if (activeGatewayCapability('wsTicket') === false) throw new Error('ws ticket unsupported')
615
640
  const res = await fetch(apiUrl('/api/ws-ticket'), {
616
641
  method: 'POST',
@@ -618,11 +643,14 @@ async function getWsTicket() {
618
643
  })
619
644
  if (!res.ok) throw new Error('ws ticket HTTP ' + res.status)
620
645
  const data = await res.json()
646
+ if (!connection.valid()) throw new Error('stale ws ticket')
621
647
  if (!data?.ticket || !Number(data.expiresAt)) throw new Error('invalid ws ticket')
622
648
  state.wsTicket = { token, server, value: data.ticket, expiresAt: Number(data.expiresAt) }
623
649
  return data.ticket
624
650
  })()
625
- try { return await wsTicketPromise } finally { wsTicketPromise = null }
651
+ wsTicketPromise = job
652
+ wsTicketConnection = connection
653
+ try { return await job } finally { if (wsTicketPromise === job) { wsTicketPromise = null; wsTicketConnection = null } }
626
654
  }
627
655
  async function rpc(method, payload = {}, timeoutMs = 45000) {
628
656
  const opts = {
@@ -657,7 +685,7 @@ async function respond(rpcId, value) {
657
685
  }
658
686
  async function safeRpc(method, payload, errText) {
659
687
  const connection = captureConnection()
660
- try { return await rpc(method, payload) }
688
+ try { const value = await rpc(method, payload); return connection.valid() ? value : null }
661
689
  catch (e) {
662
690
  if (!connection.valid()) return null
663
691
  if (e.message === 'AUTH') { toast(t('ds.toastAuth'), 'err'); return null }
@@ -807,7 +835,7 @@ async function pingServer(base) {
807
835
  const ctrl = new AbortController()
808
836
  const timer = setTimeout(() => ctrl.abort(), 3500)
809
837
  try {
810
- const res = await fetch(u + '/health?t=' + Date.now(), { signal: ctrl.signal, cache: 'no-store' })
838
+ const res = await fetch(u + '/health?probe=live&t=' + Date.now(), { signal: ctrl.signal, cache: 'no-store' })
811
839
  if (!res.ok) return Infinity
812
840
  const health = await res.json().catch(() => null)
813
841
  if (health && typeof health === 'object') {
@@ -834,7 +862,10 @@ function dshReachable() {
834
862
  return !!state.hostInfo
835
863
  }
836
864
  async function selectFastestServer({ silent = false, reconnect = true } = {}) {
837
- if (state.selectingServer) return null
865
+ const request = selectFastestServer.request = (selectFastestServer.request || 0) + 1
866
+ const connection = captureConnection(), group = state.activeGroup
867
+ const policy = JSON.stringify([state.autoSelect[group], state.groupActive[group], state.servers])
868
+ const valid = () => connection.valid() && request === selectFastestServer.request && state.activeGroup === group && policy === JSON.stringify([state.autoSelect[group], state.groupActive[group], state.servers])
838
869
  state.selectingServer = true
839
870
  try {
840
871
  if (!silent) toast(t('ds.speedTesting'))
@@ -845,6 +876,7 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
845
876
  let ms = Infinity
846
877
  if (state.autoSelect[state.activeGroup] !== false) {
847
878
  const measured = await Promise.all(candidates.map(async (server) => [server, await pingServer(server.url)]))
879
+ if (!valid()) return null
848
880
  for (const [server, latency] of measured) state.serverLatency[serverKey(server)] = latency
849
881
  best = candidates.filter(server => Number.isFinite(state.serverLatency[serverKey(server)])).sort((a, b) => state.serverLatency[serverKey(a)] - state.serverLatency[serverKey(b)])[0] || null
850
882
  const sameOrigin = best?.url === location.origin && best.origin
@@ -862,6 +894,8 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
862
894
  ms = state.serverLatency[key]
863
895
  }
864
896
  }
897
+ if (!valid()) return null
898
+ if (typeof window !== 'undefined') window.DshNetwork?.observeLatency(ms)
865
899
  renderServers()
866
900
  if (chosen !== state.server || chosenToken !== state.token) {
867
901
  state.hostInfo = null
@@ -885,7 +919,7 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
885
919
  else toast(t('ds.speedAllDown'), 'err')
886
920
  }
887
921
  return chosen
888
- } finally { state.selectingServer = false }
922
+ } finally { if (request === selectFastestServer.request) state.selectingServer = false }
889
923
  }
890
924
 
891
925
  function serverTitle(s) { return s.note || s.url }
@@ -1324,43 +1358,46 @@ function enterPollMode() {
1324
1358
  }
1325
1359
 
1326
1360
  function stopPolling() {
1327
- clearInterval(pollTimer)
1328
- pollTimer = null
1329
- clearTimeout(wsRetryTimer)
1330
- wsRetryTimer = null
1361
+ pollInFlight?.stop()
1362
+ pollInFlight = null
1363
+ clearInterval(pollTimer); pollTimer = null
1364
+ clearInterval(wsRetryTimer); wsRetryTimer = null
1331
1365
  }
1332
-
1333
1366
  function startPolling() {
1334
1367
  stopPolling()
1335
1368
  pollTimer = setInterval(pollOnce, 4000)
1336
1369
  wsRetryTimer = setInterval(tryRestoreWs, 30000)
1337
- pollOnce()
1370
+ void pollOnce()
1338
1371
  }
1339
-
1340
- let pollInFlight = false
1372
+ let pollInFlight = null
1341
1373
  async function pollOnce() {
1342
- if (state.streamMode !== 'poll' || pollInFlight) return
1343
- pollInFlight = true
1344
- try {
1345
- await Promise.all([pollKind('mux'), pollKind('host')])
1346
- } finally {
1347
- pollInFlight = false
1348
- }
1374
+ if (state.streamMode !== 'poll') return
1375
+ if (!pollInFlight) pollInFlight = new window.DshNetwork.PollLoop({
1376
+ active: () => state.streamMode === 'poll' && !!state.token,
1377
+ capture: () => { const connection = captureConnection(), cursors = state.pollSeq; return { valid: () => connection.valid() && state.pollSeq === cursors } },
1378
+ read: pollKind
1379
+ })
1380
+ return pollInFlight.tick()
1349
1381
  }
1350
1382
 
1351
- async function pollKind(kind) {
1383
+ async function pollKind(kind, cancellation) {
1352
1384
  if (state.streamMode !== 'poll') return
1385
+ const connection = captureConnection(), cursors = state.pollSeq
1386
+ const valid = () => connection.valid() && state.streamMode === 'poll' && state.pollSeq === cursors && !cancellation?.aborted
1353
1387
  const since = state.pollSeq[kind] || 0
1354
1388
  let res
1355
1389
  try {
1356
- const signal = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(5000) : undefined
1390
+ const timeout = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(window.DshNetwork?.profile().pollTimeout || 30000) : undefined
1391
+ const signal = cancellation && timeout && typeof AbortSignal.any === 'function' ? AbortSignal.any([cancellation, timeout]) : timeout || cancellation
1357
1392
  const headers = { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }
1358
- 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 })
1393
+ res = signal ? await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000`), { signal, headers }) : await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000`), { headers })
1359
1394
  } catch { return }
1395
+ if (!valid()) return
1360
1396
  if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
1361
1397
  if (!res.ok) return
1362
1398
  let data
1363
1399
  try { data = await res.json() } catch { return }
1400
+ if (!valid()) return
1364
1401
  if (!data || !Array.isArray(data.events)) return
1365
1402
  const reset = data.truncated === true || (typeof data.latestSeq === 'number' && data.latestSeq < since)
1366
1403
  if (reset) {
@@ -1376,6 +1413,7 @@ async function pollKind(kind) {
1376
1413
  else onHostFrame(item.event)
1377
1414
  }
1378
1415
  }
1416
+ return data.waitSupported === true ? 100 : 4000
1379
1417
  }
1380
1418
 
1381
1419
  function tryRestoreWs() {
@@ -1414,7 +1452,7 @@ function onMuxFrame(full) {
1414
1452
  if (f.sessionId === state.current) { applyReasoningBaseline(f.partialReasoning); scheduleReasoningRender() }
1415
1453
  return
1416
1454
  }
1417
- if (f.type === 'session/event') return onSessionEvent(f.sessionId, f.event)
1455
+ if (f.type === 'session/event') return onSessionEvent(f.sessionId, f.event, { replay: f.replay === true })
1418
1456
  if (f.type === 'approval/requested') {
1419
1457
  state.approvals = state.approvals.filter(a => a.approvalId !== f.approvalId)
1420
1458
  state.approvals.push({ ...f, rpcId: full.rpcId })
@@ -1436,7 +1474,7 @@ function onMuxFrame(full) {
1436
1474
  function onHostFrame(full) {
1437
1475
  const f = full.payload
1438
1476
  if (!f) return
1439
- 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()
1477
+ 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()
1440
1478
  if (f.type === 'host/session-activity') {
1441
1479
  const session = state.byId.get(f.sessionId)
1442
1480
  if (session) { session.updatedAt = Number(f.updatedAt) || Date.now(); renderSessions(); renderOverviewDesktop() }
@@ -1458,6 +1496,7 @@ function compactElapsed(startedAt) {
1458
1496
  return minutes > 0 ? `${minutes}:${String(remain).padStart(2, '0')}` : `${remain}s`
1459
1497
  }
1460
1498
  function setCompactionStatus(sessionId, next) {
1499
+ state.compactionTerminals ||= {}
1461
1500
  if (!sessionId) return
1462
1501
  const previous = state.compactions[sessionId]
1463
1502
  if (next?.active === true) {
@@ -1468,10 +1507,15 @@ function setCompactionStatus(sessionId, next) {
1468
1507
  startedAt: Number(next.startedAt) || previous?.startedAt || Date.now(),
1469
1508
  message: String(next.message || ''),
1470
1509
  source: next.source || previous?.source || 'event',
1510
+ compactionId: next.compactionId || previous?.compactionId || '',
1511
+ notify: next.notify ?? previous?.notify ?? (next.source === 'command'),
1471
1512
  }
1472
1513
  } else {
1473
1514
  delete state.compactions[sessionId]
1474
1515
  if (previous?.active) {
1516
+ state.compactionTerminals[sessionId] = { startedAt: previous.startedAt, compactionId: previous.compactionId }
1517
+ }
1518
+ if (previous?.active && previous.notify && next?.notify !== false && ['complete', 'failed'].includes(next?.phase)) {
1475
1519
  const command = previous.command || 'compact'
1476
1520
  if (next?.phase === 'failed') toast(command === 'compact'
1477
1521
  ? t('ds.compactFailed', { msg: next.message || t('ds.sessionRecoveryFailed') })
@@ -1484,18 +1528,25 @@ function setCompactionStatus(sessionId, next) {
1484
1528
  }
1485
1529
  async function refreshCompactionStatus(sessionId = state.current) {
1486
1530
  if (!sessionId) return
1531
+ const connection = captureConnection()
1487
1532
  try {
1488
1533
  const signal = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(8000) : undefined
1489
- const url = new URL(apiUrl('/remote/api/command-status'), location.href)
1534
+ const url = new URL(connection.server + '/remote/api/command-status', location.href)
1490
1535
  url.searchParams.set('sessionId', sessionId)
1491
- const res = await fetch(url, { headers: { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }, ...(signal ? { signal } : {}) })
1536
+ const res = await fetch(url, { headers: { authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }, ...(signal ? { signal } : {}) })
1537
+ if (!connection.valid()) return
1492
1538
  if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
1493
1539
  if (!res.ok) return
1540
+ if (!connection.valid()) return
1494
1541
  const body = await res.json().catch(() => null)
1542
+ if (!connection.valid()) return
1495
1543
  const operation = body?.operation || body?.compact
1496
1544
  if (!operation) return
1545
+ if (operation.startedAt && activeCompaction(sessionId)?.startedAt > Number(operation.startedAt)) return
1497
1546
  const pending = state.pendingCommands[sessionId]
1498
- if (operation.active) {
1547
+ if (operation.active === true) {
1548
+ const terminal = state.compactionTerminals?.[sessionId]
1549
+ if (terminal && Number(operation.startedAt) <= terminal.startedAt) return
1499
1550
  delete state.pendingCommands[sessionId]
1500
1551
  setCompactionStatus(sessionId, { ...operation, source: 'status' })
1501
1552
  } else if (activeCompaction(sessionId) && activeCompaction(sessionId).source !== 'event') {
@@ -1521,14 +1572,25 @@ function ensureCompactionMonitoring() {
1521
1572
  if (compact && compact.source !== 'event') void refreshCompactionStatus()
1522
1573
  }, 3000)
1523
1574
  }
1524
- function observeCompactionEvent(sessionId, event) {
1525
- if (event?.type === 'compaction/start') {
1526
- const existing = activeCompaction(sessionId)
1527
- setCompactionStatus(sessionId, { active: true, phase: 'running', startedAt: existing?.startedAt || Date.now(), source: existing?.source || 'event' })
1528
- } else if (event?.type === 'compaction/end' && activeCompaction(sessionId)?.source === 'event') {
1529
- setCompactionStatus(sessionId, { active: false, phase: 'complete' })
1575
+ function observeCompactionEvent(sessionId, event, meta = {}) {
1576
+ if (!event || !sessionId || !['compaction/start','compaction/end','session/end-seed'].includes(event.type)) return
1577
+ state.compactionSeqs ||= {}; state.compactionBootAt ||= Date.now()
1578
+ const seq = Number(event.seq), previous = activeCompaction(sessionId)
1579
+ if (seq > 0 && seq <= (state.compactionSeqs[sessionId] || 0)) return
1580
+ const id = event.data?.compactionId || ''
1581
+ if (event.type === 'compaction/end' && previous?.compactionId && previous.compactionId !== id) return
1582
+ if (seq > 0) state.compactionSeqs[sessionId] = seq
1583
+ const time = typeof event.time === 'number' ? event.time : Date.parse(event.time)
1584
+ if (event.type === 'compaction/start') {
1585
+ setCompactionStatus(sessionId, { active: true, phase: 'running', compactionId: id,
1586
+ startedAt: previous?.startedAt || (Number.isFinite(time) ? time : Date.now()), source: previous?.source || 'event',
1587
+ notify: meta.replay ? false : previous?.notify || Number.isFinite(time) && time >= state.compactionBootAt })
1588
+ } else {
1589
+ setCompactionStatus(sessionId, { active: false, phase: event.type === 'session/end-seed' ? 'interrupted' : event.data?.error ? 'failed' : 'complete',
1590
+ message: event.data?.error || '', ...(meta.replay || event.type === 'session/end-seed' ? { notify: false } : {}) })
1530
1591
  }
1531
1592
  }
1593
+
1532
1594
  function hydrateSessionProjections(sessionId, projections) {
1533
1595
  const s = state.byId.get(sessionId)
1534
1596
  if (!s || !projections || typeof projections !== 'object') return
@@ -1568,7 +1630,7 @@ function applyProjection(sessionId, key, value, seq) {
1568
1630
  window.DshInsights?.update()
1569
1631
  if (['goal', 'todos'].includes(key)) renderSessionCards()
1570
1632
  }
1571
- if (['title', 'goal', 'todos', 'plan', 'sessionListMetadata'].includes(key)) refreshSessions()
1633
+ if (['title', 'goal', 'todos', 'plan', 'sessionListMetadata'].includes(key)) scheduleSessionsRefresh()
1572
1634
  }
1573
1635
  function setSessionRecovery(status, error = '') {
1574
1636
  state.sessionRecovery = { status, error: String(error || '') }
@@ -1592,9 +1654,36 @@ function resyncAfterStreamOpen() {
1592
1654
  void refreshSessions().then(() => resyncCurrentSession())
1593
1655
  }
1594
1656
  function proj(s, key, d) { return s?.projections?.values?.[key] ?? d }
1595
- function openInsights(tab = 'context') {
1596
- window.DshInsights?.open({ tab, connection: captureConnection(), url: apiUrl,
1597
- getSession: () => state.byId.get(state.current), getTitle: () => titleOf(state.byId.get(state.current)) })
1657
+ function optionalPluginConfig(connection = captureConnection()) {
1658
+ return { connection, valid: connection.valid, url: path => connection.server + path,
1659
+ headers: { authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() } }
1660
+ }
1661
+ function availableInsightTabs(capabilities) {
1662
+ return [...(capabilities.context ? ['context'] : []), ...(capabilities.cost ? ['cost'] : [])]
1663
+ }
1664
+ async function refreshInsightEntry() {
1665
+ const control = $('btn-insights'), id = state.current, connection = captureConnection()
1666
+ if (!control || !id || !connection.token || !window.DshExtensions) { control?.classList.add('hidden'); return }
1667
+ const capabilities = await window.DshExtensions.getCapabilities(optionalPluginConfig(connection))
1668
+ if (!connection.valid() || state.current !== id) return
1669
+ const tabs = availableInsightTabs(capabilities)
1670
+ control.classList.toggle('hidden', !tabs.length)
1671
+ const label = t(tabs.length === 2 ? 'ds.insights' : tabs[0] === 'cost' ? 'ds.insightsCost' : 'ds.insightsContext')
1672
+ control.textContent = label; control.title = label; control.setAttribute('aria-label', label)
1673
+ }
1674
+ async function openInsights(tab = 'context', fullPage = false) {
1675
+ const connection = captureConnection(), id = state.current
1676
+ const capabilities = await window.DshExtensions.getCapabilities(optionalPluginConfig(connection))
1677
+ if (!connection.valid() || state.current !== id || !id) return
1678
+ const allowedTabs = availableInsightTabs(capabilities)
1679
+ if (!allowedTabs.length) { void refreshInsightEntry(); return }
1680
+ window.DshInsights?.close()
1681
+ const view = fullPage ? conversationView : null, wasPaused = view?.paused
1682
+ view?.pause()
1683
+ window.DshInsights?.open({ tab, fullPage, allowedTabs, connection, url: path => connection.server + path,
1684
+ getSession: () => state.byId.get(state.current), getTitle: () => titleOf(state.byId.get(state.current)),
1685
+ onFullPage: selected => void openInsights(selected, true),
1686
+ onClose: () => { if (view && !wasPaused && connection.valid() && state.current === id && state.view === 'view-chat') view.resume() } })
1598
1687
  }
1599
1688
  function sessionTitleValue(s) {
1600
1689
  const value = proj(s, 'title', '')
@@ -1642,8 +1731,8 @@ function setGoalCollapsed(sessionId, goal, collapsed) {
1642
1731
  if (collapsed) next.push({ sessionId, goalId })
1643
1732
  LS.set(COLLAPSED_GOALS_KEY, JSON.stringify(next.slice(-100)))
1644
1733
  }
1645
- function onSessionEvent(sessionId, event) {
1646
- observeCompactionEvent(sessionId, event)
1734
+ function onSessionEvent(sessionId, event, meta = {}) {
1735
+ observeCompactionEvent(sessionId, event, meta)
1647
1736
  if (event?.type === 'turn/start' || event?.type === 'turn/end') {
1648
1737
  noteSessionTurnTime(sessionId, event)
1649
1738
  renderSessions()
@@ -1664,8 +1753,7 @@ function onSessionEvent(sessionId, event) {
1664
1753
  const seq = event.seq
1665
1754
  if (seq != null && !h.seqs.has(seq) && shouldShowEvent(event.type, event)) {
1666
1755
  h.seqs.add(seq)
1667
- h.visible.push({ seq, event })
1668
- h.visible.sort((a, b) => a.seq - b.seq)
1756
+ window.DshHistory.insertSorted(h.visible, { seq, event })
1669
1757
  trimVisible()
1670
1758
  renderHistory()
1671
1759
  scheduleHistoryCacheSave()
@@ -1675,6 +1763,11 @@ function onSessionEvent(sessionId, event) {
1675
1763
  }
1676
1764
 
1677
1765
  /* ---------------- 会话 ---------------- */
1766
+ function scheduleSessionsRefresh() {
1767
+ if (state.refreshTimer) return
1768
+ const connection = captureConnection()
1769
+ state.refreshTimer = setTimeout(() => { state.refreshTimer = null; if (connection.valid()) void refreshSessions() }, 150)
1770
+ }
1678
1771
  async function refreshSessions() {
1679
1772
  if(typeof restoreCachedSessionList==='function')restoreCachedSessionList()
1680
1773
  const connection = captureConnection(), request = ++sessionsRequest
@@ -1881,7 +1974,7 @@ function getConversationView() {
1881
1974
  if(!conversationView)conversationView=new window.DshHistory.HistoryView($('history'),{
1882
1975
  html:entry=>eventHtml(entry),
1883
1976
  older:()=>loadHistory(false),olderLabel:()=>t('ds.historyEarlier'),loadingLabel:()=>t('ds.historyLoadingEarlier'),live:partialReasoningHtml,
1884
- 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);},
1977
+ changed:view=>{state.history.renderStart=view.start;state.history.renderEnd=view.end;const latest=$('btn-history-latest');if(latest){latest.classList.toggle('hidden',!view.reading&&view.end>=view.entries.length&&!state.history.tailEvicted);latest.textContent=t('ds.historyLatest')+(view.unread?' ('+view.unread+')':view.hasPending?' · '+(I18N.lang==='en'?'New content':'有新内容'):'');}},
1885
1978
  scrolled:()=>{}
1886
1979
  })
1887
1980
  return conversationView
@@ -1924,12 +2017,13 @@ async function loadHistory(reset = true) {
1924
2017
  const reasoningVersion=history.reasoningVersion||0,hadContent=history.visible.length>0
1925
2018
  history.loading=true
1926
2019
  if(reset){if(hadContent)historySource('syncing');else setSessionRecovery('loading')}
1927
- const payload={sessionId:id,maxMessages:60}
2020
+ const network=window.DshNetwork?.profile() || {historyPageSize:60,readTimeout:45000}
2021
+ const payload={sessionId:id,maxMessages:network.historyPageSize}
1928
2022
  if(!reset&&Number.isFinite(history.minSeq))payload.beforeSeq=history.minSeq
1929
2023
  getConversationView().more.disabled=true
1930
2024
  getConversationView().more.textContent=getConversationView().options.loadingLabel()
1931
2025
  let v
1932
- try{v=await rpc('session.history',payload)}catch(error){
2026
+ try{v=await rpc('session.history',payload,network.readTimeout)}catch(error){
1933
2027
  if(!connection.valid()||state.current!==id||state.history!==history)return
1934
2028
  history.loading=false;history.retryAfter=Date.now()+1500
1935
2029
  if(error.message==='AUTH'){return}
@@ -2047,7 +2141,8 @@ function partialReasoningHtml() {
2047
2141
  function safeJson(v) { try { return JSON.stringify(v, null, 2) } catch { return String(v) } }
2048
2142
  function blockHtml(b) {
2049
2143
  if (!b) return ''
2050
- if (b.type === 'text') return `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '') : esc(b.text ?? '')}</div>`
2144
+ if (b.type === 'text') return `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '', { fileLinks: true }) : esc(b.text ?? '')}</div>`
2145
+ if (b.type === 'file' && typeof window !== 'undefined' && window.DshChatFiles) return window.DshChatFiles.render(b)
2051
2146
  if (b.type === 'file') return `<div class="ds-tool">📎 ${esc(b.attachment?.name || b.name || 'file')} <small>${esc(b.attachment?.bytes ?? b.bytes ?? '')} bytes</small></div>`
2052
2147
  if (b.type === 'thinking' || b.type === 'reasoning') return `<details><summary>${esc(t('block.thinking'))}</summary><div style="opacity:.82">${esc(b.text ?? b.content ?? '')}</div></details>`
2053
2148
  if (b.type === 'tool-call') return `<div>🔧 ${esc(b.name || '')}</div>`
@@ -2099,10 +2194,22 @@ function renderHistory(reset=false, mode='auto') {
2099
2194
  }
2100
2195
 
2101
2196
  /* ---------------- 会话信息卡(goal / todo / 子代理) ---------------- */
2197
+ let sessionSubagentsJob = null
2198
+ async function loadSessionSubagents(sessionId) {
2199
+ if (sessionSubagentsJob?.sessionId === sessionId && sessionSubagentsJob.connection.valid()) return sessionSubagentsJob.promise
2200
+ const connection = captureConnection(), job = { sessionId, connection }
2201
+ job.promise = (async () => {
2202
+ const value = await safeRpc('subagent.list', { parentSessionId: sessionId }, '')
2203
+ return connection.valid() ? value : null
2204
+ })()
2205
+ sessionSubagentsJob = job
2206
+ try { return await job.promise } finally { if (sessionSubagentsJob === job) sessionSubagentsJob = null }
2207
+ }
2102
2208
  let sessionCardsRenderGeneration = 0
2103
2209
  async function renderSessionCards() {
2210
+ const connection = captureConnection()
2104
2211
  window.DshInsights?.update()
2105
- $('btn-insights')?.classList.toggle('hidden', !state.current)
2212
+ void refreshInsightEntry()
2106
2213
  const renderGeneration = ++sessionCardsRenderGeneration
2107
2214
  const sessionId = state.current
2108
2215
  const box = $('session-cards')
@@ -2149,8 +2256,8 @@ async function renderSessionCards() {
2149
2256
  requestAnimationFrame(() => box.querySelector(`[data-goal-collapse="${collapse ? '0' : '1'}"]`)?.focus())
2150
2257
  }))
2151
2258
 
2152
- const sub = await safeRpc('subagent.list', { parentSessionId: sessionId }, '')
2153
- if (renderGeneration !== sessionCardsRenderGeneration || state.current !== sessionId) return
2259
+ const sub = await loadSessionSubagents(sessionId)
2260
+ if (!connection.valid() || renderGeneration !== sessionCardsRenderGeneration || state.current !== sessionId) return
2154
2261
  if (sub?.entries?.length) {
2155
2262
  const expanded = state.subagentExpandedSession === sessionId
2156
2263
  const toggleLabel = expanded ? t('subagent.collapse') : t('subagent.expand')
@@ -2186,6 +2293,8 @@ function setGoalPhaseLocal(phase) {
2186
2293
  }
2187
2294
 
2188
2295
  async function goalAction(kind) {
2296
+ const connection = captureConnection(), sessionId = state.current, history = state.history
2297
+ const valid = () => connection.valid() && state.current === sessionId && state.history === history
2189
2298
  const s = state.byId.get(state.current)
2190
2299
  const goal = goalOf(s)
2191
2300
  if (!goal) return toast(t('goal.none'), 'err')
@@ -2194,8 +2303,8 @@ async function goalAction(kind) {
2194
2303
  const objective = prompt(t('goal.editPrompt'), goal.objective || '')
2195
2304
  if (objective === null) return
2196
2305
  if (!objective.trim()) return toast(t('goal.cannotEmpty'), 'err')
2197
- const result = await safeRpc('goal.edit', { sessionId: state.current, ref, objective: objective.trim() }, t('goal.updateFailed'))
2198
- if (result == null) return
2306
+ const result = await safeRpc('goal.edit', { sessionId, ref, objective: objective.trim() }, t('goal.updateFailed'))
2307
+ if (result == null || !valid()) return
2199
2308
  toast(t('goal.updated'), 'ok')
2200
2309
  refreshSessions()
2201
2310
  renderSessionCards()
@@ -2206,8 +2315,8 @@ async function goalAction(kind) {
2206
2315
  if (!method) return
2207
2316
  if (kind === 'clear' && !confirm(t('goal.confirmClear'))) return
2208
2317
  if (kind === 'complete' && !confirm(t('goal.confirmComplete'))) return
2209
- const result = await safeRpc(method, { sessionId: state.current, ref }, t('goal.actionFailed'))
2210
- if (result == null) return
2318
+ const result = await safeRpc(method, { sessionId, ref }, t('goal.actionFailed'))
2319
+ if (result == null || !valid()) return
2211
2320
  if (kind === 'complete') setGoalPhaseLocal('complete')
2212
2321
  if (kind === 'clear') setGoalPhaseLocal('cleared')
2213
2322
  toast(t('goal.actionSubmitted'), 'ok')
@@ -2238,16 +2347,18 @@ function sessionLogFilename(sessionId) {
2238
2347
  }
2239
2348
 
2240
2349
  async function downloadSessionExport(sessionId) {
2350
+ const connection = captureConnection()
2241
2351
  const url = new URL(apiUrl('/api/session.export'), location.href)
2242
2352
  url.searchParams.set('sessionId', sessionId)
2243
2353
  url.searchParams.set('includeDescendants', 'true')
2244
- if (state.server && state.token) url.searchParams.set('token', state.token)
2354
+ if (state.token && (state.server || !(location.pathname === '/remote' || location.pathname.startsWith('/remote/')))) url.searchParams.set('token', state.token)
2245
2355
  const headers = state.token ? { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() } : {}
2246
2356
  try {
2247
2357
  const signal = typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'
2248
2358
  ? AbortSignal.timeout(LONG_RUNNING_SLASH_COMMAND_TIMEOUT_MS)
2249
2359
  : undefined
2250
2360
  const preflight = await fetch(url, { method: 'HEAD', headers, ...(signal ? { signal } : {}) })
2361
+ if (!connection.valid()) return
2251
2362
  if (preflight.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
2252
2363
  if (!preflight.ok) throw new Error('HTTP ' + preflight.status)
2253
2364
  const anchor = document.createElement('a')
@@ -2266,6 +2377,7 @@ async function downloadSessionExport(sessionId) {
2266
2377
  async function runSlashCommand(text) {
2267
2378
  const clean = String(text || '').trim()
2268
2379
  if (!clean.startsWith('/') || !state.current) return false
2380
+ const sessionId = state.current, connection = captureConnection()
2269
2381
  const command = slashCommandName(clean)
2270
2382
  const noFallback = NO_FALLBACK_SLASH_COMMANDS.has(command)
2271
2383
  const longRunning = command === 'export'
@@ -2276,59 +2388,74 @@ async function runSlashCommand(text) {
2276
2388
  const res = await fetch(apiUrl('/remote/api/command'), {
2277
2389
  method: 'POST',
2278
2390
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() },
2279
- body: JSON.stringify({ sessionId: state.current, line: clean }),
2391
+ body: JSON.stringify({ sessionId, line: clean }),
2280
2392
  ...(signal ? { signal } : {})
2281
2393
  })
2394
+ if (!connection.valid()) return true
2282
2395
  if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return true }
2283
2396
  if (!res.ok) {
2284
2397
  if (noFallback) toast(t('ds.commandTimedOut'), 'err')
2285
2398
  return noFallback
2286
2399
  }
2287
2400
  const data = await res.json().catch(() => null)
2401
+ if (!connection.valid()) return true
2288
2402
  if (data?.ok === false) return true
2289
2403
  if (data?.ok === true && data.executed === true) {
2290
2404
  if (data.accepted) {
2291
2405
  if (command === 'compact') {
2292
- setCompactionStatus(state.current, { ...(data.operation || data.compact), active: true, command, source: 'command' })
2406
+ setCompactionStatus(sessionId, { ...(data.operation || data.compact), active: true, command, source: 'command' })
2293
2407
  } else {
2294
- const sessionId = state.current
2295
2408
  state.pendingCommands[sessionId] = command
2296
- setTimeout(() => { if (state.current === sessionId) void refreshCompactionStatus(sessionId) }, 600)
2409
+ setTimeout(() => { if (connection.valid() && state.current === sessionId) void refreshCompactionStatus(sessionId) }, 600)
2297
2410
  }
2298
- } else if (command === 'export') await downloadSessionExport(state.current)
2411
+ } else if (command === 'export') await downloadSessionExport(sessionId)
2299
2412
  return true
2300
2413
  }
2301
2414
  } catch (e) {
2415
+ if (!connection.valid() || state.current !== sessionId) return true
2302
2416
  console.error('slash command bridge failed', e)
2303
2417
  if (noFallback) {
2304
2418
  toast(t('ds.commandTimedOut'), 'err')
2305
2419
  return true
2306
2420
  }
2307
2421
  }
2308
- return false
2422
+ return !connection.valid() || state.current !== sessionId
2309
2423
  }
2310
2424
 
2311
2425
  async function sendMessage() {
2312
2426
  const input = $('composer')
2313
- const text = input.value.trim()
2427
+ const originalText = input.value, text = originalText.trim()
2314
2428
  if (!text || !state.current) return
2315
- state.sessionActivity.add(state.current)
2316
- if (await runSlashCommand(text)) { input.value = ''; return }
2317
- input.value = ''
2318
- setSessionRecovery('resuming')
2319
- const v = await safeRpc('session.prompt', {
2320
- sessionId: state.current,
2321
- mode: 'queue',
2322
- content: [{ type: 'text', text }]
2323
- }, '')
2324
- if (v) { setSessionRecovery('ready'); noteSessionTurnTime(state.current, Date.now()); renderSessions(); toast(t('ds.toastSent'), 'ok') }
2325
- else setSessionRecovery('error')
2429
+ const sessionId = state.current, connection = captureConnection(), history = state.history
2430
+ const pending = sendMessage.pending ||= new Set()
2431
+ if (pending.has(history)) return
2432
+ pending.add(history)
2433
+ const valid = () => connection.valid() && state.current === sessionId && state.history === history
2434
+ try {
2435
+ state.sessionActivity.add(sessionId)
2436
+ if (await runSlashCommand(text)) { if (valid() && input.value === originalText) input.value = ''; return }
2437
+ if (!valid()) return
2438
+ setSessionRecovery('resuming')
2439
+ const v = await safeRpc('session.prompt', {
2440
+ sessionId,
2441
+ mode: 'queue',
2442
+ content: [{ type: 'text', text }]
2443
+ }, '')
2444
+ if (!valid()) return
2445
+ if (v?.accepted) {
2446
+ if (input.value === originalText) input.value = ''
2447
+ setSessionRecovery('ready'); noteSessionTurnTime(sessionId, Date.now()); renderSessions(); toast(t('ds.toastSent'), 'ok')
2448
+ }
2449
+ else setSessionRecovery('error')
2450
+ } finally { pending.delete(history) }
2326
2451
  }
2327
2452
 
2328
2453
  async function cancelSession() {
2329
2454
  if (!state.current) return
2330
2455
  if (!confirm(t('ds.sessionStopConfirm'))) return
2331
- const v = await safeRpc('session.cancel', { sessionId: state.current }, t('ds.sessionStopFailed'))
2456
+ const sessionId = state.current, connection = captureConnection()
2457
+ const v = await safeRpc('session.cancel', { sessionId }, t('ds.sessionStopFailed'))
2458
+ if (!connection.valid() || state.current !== sessionId) return
2332
2459
  if (v?.accepted) { setSessionRecovery('ready'); toast(t('ds.sessionStopRequested'), 'ok') }
2333
2460
  }
2334
2461
 
@@ -2348,6 +2475,7 @@ function closeRenameSession() {
2348
2475
  async function confirmRenameSession() {
2349
2476
  const sessionId = renamePendingSessionId
2350
2477
  if (!sessionId) return
2478
+ const connection = captureConnection()
2351
2479
  const title = $('rename-session-input').value.trim()
2352
2480
  if (!title) return toast(t('ds.sessionRenameEmpty'), 'err')
2353
2481
  const button = $('rename-confirm')
@@ -2355,6 +2483,7 @@ async function confirmRenameSession() {
2355
2483
  setSessionRecovery('resuming')
2356
2484
  try {
2357
2485
  const value = await safeRpc('session.rename', { sessionId, title }, t('ds.sessionRenameFailed'))
2486
+ if (!connection.valid() || renamePendingSessionId !== sessionId) return
2358
2487
  if (value == null) { setSessionRecovery('error'); return }
2359
2488
  if (value.title) applyProjection(sessionId, 'title', value.title, value.seq)
2360
2489
  closeRenameSession()
@@ -2369,11 +2498,12 @@ async function confirmRenameSession() {
2369
2498
  async function archiveCurrentSession() {
2370
2499
  const sessionId = state.current
2371
2500
  if (!sessionId || !confirm(t('ds.sessionArchiveConfirm'))) return
2501
+ const connection = captureConnection()
2372
2502
  const value = await safeRpc('workspace.archiveSession', { sessionId }, t('ds.toastOpFailed'))
2373
- if (!value) return
2503
+ if (!value || !connection.valid()) return
2374
2504
  if (Array.isArray(value.archivedSessionIds)) state.archivedIds = value.archivedSessionIds
2375
2505
  toast(t('ds.sessionArchived'), 'ok')
2376
- closeSession()
2506
+ if (state.current === sessionId) await closeSession()
2377
2507
  await refreshSessions()
2378
2508
  }
2379
2509
 
@@ -2513,18 +2643,21 @@ function renderNotifStack() {
2513
2643
  renderOverviewDesktop()
2514
2644
  }
2515
2645
  async function approveApproval(id, allow) {
2646
+ const connection = captureConnection()
2516
2647
  const a = state.approvals.find(x => x.approvalId === id)
2517
2648
  if (!a) return
2518
2649
  let ok
2519
2650
  try {
2520
2651
  ok = await respond(a.rpcId, { sessionId: a.sessionId, approvalId: a.approvalId, outcome: allow ? 'allowed-once' : 'rejected' })
2521
2652
  } catch (e) {
2653
+ if (!connection.valid()) return
2522
2654
  if (e.message === 'AUTH') toast(t('ds.toastAuth'), 'err')
2523
2655
  else toast(t('ds.pendingSubmitFailed', { msg: e.message || t('ds.feedbackNetworkError') }), 'err')
2524
2656
  return
2525
2657
  }
2658
+ if (!connection.valid()) return
2526
2659
  toast(ok ? (allow ? t('ds.allowed') : t('ds.rejected')) : t('ds.stale'), ok ? 'ok' : 'err')
2527
- state.approvals = state.approvals.filter(x => x.approvalId !== id)
2660
+ state.approvals = state.approvals.filter(x => x.rpcId !== a.rpcId)
2528
2661
  renderNotifStack()
2529
2662
  }
2530
2663
  function openQuestionModal(q) {
@@ -2540,6 +2673,7 @@ function openQuestionModal(q) {
2540
2673
  $('modal-question').classList.remove('hidden')
2541
2674
  }
2542
2675
  async function submitQuestion() {
2676
+ const connection = captureConnection()
2543
2677
  const q = state.questionModal
2544
2678
  if (!q) return
2545
2679
  const answers = q.questions.map((item, i) => {
@@ -2555,13 +2689,15 @@ async function submitQuestion() {
2555
2689
  try {
2556
2690
  ok = await respond(q.rpcId, { sessionId: q.sessionId, answer: { answers } })
2557
2691
  } catch (e) {
2692
+ if (!connection.valid()) return
2558
2693
  if (e.message === 'AUTH') toast(t('ds.toastAuth'), 'err')
2559
2694
  else toast(t('ds.pendingSubmitFailed', { msg: e.message || t('ds.feedbackNetworkError') }), 'err')
2560
2695
  return
2561
2696
  }
2697
+ if (!connection.valid()) return
2562
2698
  if (ok) {
2563
2699
  toast(t('ds.questionSubmitted'), 'ok')
2564
- $('modal-question').classList.add('hidden')
2700
+ if (state.questionModal === q) { $('modal-question').classList.add('hidden'); state.questionModal = null }
2565
2701
  state.questions = state.questions.filter(x => x.rpcId !== q.rpcId)
2566
2702
  renderNotifStack()
2567
2703
  } else toast(t('ds.stale'), 'err')
@@ -2666,7 +2802,6 @@ async function createWorkspace() {
2666
2802
  button.disabled = true
2667
2803
  try {
2668
2804
  const res = await fetch(fsApiUrl('/mkdir', { path: parent, name }), { method: 'POST', headers: fsHeaders() })
2669
- if (!connection.valid()) return
2670
2805
  if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
2671
2806
  const data = await res.json().catch(() => ({}))
2672
2807
  if (!connection.valid()) return
@@ -3045,6 +3180,7 @@ async function openNewSessionModal() {
3045
3180
  function closeNewSessionModal() { $('modal-new-session').classList.add('hidden') }
3046
3181
  async function createSessionInWorkspace() {
3047
3182
  if (createSessionInWorkspace.busy) return
3183
+ const connection = captureConnection()
3048
3184
  const workspaceId = $('new-session-workspace').value
3049
3185
  if (!workspaceById(workspaceId)) return toast(t('ds.newSessionChooseWorkspace'), 'err')
3050
3186
  createSessionInWorkspace.busy = true
@@ -3052,10 +3188,11 @@ async function createSessionInWorkspace() {
3052
3188
  button.disabled = true
3053
3189
  try {
3054
3190
  const value = await safeRpc('session.create', { workspaceId }, '')
3055
- if (!value?.sessionId) return
3191
+ if (!connection.valid() || !value?.sessionId) return
3056
3192
  LS.set('lastNewSessionWorkspaceV1', workspaceId)
3057
3193
  closeNewSessionModal()
3058
3194
  await refreshSessions()
3195
+ if (!connection.valid()) return
3059
3196
  openSession(value.sessionId)
3060
3197
  } finally {
3061
3198
  createSessionInWorkspace.busy = false
@@ -3070,8 +3207,10 @@ function openWorkbenchModal() {
3070
3207
  wbFsLoad(null)
3071
3208
  setTimeout(() => $('wb-path-input').focus(), 50)
3072
3209
  }
3073
- function closeWorkbenchModal() { $('modal-workbench').classList.add('hidden') }
3210
+ function closeWorkbenchModal() { wbFs.request = (wbFs.request || 0) + 1; $('modal-workbench').classList.add('hidden') }
3074
3211
  async function wbFsLoad(dir) {
3212
+ const connection = captureConnection(), request = wbFs.request = (wbFs.request || 0) + 1
3213
+ const valid = () => connection.valid() && request === wbFs.request
3075
3214
  const box = $('wb-fs-list')
3076
3215
  const target = dir ?? wbFs.path ?? ''
3077
3216
  box.innerHTML = `<div class="ds-empty">${esc(t('ds.loading'))}</div>`
@@ -3079,6 +3218,7 @@ async function wbFsLoad(dir) {
3079
3218
  try {
3080
3219
  const res = await fetch(fsApiUrl('/list', target ? { path: target } : {}), { headers: fsHeaders() })
3081
3220
  const data = await res.json().catch(() => ({}))
3221
+ if (!valid()) return
3082
3222
  if (!res.ok || !Array.isArray(data.entries)) throw new Error(data.error || ('HTTP ' + res.status))
3083
3223
  wbFs.path = data.path
3084
3224
  if (!wbFs.initial) wbFs.initial = data.path
@@ -3091,6 +3231,7 @@ async function wbFsLoad(dir) {
3091
3231
  box.querySelectorAll('[data-wb-dir]').forEach(row => row.addEventListener('click', e => { if (!e.target.closest('[data-wb-select]')) wbFsLoad(row.dataset.wbDir) }))
3092
3232
  box.querySelectorAll('[data-wb-select]').forEach(button => button.addEventListener('click', () => bindWorkbench(button.dataset.wbSelect)))
3093
3233
  } catch (e) {
3234
+ if (!valid()) return
3094
3235
  $('wb-fs-path').textContent = target || '~'
3095
3236
  box.innerHTML = `<div class="ds-empty">${esc(e.message || t('ds.toastConnFailed'))}</div>`
3096
3237
  }
@@ -3102,38 +3243,49 @@ function wbFsUp() {
3102
3243
  }
3103
3244
  }
3104
3245
  async function bindWorkbench(rawPath) {
3246
+ const connection = captureConnection()
3105
3247
  const value = String(rawPath || '').trim()
3106
3248
  if (!value) return toast(t('wb.pathEmpty'), 'err')
3107
3249
  try {
3108
3250
  const wb = await wbGateway('POST', '/workbench/bind', { path: value })
3251
+ if (!connection.valid()) return
3109
3252
  state.wb = { bound: true, path: wb.path || value, title: wb.title || '', expanded: true, projects: null, open: null, apiMissing: false }
3110
3253
  const paths = [state.wb.path]
3111
3254
  try {
3112
3255
  const res = await fetch(fsApiUrl('/list', { path: state.wb.path }), { headers: fsHeaders() })
3113
3256
  const data = await res.json().catch(() => ({}))
3257
+ if (!connection.valid()) return
3114
3258
  for (const e of data.entries || []) if (e.type === 'dir') paths.push(wbJoin(state.wb.path, e.name))
3115
3259
  } catch {}
3116
3260
  for (const projectPath of paths) {
3261
+ if (!connection.valid()) return
3117
3262
  try { await rpc('workspace.create', { path: projectPath }) } catch {}
3118
3263
  }
3264
+ if (!connection.valid()) return
3119
3265
  closeWorkbenchModal()
3120
3266
  await refreshWorkbench({ silent: true })
3267
+ if (!connection.valid()) return
3121
3268
  await refreshSessions()
3269
+ if (!connection.valid()) return
3122
3270
  toast(t('wb.boundOk', { path: state.wb.path }), 'ok')
3123
3271
  } catch (e) {
3272
+ if (!connection.valid()) return
3124
3273
  if (e.message === 'AUTH') return toast(t('ds.toastAuth'), 'err')
3125
3274
  toast(t('wb.bindFailed', { msg: e.message }), 'err')
3126
3275
  }
3127
3276
  }
3128
3277
  async function unbindWorkbench() {
3129
3278
  if (!confirm(t('wb.unbindConfirm'))) return
3279
+ const connection = captureConnection()
3130
3280
  try {
3131
3281
  await wbGateway('POST', '/workbench/unbind')
3282
+ if (!connection.valid()) return
3132
3283
  state.wb = { bound: false, path: '', title: '', expanded: false, projects: null, open: null, apiMissing: false }
3133
3284
  renderWorkbench()
3134
3285
  renderSessions()
3135
3286
  toast(t('wb.unboundOk'), 'ok')
3136
3287
  } catch (e) {
3288
+ if (!connection.valid()) return
3137
3289
  if (e.message === 'AUTH') return toast(t('ds.toastAuth'), 'err')
3138
3290
  toast(t('wb.unbindFailed', { msg: e.message }), 'err')
3139
3291
  }
@@ -3253,7 +3405,7 @@ async function probeOverviewLinks(signal) {
3253
3405
  const controller=new AbortController(),cancel=()=>controller.abort()
3254
3406
  signal.addEventListener('abort',cancel,{once:true});if(signal.aborted)controller.abort()
3255
3407
  timer=setTimeout(cancel,4000)
3256
- const healthRequest=fetch(base+'/health?t='+Date.now(),{signal:controller.signal,cache:'no-store'}).then(async response=>{
3408
+ const healthRequest=fetch(base+'/health?probe=live&t='+Date.now(),{signal:controller.signal,cache:'no-store'}).then(async response=>{
3257
3409
  if(!response.ok)throw Error('health')
3258
3410
  const health=await response.json();if(health?.ok!==true)throw Error('health')
3259
3411
  return health
@@ -3379,16 +3531,18 @@ function setMobileSidebar(open) {
3379
3531
  $('ds-app')?.classList.toggle('mobile-nav-open', visible)
3380
3532
  }
3381
3533
 
3382
- function openDesktopPlugins() {
3534
+ function openDesktopPlugins(route = 'manage') {
3383
3535
  const connection=captureConnection()
3384
3536
  if(!connection.token){$('desktop-plugin-page').textContent=t('ds.toastAuth');return}
3385
- 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'))
3537
+ window.DshExtensions.mount({connection,getSession:()=>state.byId.get(state.current),getTitle:()=>titleOf(state.byId.get(state.current)),openContext:()=>void openInsights('context',true),scrollTop:()=>{$('view-plugins').scrollTop=0},url:path=>connection.server+path,headers:{authorization:'Bearer '+connection.token,'x-dsh-remote-client':'web',...clientIdHeaders()},valid:connection.valid},$('desktop-plugin-page'),route)
3386
3538
  }
3387
3539
 
3388
3540
  function showView(id) {
3541
+ if (id !== 'view-chat') conversationView?.pause()
3389
3542
  if (state.view === 'view-chat' && id !== 'view-chat' && state.current) void archiveEmptySessionOnLeave(state.current)
3390
3543
  state.view = id
3391
3544
  for (const v of ['view-overview', 'view-sessions', 'view-chat', 'view-files', 'view-plugins', 'view-settings']) $(v).classList.toggle('hidden', v !== id)
3545
+ if (id === 'view-chat') conversationView?.resume()
3392
3546
  document.querySelectorAll('.ds-nav-item').forEach(b => b.classList.toggle('active', b.dataset.view === id))
3393
3547
  if (narrowSidebarQuery.matches) setMobileSidebar(false)
3394
3548
  window.DshMotion?.view($(id))
@@ -3400,7 +3554,7 @@ function showView(id) {
3400
3554
  if (id === 'view-files' && !state.fs.loaded) loadFs(null, true)
3401
3555
  if (id === 'view-settings') showSettingsHome()
3402
3556
  if (id === 'view-plugins') openDesktopPlugins()
3403
- else window.DshPluginCenter?.close()
3557
+ else window.DshExtensions?.close()
3404
3558
  updateSessionActions()
3405
3559
  }
3406
3560
 
@@ -3603,6 +3757,7 @@ function bindUi() {
3603
3757
  if (!e.target.closest('#model-menu') && !e.target.closest('#btn-model')) $('model-menu')?.classList.add('hidden')
3604
3758
  })
3605
3759
  $('btn-stats-top').addEventListener('click', toggleStatsDrawer)
3760
+ window.DshChatFiles?.bind($('history'), () => { const c=captureConnection(); return { ...c,sessionId:state.current,cwd:sessionCwd(state.byId.get(state.current)),native:false,headers:{authorization:'Bearer '+c.token,...clientIdHeaders()},notice:toast } })
3606
3761
  $('btn-insights').addEventListener('click', () => openInsights())
3607
3762
  $('stats-drawer-close').addEventListener('click', toggleStatsDrawer)
3608
3763
  // 赞赏支持
@@ -3694,6 +3849,10 @@ function bindUi() {
3694
3849
  try { await navigator.clipboard.writeText(state.token); toast(t('ds.toastCopied'), 'ok') }
3695
3850
  catch { toast(t('ds.toastOpFailed'), 'err') }
3696
3851
  })
3852
+ $('desktop-token-save').addEventListener('click', () => void saveAccessTokenDesktop())
3853
+ $('desktop-token-input').addEventListener('keydown', event => {
3854
+ if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); void saveAccessTokenDesktop() }
3855
+ })
3697
3856
  $('btn-theme').addEventListener('click', () => {
3698
3857
  const cur = themeGet() || 'default'
3699
3858
  const idx = THEME_META.findIndex(m => m.id === cur)
@@ -3702,7 +3861,7 @@ function bindUi() {
3702
3861
  $('btn-lang').addEventListener('click', () => {
3703
3862
  I18N.setLang(I18N.lang === 'zh' ? 'en' : 'zh')
3704
3863
  $('btn-lang').textContent = I18N.lang === 'zh' ? 'EN' : '中文'
3705
- renderServers(); renderSessions(); renderNotifStack(); renderOverviewDesktop(); updateConn(); themeApply()
3864
+ renderServers(); renderSessions(); renderNotifStack(); renderOverviewDesktop(); updateConn(); themeApply(); void refreshInsightEntry()
3706
3865
  })
3707
3866
  $('fs-up').addEventListener('click', fsUp)
3708
3867
  $('fs-root').addEventListener('change', (event) => {
@@ -3717,6 +3876,19 @@ function bindUi() {
3717
3876
  $('btn-question-cancel').addEventListener('click', () => { $('modal-question').classList.add('hidden'); toast(t('ds.ignored'), 'ok') })
3718
3877
  }
3719
3878
 
3879
+ async function saveAccessTokenDesktop() {
3880
+ const value = $('desktop-token-input').value.trim()
3881
+ if (!value) return
3882
+ state.token = value; LS.set('token', value)
3883
+ const current = state.servers.find(s => s.id === state.groupActive[state.activeGroup]) || state.servers.find(s => s.url === (state.server || location.origin))
3884
+ if (current) current.token = value
3885
+ saveServers(); $('desktop-token-input').value = ''
3886
+ $('token-desc').textContent = '● ' + value.slice(0, 12) + '…'
3887
+ showView('view-overview'); openStreams()
3888
+ await Promise.all([refreshSessions(), refreshHostDescriptionDesktop()])
3889
+ void refreshWorkbench({ silent: true })
3890
+ }
3891
+
3720
3892
  async function start() {
3721
3893
  const urlToken = new URLSearchParams(location.search).get('token')?.trim() || ''
3722
3894
  if (urlToken) {
@@ -3735,12 +3907,9 @@ async function start() {
3735
3907
  LS.set('token', urlToken)
3736
3908
  saveServers()
3737
3909
  }
3738
- if (!state.token) {
3739
- const input = prompt(t('ds.tokenTitle'))
3740
- if (input && input.trim()) { state.token = input.trim(); LS.set('token', state.token) }
3741
- }
3742
3910
  $('token-desc').textContent = state.token ? '● ' + state.token.slice(0, 12) + '…' : t('ds.toastAuth')
3743
3911
  bindUi()
3912
+ if (!state.token) { showView('view-settings'); $('desktop-token-input').focus() }
3744
3913
  renderWorkbench()
3745
3914
  updateConn()
3746
3915
  checkNotesOnStart()