dsh-remote-plugin 0.7.3 → 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.
@@ -113,10 +113,15 @@ 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()
117
118
  state.hostInfo = null
118
119
  if(typeof closeStream==='function'&&typeof streamMeta!=='undefined'){closeStream('mux');closeStream('host')}
119
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()
120
125
  state.fs.path = null; state.fs.initial = null; state.fs.loaded = false; state.fs.roots = []; state.fs.rootIndex = 0
121
126
  state.workspaces = []; state.archivedIds = []; state.wb = { bound: false, path: '', projects: null }
122
127
  window.DshPluginCenter?.close()
@@ -128,7 +133,10 @@ for (const key of ['server', 'token']) {
128
133
  const generation=connectionGeneration
129
134
  queueMicrotask(()=>{if(generation!==connectionGeneration)return;if(typeof conversationView!=='undefined')conversationView?.reset();restoreCachedSessionList()})
130
135
  }
131
- if (typeof document !== 'undefined') document.getElementById('modal-workspace')?.classList.add('hidden')
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
+ }
132
140
  },
133
141
  })
134
142
  }
@@ -289,15 +297,20 @@ function toggleModelMenuDesktop() {
289
297
 
290
298
  async function loadSessionModels() {
291
299
  if (!state.current || state.models.loading) return
292
- 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
293
304
  renderModelMenu()
294
305
  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
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
300
312
  } catch (e) {
313
+ if (!valid()) return
301
314
  if (e.message === 'AUTH') { toast(t('ds.toastAuth'), 'err'); state.models.loading = false; renderModelMenu(); return }
302
315
  toast(t('models.loadFailed', { msg: e.message }), 'err')
303
316
  }
@@ -363,9 +376,12 @@ function reasoningEffortOptions(model) {
363
376
  async function selectSessionEffort(effortId) {
364
377
  const cur = state.models.current
365
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
366
381
  const v = await safeRpc('session.selectModel', {
367
- sessionId: state.current, provider: cur.provider, model: cur.model, reasoningEffort: effortId
382
+ sessionId, provider: cur.provider, model: cur.model, reasoningEffort: effortId
368
383
  }, t('models.effortFailed'))
384
+ if (!connection.valid() || state.current !== sessionId || state.models !== models || models.request !== request) return
369
385
  if (v?.selected) {
370
386
  state.models.current = v.selected
371
387
  renderEffortMenu()
@@ -375,12 +391,15 @@ async function selectSessionEffort(effortId) {
375
391
 
376
392
  async function selectSessionModel(provider, modelId) {
377
393
  if (!state.current) return
394
+ const connection = captureConnection(), sessionId = state.current, models = state.models
395
+ const request = models.request = (models.request || 0) + 1
378
396
  const group = (state.models.groups || []).find(g => g.id === provider)
379
397
  const model = (group?.models || []).find(m => m.id === modelId)
380
- const payload = { sessionId: state.current, provider, model: modelId }
398
+ const payload = { sessionId, provider, model: modelId }
381
399
  const effort = model?.reasoning?.defaultEffort || model?.reasoning?.efforts?.[0]?.id
382
400
  if (effort) payload.reasoningEffort = effort
383
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
384
403
  if (v?.selected) {
385
404
  state.models.current = v.selected
386
405
  renderModelMenu()
@@ -603,14 +622,16 @@ function hideTip() { const tip = $('ds-tip'); if (tip) tip.classList.add('hidden
603
622
  /* ---------------- API ---------------- */
604
623
  function apiUrl(path) { return (state.server || '') + path }
605
624
  let wsTicketPromise = null
625
+ let wsTicketConnection = null
606
626
  async function getWsTicket() {
607
627
  const now = Date.now()
608
628
  if (state.wsTicket.token === state.token && state.wsTicket.server === state.server &&
609
629
  state.wsTicket.value && state.wsTicket.expiresAt > now + 15000) return state.wsTicket.value
610
- if (wsTicketPromise) return wsTicketPromise
630
+ if (wsTicketPromise && wsTicketConnection?.valid()) return wsTicketPromise
631
+ const connection = captureConnection()
611
632
  const token = state.token
612
633
  const server = state.server
613
- wsTicketPromise = (async () => {
634
+ const job = (async () => {
614
635
  if (activeGatewayCapability('wsTicket') === false) throw new Error('ws ticket unsupported')
615
636
  const res = await fetch(apiUrl('/api/ws-ticket'), {
616
637
  method: 'POST',
@@ -618,11 +639,14 @@ async function getWsTicket() {
618
639
  })
619
640
  if (!res.ok) throw new Error('ws ticket HTTP ' + res.status)
620
641
  const data = await res.json()
642
+ if (!connection.valid()) throw new Error('stale ws ticket')
621
643
  if (!data?.ticket || !Number(data.expiresAt)) throw new Error('invalid ws ticket')
622
644
  state.wsTicket = { token, server, value: data.ticket, expiresAt: Number(data.expiresAt) }
623
645
  return data.ticket
624
646
  })()
625
- 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 } }
626
650
  }
627
651
  async function rpc(method, payload = {}, timeoutMs = 45000) {
628
652
  const opts = {
@@ -657,7 +681,7 @@ async function respond(rpcId, value) {
657
681
  }
658
682
  async function safeRpc(method, payload, errText) {
659
683
  const connection = captureConnection()
660
- try { return await rpc(method, payload) }
684
+ try { const value = await rpc(method, payload); return connection.valid() ? value : null }
661
685
  catch (e) {
662
686
  if (!connection.valid()) return null
663
687
  if (e.message === 'AUTH') { toast(t('ds.toastAuth'), 'err'); return null }
@@ -807,7 +831,7 @@ async function pingServer(base) {
807
831
  const ctrl = new AbortController()
808
832
  const timer = setTimeout(() => ctrl.abort(), 3500)
809
833
  try {
810
- 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' })
811
835
  if (!res.ok) return Infinity
812
836
  const health = await res.json().catch(() => null)
813
837
  if (health && typeof health === 'object') {
@@ -834,7 +858,10 @@ function dshReachable() {
834
858
  return !!state.hostInfo
835
859
  }
836
860
  async function selectFastestServer({ silent = false, reconnect = true } = {}) {
837
- 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])
838
865
  state.selectingServer = true
839
866
  try {
840
867
  if (!silent) toast(t('ds.speedTesting'))
@@ -845,6 +872,7 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
845
872
  let ms = Infinity
846
873
  if (state.autoSelect[state.activeGroup] !== false) {
847
874
  const measured = await Promise.all(candidates.map(async (server) => [server, await pingServer(server.url)]))
875
+ if (!valid()) return null
848
876
  for (const [server, latency] of measured) state.serverLatency[serverKey(server)] = latency
849
877
  best = candidates.filter(server => Number.isFinite(state.serverLatency[serverKey(server)])).sort((a, b) => state.serverLatency[serverKey(a)] - state.serverLatency[serverKey(b)])[0] || null
850
878
  const sameOrigin = best?.url === location.origin && best.origin
@@ -862,6 +890,8 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
862
890
  ms = state.serverLatency[key]
863
891
  }
864
892
  }
893
+ if (!valid()) return null
894
+ if (typeof window !== 'undefined') window.DshNetwork?.observeLatency(ms)
865
895
  renderServers()
866
896
  if (chosen !== state.server || chosenToken !== state.token) {
867
897
  state.hostInfo = null
@@ -885,7 +915,7 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
885
915
  else toast(t('ds.speedAllDown'), 'err')
886
916
  }
887
917
  return chosen
888
- } finally { state.selectingServer = false }
918
+ } finally { if (request === selectFastestServer.request) state.selectingServer = false }
889
919
  }
890
920
 
891
921
  function serverTitle(s) { return s.note || s.url }
@@ -1324,43 +1354,46 @@ function enterPollMode() {
1324
1354
  }
1325
1355
 
1326
1356
  function stopPolling() {
1327
- clearInterval(pollTimer)
1328
- pollTimer = null
1329
- clearTimeout(wsRetryTimer)
1330
- wsRetryTimer = null
1357
+ pollInFlight?.stop()
1358
+ pollInFlight = null
1359
+ clearInterval(pollTimer); pollTimer = null
1360
+ clearInterval(wsRetryTimer); wsRetryTimer = null
1331
1361
  }
1332
-
1333
1362
  function startPolling() {
1334
1363
  stopPolling()
1335
1364
  pollTimer = setInterval(pollOnce, 4000)
1336
1365
  wsRetryTimer = setInterval(tryRestoreWs, 30000)
1337
- pollOnce()
1366
+ void pollOnce()
1338
1367
  }
1339
-
1340
- let pollInFlight = false
1368
+ let pollInFlight = null
1341
1369
  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
- }
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()
1349
1377
  }
1350
1378
 
1351
- async function pollKind(kind) {
1379
+ async function pollKind(kind, cancellation) {
1352
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
1353
1383
  const since = state.pollSeq[kind] || 0
1354
1384
  let res
1355
1385
  try {
1356
- 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
1357
1388
  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 })
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 })
1359
1390
  } catch { return }
1391
+ if (!valid()) return
1360
1392
  if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
1361
1393
  if (!res.ok) return
1362
1394
  let data
1363
1395
  try { data = await res.json() } catch { return }
1396
+ if (!valid()) return
1364
1397
  if (!data || !Array.isArray(data.events)) return
1365
1398
  const reset = data.truncated === true || (typeof data.latestSeq === 'number' && data.latestSeq < since)
1366
1399
  if (reset) {
@@ -1376,6 +1409,7 @@ async function pollKind(kind) {
1376
1409
  else onHostFrame(item.event)
1377
1410
  }
1378
1411
  }
1412
+ return data.waitSupported === true ? 100 : 4000
1379
1413
  }
1380
1414
 
1381
1415
  function tryRestoreWs() {
@@ -1436,7 +1470,7 @@ function onMuxFrame(full) {
1436
1470
  function onHostFrame(full) {
1437
1471
  const f = full.payload
1438
1472
  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()
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()
1440
1474
  if (f.type === 'host/session-activity') {
1441
1475
  const session = state.byId.get(f.sessionId)
1442
1476
  if (session) { session.updatedAt = Number(f.updatedAt) || Date.now(); renderSessions(); renderOverviewDesktop() }
@@ -1568,7 +1602,7 @@ function applyProjection(sessionId, key, value, seq) {
1568
1602
  window.DshInsights?.update()
1569
1603
  if (['goal', 'todos'].includes(key)) renderSessionCards()
1570
1604
  }
1571
- if (['title', 'goal', 'todos', 'plan', 'sessionListMetadata'].includes(key)) refreshSessions()
1605
+ if (['title', 'goal', 'todos', 'plan', 'sessionListMetadata'].includes(key)) scheduleSessionsRefresh()
1572
1606
  }
1573
1607
  function setSessionRecovery(status, error = '') {
1574
1608
  state.sessionRecovery = { status, error: String(error || '') }
@@ -1664,8 +1698,7 @@ function onSessionEvent(sessionId, event) {
1664
1698
  const seq = event.seq
1665
1699
  if (seq != null && !h.seqs.has(seq) && shouldShowEvent(event.type, event)) {
1666
1700
  h.seqs.add(seq)
1667
- h.visible.push({ seq, event })
1668
- h.visible.sort((a, b) => a.seq - b.seq)
1701
+ window.DshHistory.insertSorted(h.visible, { seq, event })
1669
1702
  trimVisible()
1670
1703
  renderHistory()
1671
1704
  scheduleHistoryCacheSave()
@@ -1675,6 +1708,11 @@ function onSessionEvent(sessionId, event) {
1675
1708
  }
1676
1709
 
1677
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
+ }
1678
1716
  async function refreshSessions() {
1679
1717
  if(typeof restoreCachedSessionList==='function')restoreCachedSessionList()
1680
1718
  const connection = captureConnection(), request = ++sessionsRequest
@@ -1924,12 +1962,13 @@ async function loadHistory(reset = true) {
1924
1962
  const reasoningVersion=history.reasoningVersion||0,hadContent=history.visible.length>0
1925
1963
  history.loading=true
1926
1964
  if(reset){if(hadContent)historySource('syncing');else setSessionRecovery('loading')}
1927
- const payload={sessionId:id,maxMessages:60}
1965
+ const network=window.DshNetwork?.profile() || {historyPageSize:60,readTimeout:45000}
1966
+ const payload={sessionId:id,maxMessages:network.historyPageSize}
1928
1967
  if(!reset&&Number.isFinite(history.minSeq))payload.beforeSeq=history.minSeq
1929
1968
  getConversationView().more.disabled=true
1930
1969
  getConversationView().more.textContent=getConversationView().options.loadingLabel()
1931
1970
  let v
1932
- try{v=await rpc('session.history',payload)}catch(error){
1971
+ try{v=await rpc('session.history',payload,network.readTimeout)}catch(error){
1933
1972
  if(!connection.valid()||state.current!==id||state.history!==history)return
1934
1973
  history.loading=false;history.retryAfter=Date.now()+1500
1935
1974
  if(error.message==='AUTH'){return}
@@ -2099,8 +2138,20 @@ function renderHistory(reset=false, mode='auto') {
2099
2138
  }
2100
2139
 
2101
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
+ }
2102
2152
  let sessionCardsRenderGeneration = 0
2103
2153
  async function renderSessionCards() {
2154
+ const connection = captureConnection()
2104
2155
  window.DshInsights?.update()
2105
2156
  $('btn-insights')?.classList.toggle('hidden', !state.current)
2106
2157
  const renderGeneration = ++sessionCardsRenderGeneration
@@ -2149,8 +2200,8 @@ async function renderSessionCards() {
2149
2200
  requestAnimationFrame(() => box.querySelector(`[data-goal-collapse="${collapse ? '0' : '1'}"]`)?.focus())
2150
2201
  }))
2151
2202
 
2152
- const sub = await safeRpc('subagent.list', { parentSessionId: sessionId }, '')
2153
- if (renderGeneration !== sessionCardsRenderGeneration || state.current !== sessionId) return
2203
+ const sub = await loadSessionSubagents(sessionId)
2204
+ if (!connection.valid() || renderGeneration !== sessionCardsRenderGeneration || state.current !== sessionId) return
2154
2205
  if (sub?.entries?.length) {
2155
2206
  const expanded = state.subagentExpandedSession === sessionId
2156
2207
  const toggleLabel = expanded ? t('subagent.collapse') : t('subagent.expand')
@@ -2186,6 +2237,8 @@ function setGoalPhaseLocal(phase) {
2186
2237
  }
2187
2238
 
2188
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
2189
2242
  const s = state.byId.get(state.current)
2190
2243
  const goal = goalOf(s)
2191
2244
  if (!goal) return toast(t('goal.none'), 'err')
@@ -2194,8 +2247,8 @@ async function goalAction(kind) {
2194
2247
  const objective = prompt(t('goal.editPrompt'), goal.objective || '')
2195
2248
  if (objective === null) return
2196
2249
  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
2250
+ const result = await safeRpc('goal.edit', { sessionId, ref, objective: objective.trim() }, t('goal.updateFailed'))
2251
+ if (result == null || !valid()) return
2199
2252
  toast(t('goal.updated'), 'ok')
2200
2253
  refreshSessions()
2201
2254
  renderSessionCards()
@@ -2206,8 +2259,8 @@ async function goalAction(kind) {
2206
2259
  if (!method) return
2207
2260
  if (kind === 'clear' && !confirm(t('goal.confirmClear'))) return
2208
2261
  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
2262
+ const result = await safeRpc(method, { sessionId, ref }, t('goal.actionFailed'))
2263
+ if (result == null || !valid()) return
2211
2264
  if (kind === 'complete') setGoalPhaseLocal('complete')
2212
2265
  if (kind === 'clear') setGoalPhaseLocal('cleared')
2213
2266
  toast(t('goal.actionSubmitted'), 'ok')
@@ -2238,16 +2291,18 @@ function sessionLogFilename(sessionId) {
2238
2291
  }
2239
2292
 
2240
2293
  async function downloadSessionExport(sessionId) {
2294
+ const connection = captureConnection()
2241
2295
  const url = new URL(apiUrl('/api/session.export'), location.href)
2242
2296
  url.searchParams.set('sessionId', sessionId)
2243
2297
  url.searchParams.set('includeDescendants', 'true')
2244
- 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)
2245
2299
  const headers = state.token ? { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() } : {}
2246
2300
  try {
2247
2301
  const signal = typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'
2248
2302
  ? AbortSignal.timeout(LONG_RUNNING_SLASH_COMMAND_TIMEOUT_MS)
2249
2303
  : undefined
2250
2304
  const preflight = await fetch(url, { method: 'HEAD', headers, ...(signal ? { signal } : {}) })
2305
+ if (!connection.valid()) return
2251
2306
  if (preflight.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
2252
2307
  if (!preflight.ok) throw new Error('HTTP ' + preflight.status)
2253
2308
  const anchor = document.createElement('a')
@@ -2266,6 +2321,7 @@ async function downloadSessionExport(sessionId) {
2266
2321
  async function runSlashCommand(text) {
2267
2322
  const clean = String(text || '').trim()
2268
2323
  if (!clean.startsWith('/') || !state.current) return false
2324
+ const sessionId = state.current, connection = captureConnection()
2269
2325
  const command = slashCommandName(clean)
2270
2326
  const noFallback = NO_FALLBACK_SLASH_COMMANDS.has(command)
2271
2327
  const longRunning = command === 'export'
@@ -2276,59 +2332,74 @@ async function runSlashCommand(text) {
2276
2332
  const res = await fetch(apiUrl('/remote/api/command'), {
2277
2333
  method: 'POST',
2278
2334
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() },
2279
- body: JSON.stringify({ sessionId: state.current, line: clean }),
2335
+ body: JSON.stringify({ sessionId, line: clean }),
2280
2336
  ...(signal ? { signal } : {})
2281
2337
  })
2338
+ if (!connection.valid()) return true
2282
2339
  if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return true }
2283
2340
  if (!res.ok) {
2284
2341
  if (noFallback) toast(t('ds.commandTimedOut'), 'err')
2285
2342
  return noFallback
2286
2343
  }
2287
2344
  const data = await res.json().catch(() => null)
2345
+ if (!connection.valid()) return true
2288
2346
  if (data?.ok === false) return true
2289
2347
  if (data?.ok === true && data.executed === true) {
2290
2348
  if (data.accepted) {
2291
2349
  if (command === 'compact') {
2292
- setCompactionStatus(state.current, { ...(data.operation || data.compact), active: true, command, source: 'command' })
2350
+ setCompactionStatus(sessionId, { ...(data.operation || data.compact), active: true, command, source: 'command' })
2293
2351
  } else {
2294
- const sessionId = state.current
2295
2352
  state.pendingCommands[sessionId] = command
2296
- setTimeout(() => { if (state.current === sessionId) void refreshCompactionStatus(sessionId) }, 600)
2353
+ setTimeout(() => { if (connection.valid() && state.current === sessionId) void refreshCompactionStatus(sessionId) }, 600)
2297
2354
  }
2298
- } else if (command === 'export') await downloadSessionExport(state.current)
2355
+ } else if (command === 'export') await downloadSessionExport(sessionId)
2299
2356
  return true
2300
2357
  }
2301
2358
  } catch (e) {
2359
+ if (!connection.valid() || state.current !== sessionId) return true
2302
2360
  console.error('slash command bridge failed', e)
2303
2361
  if (noFallback) {
2304
2362
  toast(t('ds.commandTimedOut'), 'err')
2305
2363
  return true
2306
2364
  }
2307
2365
  }
2308
- return false
2366
+ return !connection.valid() || state.current !== sessionId
2309
2367
  }
2310
2368
 
2311
2369
  async function sendMessage() {
2312
2370
  const input = $('composer')
2313
- const text = input.value.trim()
2371
+ const originalText = input.value, text = originalText.trim()
2314
2372
  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')
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) }
2326
2395
  }
2327
2396
 
2328
2397
  async function cancelSession() {
2329
2398
  if (!state.current) return
2330
2399
  if (!confirm(t('ds.sessionStopConfirm'))) return
2331
- 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
2332
2403
  if (v?.accepted) { setSessionRecovery('ready'); toast(t('ds.sessionStopRequested'), 'ok') }
2333
2404
  }
2334
2405
 
@@ -2348,6 +2419,7 @@ function closeRenameSession() {
2348
2419
  async function confirmRenameSession() {
2349
2420
  const sessionId = renamePendingSessionId
2350
2421
  if (!sessionId) return
2422
+ const connection = captureConnection()
2351
2423
  const title = $('rename-session-input').value.trim()
2352
2424
  if (!title) return toast(t('ds.sessionRenameEmpty'), 'err')
2353
2425
  const button = $('rename-confirm')
@@ -2355,6 +2427,7 @@ async function confirmRenameSession() {
2355
2427
  setSessionRecovery('resuming')
2356
2428
  try {
2357
2429
  const value = await safeRpc('session.rename', { sessionId, title }, t('ds.sessionRenameFailed'))
2430
+ if (!connection.valid() || renamePendingSessionId !== sessionId) return
2358
2431
  if (value == null) { setSessionRecovery('error'); return }
2359
2432
  if (value.title) applyProjection(sessionId, 'title', value.title, value.seq)
2360
2433
  closeRenameSession()
@@ -2369,11 +2442,12 @@ async function confirmRenameSession() {
2369
2442
  async function archiveCurrentSession() {
2370
2443
  const sessionId = state.current
2371
2444
  if (!sessionId || !confirm(t('ds.sessionArchiveConfirm'))) return
2445
+ const connection = captureConnection()
2372
2446
  const value = await safeRpc('workspace.archiveSession', { sessionId }, t('ds.toastOpFailed'))
2373
- if (!value) return
2447
+ if (!value || !connection.valid()) return
2374
2448
  if (Array.isArray(value.archivedSessionIds)) state.archivedIds = value.archivedSessionIds
2375
2449
  toast(t('ds.sessionArchived'), 'ok')
2376
- closeSession()
2450
+ if (state.current === sessionId) await closeSession()
2377
2451
  await refreshSessions()
2378
2452
  }
2379
2453
 
@@ -2513,18 +2587,21 @@ function renderNotifStack() {
2513
2587
  renderOverviewDesktop()
2514
2588
  }
2515
2589
  async function approveApproval(id, allow) {
2590
+ const connection = captureConnection()
2516
2591
  const a = state.approvals.find(x => x.approvalId === id)
2517
2592
  if (!a) return
2518
2593
  let ok
2519
2594
  try {
2520
2595
  ok = await respond(a.rpcId, { sessionId: a.sessionId, approvalId: a.approvalId, outcome: allow ? 'allowed-once' : 'rejected' })
2521
2596
  } catch (e) {
2597
+ if (!connection.valid()) return
2522
2598
  if (e.message === 'AUTH') toast(t('ds.toastAuth'), 'err')
2523
2599
  else toast(t('ds.pendingSubmitFailed', { msg: e.message || t('ds.feedbackNetworkError') }), 'err')
2524
2600
  return
2525
2601
  }
2602
+ if (!connection.valid()) return
2526
2603
  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)
2604
+ state.approvals = state.approvals.filter(x => x.rpcId !== a.rpcId)
2528
2605
  renderNotifStack()
2529
2606
  }
2530
2607
  function openQuestionModal(q) {
@@ -2540,6 +2617,7 @@ function openQuestionModal(q) {
2540
2617
  $('modal-question').classList.remove('hidden')
2541
2618
  }
2542
2619
  async function submitQuestion() {
2620
+ const connection = captureConnection()
2543
2621
  const q = state.questionModal
2544
2622
  if (!q) return
2545
2623
  const answers = q.questions.map((item, i) => {
@@ -2555,13 +2633,15 @@ async function submitQuestion() {
2555
2633
  try {
2556
2634
  ok = await respond(q.rpcId, { sessionId: q.sessionId, answer: { answers } })
2557
2635
  } catch (e) {
2636
+ if (!connection.valid()) return
2558
2637
  if (e.message === 'AUTH') toast(t('ds.toastAuth'), 'err')
2559
2638
  else toast(t('ds.pendingSubmitFailed', { msg: e.message || t('ds.feedbackNetworkError') }), 'err')
2560
2639
  return
2561
2640
  }
2641
+ if (!connection.valid()) return
2562
2642
  if (ok) {
2563
2643
  toast(t('ds.questionSubmitted'), 'ok')
2564
- $('modal-question').classList.add('hidden')
2644
+ if (state.questionModal === q) { $('modal-question').classList.add('hidden'); state.questionModal = null }
2565
2645
  state.questions = state.questions.filter(x => x.rpcId !== q.rpcId)
2566
2646
  renderNotifStack()
2567
2647
  } else toast(t('ds.stale'), 'err')
@@ -3045,6 +3125,7 @@ async function openNewSessionModal() {
3045
3125
  function closeNewSessionModal() { $('modal-new-session').classList.add('hidden') }
3046
3126
  async function createSessionInWorkspace() {
3047
3127
  if (createSessionInWorkspace.busy) return
3128
+ const connection = captureConnection()
3048
3129
  const workspaceId = $('new-session-workspace').value
3049
3130
  if (!workspaceById(workspaceId)) return toast(t('ds.newSessionChooseWorkspace'), 'err')
3050
3131
  createSessionInWorkspace.busy = true
@@ -3052,10 +3133,11 @@ async function createSessionInWorkspace() {
3052
3133
  button.disabled = true
3053
3134
  try {
3054
3135
  const value = await safeRpc('session.create', { workspaceId }, '')
3055
- if (!value?.sessionId) return
3136
+ if (!connection.valid() || !value?.sessionId) return
3056
3137
  LS.set('lastNewSessionWorkspaceV1', workspaceId)
3057
3138
  closeNewSessionModal()
3058
3139
  await refreshSessions()
3140
+ if (!connection.valid()) return
3059
3141
  openSession(value.sessionId)
3060
3142
  } finally {
3061
3143
  createSessionInWorkspace.busy = false
@@ -3070,8 +3152,10 @@ function openWorkbenchModal() {
3070
3152
  wbFsLoad(null)
3071
3153
  setTimeout(() => $('wb-path-input').focus(), 50)
3072
3154
  }
3073
- function closeWorkbenchModal() { $('modal-workbench').classList.add('hidden') }
3155
+ function closeWorkbenchModal() { wbFs.request = (wbFs.request || 0) + 1; $('modal-workbench').classList.add('hidden') }
3074
3156
  async function wbFsLoad(dir) {
3157
+ const connection = captureConnection(), request = wbFs.request = (wbFs.request || 0) + 1
3158
+ const valid = () => connection.valid() && request === wbFs.request
3075
3159
  const box = $('wb-fs-list')
3076
3160
  const target = dir ?? wbFs.path ?? ''
3077
3161
  box.innerHTML = `<div class="ds-empty">${esc(t('ds.loading'))}</div>`
@@ -3079,6 +3163,7 @@ async function wbFsLoad(dir) {
3079
3163
  try {
3080
3164
  const res = await fetch(fsApiUrl('/list', target ? { path: target } : {}), { headers: fsHeaders() })
3081
3165
  const data = await res.json().catch(() => ({}))
3166
+ if (!valid()) return
3082
3167
  if (!res.ok || !Array.isArray(data.entries)) throw new Error(data.error || ('HTTP ' + res.status))
3083
3168
  wbFs.path = data.path
3084
3169
  if (!wbFs.initial) wbFs.initial = data.path
@@ -3091,6 +3176,7 @@ async function wbFsLoad(dir) {
3091
3176
  box.querySelectorAll('[data-wb-dir]').forEach(row => row.addEventListener('click', e => { if (!e.target.closest('[data-wb-select]')) wbFsLoad(row.dataset.wbDir) }))
3092
3177
  box.querySelectorAll('[data-wb-select]').forEach(button => button.addEventListener('click', () => bindWorkbench(button.dataset.wbSelect)))
3093
3178
  } catch (e) {
3179
+ if (!valid()) return
3094
3180
  $('wb-fs-path').textContent = target || '~'
3095
3181
  box.innerHTML = `<div class="ds-empty">${esc(e.message || t('ds.toastConnFailed'))}</div>`
3096
3182
  }
@@ -3102,38 +3188,49 @@ function wbFsUp() {
3102
3188
  }
3103
3189
  }
3104
3190
  async function bindWorkbench(rawPath) {
3191
+ const connection = captureConnection()
3105
3192
  const value = String(rawPath || '').trim()
3106
3193
  if (!value) return toast(t('wb.pathEmpty'), 'err')
3107
3194
  try {
3108
3195
  const wb = await wbGateway('POST', '/workbench/bind', { path: value })
3196
+ if (!connection.valid()) return
3109
3197
  state.wb = { bound: true, path: wb.path || value, title: wb.title || '', expanded: true, projects: null, open: null, apiMissing: false }
3110
3198
  const paths = [state.wb.path]
3111
3199
  try {
3112
3200
  const res = await fetch(fsApiUrl('/list', { path: state.wb.path }), { headers: fsHeaders() })
3113
3201
  const data = await res.json().catch(() => ({}))
3202
+ if (!connection.valid()) return
3114
3203
  for (const e of data.entries || []) if (e.type === 'dir') paths.push(wbJoin(state.wb.path, e.name))
3115
3204
  } catch {}
3116
3205
  for (const projectPath of paths) {
3206
+ if (!connection.valid()) return
3117
3207
  try { await rpc('workspace.create', { path: projectPath }) } catch {}
3118
3208
  }
3209
+ if (!connection.valid()) return
3119
3210
  closeWorkbenchModal()
3120
3211
  await refreshWorkbench({ silent: true })
3212
+ if (!connection.valid()) return
3121
3213
  await refreshSessions()
3214
+ if (!connection.valid()) return
3122
3215
  toast(t('wb.boundOk', { path: state.wb.path }), 'ok')
3123
3216
  } catch (e) {
3217
+ if (!connection.valid()) return
3124
3218
  if (e.message === 'AUTH') return toast(t('ds.toastAuth'), 'err')
3125
3219
  toast(t('wb.bindFailed', { msg: e.message }), 'err')
3126
3220
  }
3127
3221
  }
3128
3222
  async function unbindWorkbench() {
3129
3223
  if (!confirm(t('wb.unbindConfirm'))) return
3224
+ const connection = captureConnection()
3130
3225
  try {
3131
3226
  await wbGateway('POST', '/workbench/unbind')
3227
+ if (!connection.valid()) return
3132
3228
  state.wb = { bound: false, path: '', title: '', expanded: false, projects: null, open: null, apiMissing: false }
3133
3229
  renderWorkbench()
3134
3230
  renderSessions()
3135
3231
  toast(t('wb.unboundOk'), 'ok')
3136
3232
  } catch (e) {
3233
+ if (!connection.valid()) return
3137
3234
  if (e.message === 'AUTH') return toast(t('ds.toastAuth'), 'err')
3138
3235
  toast(t('wb.unbindFailed', { msg: e.message }), 'err')
3139
3236
  }
@@ -3253,7 +3350,7 @@ async function probeOverviewLinks(signal) {
3253
3350
  const controller=new AbortController(),cancel=()=>controller.abort()
3254
3351
  signal.addEventListener('abort',cancel,{once:true});if(signal.aborted)controller.abort()
3255
3352
  timer=setTimeout(cancel,4000)
3256
- const healthRequest=fetch(base+'/health?t='+Date.now(),{signal:controller.signal,cache:'no-store'}).then(async response=>{
3353
+ const healthRequest=fetch(base+'/health?probe=live&t='+Date.now(),{signal:controller.signal,cache:'no-store'}).then(async response=>{
3257
3354
  if(!response.ok)throw Error('health')
3258
3355
  const health=await response.json();if(health?.ok!==true)throw Error('health')
3259
3356
  return health
@@ -3694,6 +3791,10 @@ function bindUi() {
3694
3791
  try { await navigator.clipboard.writeText(state.token); toast(t('ds.toastCopied'), 'ok') }
3695
3792
  catch { toast(t('ds.toastOpFailed'), 'err') }
3696
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
+ })
3697
3798
  $('btn-theme').addEventListener('click', () => {
3698
3799
  const cur = themeGet() || 'default'
3699
3800
  const idx = THEME_META.findIndex(m => m.id === cur)
@@ -3717,6 +3818,19 @@ function bindUi() {
3717
3818
  $('btn-question-cancel').addEventListener('click', () => { $('modal-question').classList.add('hidden'); toast(t('ds.ignored'), 'ok') })
3718
3819
  }
3719
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
+
3720
3834
  async function start() {
3721
3835
  const urlToken = new URLSearchParams(location.search).get('token')?.trim() || ''
3722
3836
  if (urlToken) {
@@ -3735,12 +3849,9 @@ async function start() {
3735
3849
  LS.set('token', urlToken)
3736
3850
  saveServers()
3737
3851
  }
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
3852
  $('token-desc').textContent = state.token ? '● ' + state.token.slice(0, 12) + '…' : t('ds.toastAuth')
3743
3853
  bindUi()
3854
+ if (!state.token) { showView('view-settings'); $('desktop-token-input').focus() }
3744
3855
  renderWorkbench()
3745
3856
  updateConn()
3746
3857
  checkNotesOnStart()