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.
package/public/app.js CHANGED
@@ -115,10 +115,17 @@ for (const key of ['server', 'token']) {
115
115
  set(next) {
116
116
  if (next === value) return
117
117
  value = next; connectionGeneration++
118
+ clearTimeout(state.refreshTimer); state.refreshTimer = null
118
119
  state.sessions = []; state.byId.clear(); state.pendingProjections.clear()
119
120
  state.hostInfo = null
120
121
  if(typeof closeStream==='function'&&typeof streamMeta!=='undefined'){closeStream('mux');closeStream('host')}
121
122
  state.current = null; state.history = emptyHistory()
123
+ state.models = { loaded: false, loading: false, groups: [], current: null, failures: [] }
124
+ state.modelSettings = { status: 'idle', error: '', writable: false, hasDocument: false, providers: [], namespaces: [], credentials: {} }; state.modelEditor = null
125
+ state.goalEdit = null; state.goalEditContext = null
126
+ state.approvals = []; state.questions = []; state.questionModal = null
127
+ state.queues = {}; state.jobs = {}; state.queueSteering = {}; state.compactions = {}; state.pendingCommands = {}; state.sessionTurnTimes = {}
128
+ state.sessionActivity = new Set(); state.pendingPrompts = new Set()
122
129
  state.fs.path = null; state.fs.initial = null; state.fs.loaded = false; state.fs.roots = []; state.fs.rootIndex = 0
123
130
  state.wb = null; state.wbProjects = []; state.wbArchived = []; state.workspaceFilter = ''; state.fs.workspaceId = ''; clearTimeout(scheduleHistoryCacheSave._t)
124
131
  window.DshPluginCenter?.close()
@@ -132,6 +139,9 @@ for (const key of ['server', 'token']) {
132
139
  }
133
140
  if (typeof document !== 'undefined') {
134
141
  document.getElementById('modal-workspace')?.classList.add('hidden')
142
+ for (const id of ['modal-question', 'modal-new-session', 'modal-rename', 'modal-archive', 'modal-goal']) document.getElementById(id)?.classList.add('hidden')
143
+ if (typeof renderPending === 'function') renderPending()
144
+ if (typeof renderModelSettings === 'function') renderModelSettings()
135
145
  const generation = connectionGeneration
136
146
  queueMicrotask(() => {
137
147
  if (generation === connectionGeneration && document.getElementById('view-plugins')?.classList.contains('hidden') === false) openPluginPage()
@@ -433,14 +443,16 @@ function apiUrl(path) {
433
443
  }
434
444
 
435
445
  let wsTicketPromise = null
446
+ let wsTicketConnection = null
436
447
  async function getWsTicket() {
437
448
  const now = Date.now()
438
449
  if (state.wsTicket.token === state.token && state.wsTicket.server === state.server &&
439
450
  state.wsTicket.value && state.wsTicket.expiresAt > now + 15000) return state.wsTicket.value
440
- if (wsTicketPromise) return wsTicketPromise
451
+ if (wsTicketPromise && wsTicketConnection?.valid()) return wsTicketPromise
452
+ const connection = captureConnection()
441
453
  const token = state.token
442
454
  const server = state.server
443
- wsTicketPromise = (async () => {
455
+ const job = (async () => {
444
456
  if (activeGatewayCapability('wsTicket') === false) throw new Error('ws ticket unsupported')
445
457
  const res = await fetch(apiUrl('/api/ws-ticket'), {
446
458
  method: 'POST',
@@ -452,11 +464,14 @@ async function getWsTicket() {
452
464
  })
453
465
  if (!res.ok) throw new Error('ws ticket HTTP ' + res.status)
454
466
  const data = await res.json()
467
+ if (!connection.valid()) throw new Error('stale ws ticket')
455
468
  if (!data?.ticket || !Number(data.expiresAt)) throw new Error('invalid ws ticket')
456
469
  state.wsTicket = { token, server, value: data.ticket, expiresAt: Number(data.expiresAt) }
457
470
  return data.ticket
458
471
  })()
459
- try { return await wsTicketPromise } finally { wsTicketPromise = null }
472
+ wsTicketPromise = job
473
+ wsTicketConnection = connection
474
+ try { return await job } finally { if (wsTicketPromise === job) { wsTicketPromise = null; wsTicketConnection = null } }
460
475
  }
461
476
 
462
477
  function updateBase() {
@@ -525,7 +540,7 @@ async function respond(rpcId, value) {
525
540
 
526
541
  async function safeRpc(method, payload, errText) {
527
542
  const connection = captureConnection()
528
- try { return await rpc(method, payload) }
543
+ try { const value = await rpc(method, payload); return connection.valid() ? value : null }
529
544
  catch (e) {
530
545
  if (!connection.valid()) return null
531
546
  if (e.message === 'AUTH') authFailure()
@@ -718,7 +733,7 @@ async function pingServer(base) {
718
733
  const ctrl = new AbortController()
719
734
  const timer = setTimeout(() => ctrl.abort(), 3500)
720
735
  try {
721
- const res = await fetch(u + '/health?t=' + Date.now(), { signal: ctrl.signal, cache: 'no-store' })
736
+ const res = await fetch(u + '/health?probe=live&t=' + Date.now(), { signal: ctrl.signal, cache: 'no-store' })
722
737
  if (!res.ok) return Infinity
723
738
  const health = await res.json().catch(() => null)
724
739
  if (health && typeof health === 'object') {
@@ -751,7 +766,10 @@ function dshReachable() {
751
766
  }
752
767
 
753
768
  async function selectFastestServer({ silent = false, reconnect = true } = {}) {
754
- if (state.selectingServer) return null
769
+ const request = selectFastestServer.request = (selectFastestServer.request || 0) + 1
770
+ const connection = captureConnection(), group = state.activeGroup
771
+ const policy = JSON.stringify([state.autoSelect[group], state.groupActive[group], state.servers])
772
+ const valid = () => connection.valid() && request === selectFastestServer.request && state.activeGroup === group && policy === JSON.stringify([state.autoSelect[group], state.groupActive[group], state.servers])
755
773
  state.selectingServer = true
756
774
  try {
757
775
  if (!silent) toast(t('speed.testing'))
@@ -763,6 +781,7 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
763
781
 
764
782
  if (state.autoSelect[state.activeGroup] !== false) {
765
783
  const measured = await Promise.all(candidates.map(async (server) => [server, await pingServer(server.url)]))
784
+ if (!valid()) return null
766
785
  for (const [server, latency] of measured) state.serverLatency[serverKey(server)] = latency
767
786
  best = candidates
768
787
  .filter(server => Number.isFinite(state.serverLatency[serverKey(server)]))
@@ -783,6 +802,8 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
783
802
  }
784
803
  }
785
804
 
805
+ if (!valid()) return null
806
+ if (typeof window !== 'undefined') window.DshNetwork?.observeLatency(ms)
786
807
  renderServers()
787
808
  if (chosen !== state.server || chosenToken !== state.token) {
788
809
  state.hostInfo = null
@@ -813,7 +834,7 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
813
834
  await maybeWarnAppBehindGateway()
814
835
  return chosen
815
836
  } finally {
816
- state.selectingServer = false
837
+ if (request === selectFastestServer.request) state.selectingServer = false
817
838
  }
818
839
  }
819
840
 
@@ -1345,43 +1366,46 @@ function enterPollMode() {
1345
1366
  }
1346
1367
 
1347
1368
  function stopPolling() {
1348
- clearInterval(pollTimer)
1349
- pollTimer = null
1350
- clearTimeout(wsRetryTimer)
1351
- wsRetryTimer = null
1369
+ pollInFlight?.stop()
1370
+ pollInFlight = null
1371
+ clearInterval(pollTimer); pollTimer = null
1372
+ clearInterval(wsRetryTimer); wsRetryTimer = null
1352
1373
  }
1353
-
1354
1374
  function startPolling() {
1355
1375
  stopPolling()
1356
1376
  pollTimer = setInterval(pollOnce, 4000)
1357
1377
  wsRetryTimer = setInterval(tryRestoreWs, 30000)
1358
- pollOnce()
1378
+ void pollOnce()
1359
1379
  }
1360
-
1361
- let pollInFlight = false
1380
+ let pollInFlight = null
1362
1381
  async function pollOnce() {
1363
- if (state.streamMode !== 'poll' || pollInFlight) return
1364
- pollInFlight = true
1365
- try {
1366
- await Promise.all([pollKind('mux'), pollKind('host')])
1367
- } finally {
1368
- pollInFlight = false
1369
- }
1382
+ if (state.streamMode !== 'poll') return
1383
+ if (!pollInFlight) pollInFlight = new window.DshNetwork.PollLoop({
1384
+ active: () => state.streamMode === 'poll' && !!state.token,
1385
+ capture: () => { const connection = captureConnection(), cursors = state.pollSeq; return { valid: () => connection.valid() && state.pollSeq === cursors } },
1386
+ read: pollKind
1387
+ })
1388
+ return pollInFlight.tick()
1370
1389
  }
1371
1390
 
1372
- async function pollKind(kind) {
1391
+ async function pollKind(kind, cancellation) {
1373
1392
  if (state.streamMode !== 'poll') return
1393
+ const connection = captureConnection(), cursors = state.pollSeq
1394
+ const valid = () => connection.valid() && state.streamMode === 'poll' && state.pollSeq === cursors && !cancellation?.aborted
1374
1395
  const since = state.pollSeq[kind] || 0
1375
1396
  let res
1376
1397
  try {
1377
- const signal = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(30000) : undefined
1398
+ const timeout = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(window.DshNetwork?.profile().pollTimeout || 30000) : undefined
1399
+ const signal = cancellation && timeout && typeof AbortSignal.any === 'function' ? AbortSignal.any([cancellation, timeout]) : timeout || cancellation
1378
1400
  const headers = { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }
1379
1401
  res = signal ? await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000`), { signal, headers }) : await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000`), { headers })
1380
1402
  } catch { return }
1403
+ if (!valid()) return
1381
1404
  if (res.status === 401) { authFailure(); return }
1382
1405
  if (!res.ok) return
1383
1406
  let data
1384
1407
  try { data = await res.json() } catch { return }
1408
+ if (!valid()) return
1385
1409
  if (!data || !Array.isArray(data.events)) return
1386
1410
  // 网关重启或客户端离线过久后,游标可能落后于内存环形缓冲;
1387
1411
  // 从当前缓冲重新接收,并刷新权威会话列表,避免静默漏事件。
@@ -1403,6 +1427,7 @@ async function pollKind(kind) {
1403
1427
  else onHostFrame(item.event)
1404
1428
  }
1405
1429
  }
1430
+ return data.waitSupported === true ? 100 : 4000
1406
1431
  }
1407
1432
 
1408
1433
  function tryRestoreWs() {
@@ -1630,8 +1655,9 @@ function onSessionEvent(sessionId, event) {
1630
1655
 
1631
1656
  /* ---------------- 数据刷新 ---------------- */
1632
1657
  function scheduleRefresh() {
1633
- clearTimeout(state.refreshTimer)
1634
- state.refreshTimer = setTimeout(refreshAll, 700)
1658
+ if (state.refreshTimer) return
1659
+ const connection = captureConnection()
1660
+ state.refreshTimer = setTimeout(() => { state.refreshTimer = null; if (connection.valid()) void refreshAll() }, 700)
1635
1661
  }
1636
1662
 
1637
1663
  async function refreshAll() {
@@ -2520,12 +2546,13 @@ async function loadHistory(reset = true) {
2520
2546
  const reasoningVersion=history.reasoningVersion||0,hadContent=history.visible.length>0
2521
2547
  history.loading=true
2522
2548
  if(reset){if(hadContent)historySource('syncing');else setSessionRecovery('loading')}
2523
- const payload={sessionId:id,maxMessages:60}
2549
+ const network=window.DshNetwork?.profile() || {historyPageSize:60,readTimeout:45000}
2550
+ const payload={sessionId:id,maxMessages:network.historyPageSize}
2524
2551
  if(!reset&&Number.isFinite(history.minSeq))payload.beforeSeq=history.minSeq
2525
2552
  getConversationView().more.disabled=true
2526
2553
  getConversationView().more.textContent=getConversationView().options.loadingLabel()
2527
2554
  let v
2528
- try{v=await rpc('session.history',payload)}catch(error){
2555
+ try{v=await rpc('session.history',payload,network.readTimeout)}catch(error){
2529
2556
  if(!connection.valid()||state.current!==id||state.history!==history)return
2530
2557
  history.loading=false;history.retryAfter=Date.now()+1500
2531
2558
  if(error.message==='AUTH'){authFailure();return}
@@ -2572,8 +2599,7 @@ function insertLiveEvent(event) {
2572
2599
  return
2573
2600
  }
2574
2601
  h.seqs.add(seq)
2575
- h.visible.push({ seq, event })
2576
- h.visible.sort((a, b) => a.seq - b.seq)
2602
+ window.DshHistory.insertSorted(h.visible, { seq, event })
2577
2603
  trimVisible()
2578
2604
  renderHistory(false, 'fixed')
2579
2605
  scheduleHistoryCacheSave()
@@ -2771,8 +2797,20 @@ function statsHtml(s) {
2771
2797
  return html || '<div class="empty">' + t('stats.empty') + '</div>'
2772
2798
  }
2773
2799
 
2800
+ let sessionSubagentsJob = null
2801
+ async function loadSessionSubagents(sessionId) {
2802
+ if (sessionSubagentsJob?.sessionId === sessionId && sessionSubagentsJob.connection.valid()) return sessionSubagentsJob.promise
2803
+ const connection = captureConnection(), job = { sessionId, connection }
2804
+ job.promise = (async () => {
2805
+ const value = await safeRpc('subagent.list', { parentSessionId: sessionId }, '')
2806
+ return connection.valid() ? value : null
2807
+ })()
2808
+ sessionSubagentsJob = job
2809
+ try { return await job.promise } finally { if (sessionSubagentsJob === job) sessionSubagentsJob = null }
2810
+ }
2774
2811
  let sessionCardsRenderGeneration = 0
2775
2812
  async function renderSessionCards() {
2813
+ const connection = captureConnection()
2776
2814
  window.DshInsights?.update()
2777
2815
  const renderGeneration = ++sessionCardsRenderGeneration
2778
2816
  const sessionId = state.current
@@ -2824,8 +2862,8 @@ async function renderSessionCards() {
2824
2862
  }))
2825
2863
 
2826
2864
  // 子代理
2827
- const sub = await safeRpc('subagent.list', { parentSessionId: sessionId })
2828
- if (renderGeneration !== sessionCardsRenderGeneration || state.current !== sessionId) return
2865
+ const sub = await loadSessionSubagents(sessionId)
2866
+ if (!connection.valid() || renderGeneration !== sessionCardsRenderGeneration || state.current !== sessionId) return
2829
2867
  if (sub?.entries?.length) {
2830
2868
  const expanded = state.subagentExpandedSession === sessionId
2831
2869
  const toggleLabel = expanded ? t('subagent.collapse') : t('subagent.expand')
@@ -2861,6 +2899,8 @@ function setGoalPhaseLocal(phase) {
2861
2899
  }
2862
2900
 
2863
2901
  async function goalAction(kind) {
2902
+ const connection = captureConnection(), sessionId = state.current, history = state.history
2903
+ const valid = () => connection.valid() && state.current === sessionId && state.history === history
2864
2904
  const s = state.byId.get(state.current)
2865
2905
  const goal = goalOf(s)
2866
2906
  if (!goal) return toast(t('goal.none'))
@@ -2871,8 +2911,8 @@ async function goalAction(kind) {
2871
2911
  if (!method) return
2872
2912
  if (kind === 'clear' && !confirm(t('goal.confirmClear'))) return
2873
2913
  if (kind === 'complete' && !confirm(t('goal.confirmComplete'))) return
2874
- const result = await safeRpc(method, { sessionId: state.current, ref }, t('goal.actionFailed'))
2875
- if (result == null) return
2914
+ const result = await safeRpc(method, { sessionId, ref }, t('goal.actionFailed'))
2915
+ if (result == null || !valid()) return
2876
2916
  if (kind === 'complete') setGoalPhaseLocal('complete')
2877
2917
  if (kind === 'clear') setGoalPhaseLocal('cleared')
2878
2918
  toast(t('goal.actionSubmitted'), 'ok')
@@ -2913,19 +2953,22 @@ function sessionLogExportUrl(sessionId, includeToken = false) {
2913
2953
  }
2914
2954
 
2915
2955
  async function downloadSessionExport(sessionId) {
2956
+ const connection = captureConnection()
2916
2957
  const nativePlatform = !!CAP?.isNativePlatform?.()
2917
2958
  const nativeDownload = !!(nativePlatform && window.NativeFile?.downloadToDownloads)
2918
2959
  if (nativePlatform && !nativeDownload) {
2919
2960
  toast(t('fs.downloadUnsupported'), 'err')
2920
2961
  return
2921
2962
  }
2922
- const url = sessionLogExportUrl(sessionId, !nativeDownload && !!state.server)
2963
+ const pluginOrigin = location.pathname === '/remote' || location.pathname.startsWith('/remote/')
2964
+ const url = sessionLogExportUrl(sessionId, !nativeDownload && (!!state.server || !pluginOrigin))
2923
2965
  const headers = state.token ? { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() } : {}
2924
2966
  try {
2925
2967
  const signal = typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'
2926
2968
  ? AbortSignal.timeout(LONG_RUNNING_SLASH_COMMAND_TIMEOUT_MS)
2927
2969
  : undefined
2928
2970
  const preflight = await fetch(url, { method: 'HEAD', headers, ...(signal ? { signal } : {}) })
2971
+ if (!connection.valid()) return
2929
2972
  if (preflight.status === 401) { authFailure(); return }
2930
2973
  if (!preflight.ok) throw new Error('HTTP ' + preflight.status)
2931
2974
  const filename = sessionLogFilename(sessionId)
@@ -2951,6 +2994,7 @@ async function downloadSessionExport(sessionId) {
2951
2994
  async function runSlashCommand(text) {
2952
2995
  const clean = String(text || '').trim()
2953
2996
  if (!clean.startsWith('/') || !state.current) return false
2997
+ const sessionId = state.current, connection = captureConnection()
2954
2998
  const command = slashCommandName(clean)
2955
2999
  const noFallback = NO_FALLBACK_SLASH_COMMANDS.has(command)
2956
3000
  const longRunning = command === 'export'
@@ -2961,37 +3005,39 @@ async function runSlashCommand(text) {
2961
3005
  const res = await fetch(apiUrl('/remote/api/command'), {
2962
3006
  method: 'POST',
2963
3007
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() },
2964
- body: JSON.stringify({ sessionId: state.current, line: clean }),
3008
+ body: JSON.stringify({ sessionId, line: clean }),
2965
3009
  ...(signal ? { signal } : {})
2966
3010
  })
3011
+ if (!connection.valid()) return true
2967
3012
  if (res.status === 401) { authFailure(); return true }
2968
3013
  if (!res.ok) {
2969
3014
  if (noFallback) toast(t('session.commandTimedOut'), 'err')
2970
3015
  return noFallback
2971
3016
  }
2972
3017
  const data = await res.json().catch(() => null)
3018
+ if (!connection.valid()) return true
2973
3019
  if (data?.ok === false) { toast(data.message || t('send.failed'), 'err'); return true }
2974
3020
  if (data?.ok && data.executed === true) {
2975
3021
  if (data.accepted) {
2976
3022
  if (command === 'compact') {
2977
- setCompactionStatus(state.current, { ...(data.operation || data.compact), active: true, command, source: 'command' })
3023
+ setCompactionStatus(sessionId, { ...(data.operation || data.compact), active: true, command, source: 'command' })
2978
3024
  } else {
2979
- const sessionId = state.current
2980
3025
  state.pendingCommands[sessionId] = command
2981
- setTimeout(() => { if (state.current === sessionId) void refreshCompactionStatus(sessionId) }, 600)
3026
+ setTimeout(() => { if (connection.valid() && state.current === sessionId) void refreshCompactionStatus(sessionId) }, 600)
2982
3027
  }
2983
- } else if (command === 'export') await downloadSessionExport(state.current)
3028
+ } else if (command === 'export') await downloadSessionExport(sessionId)
2984
3029
  else toast(t('send.commandExecuted'), 'ok')
2985
3030
  return true
2986
3031
  }
2987
3032
  } catch (e) {
3033
+ if (!connection.valid() || state.current !== sessionId) return true
2988
3034
  console.error('slash command bridge failed', e)
2989
3035
  if (noFallback) {
2990
3036
  toast(t('session.commandTimedOut'), 'err')
2991
3037
  return true
2992
3038
  }
2993
3039
  }
2994
- return false
3040
+ return !connection.valid() || state.current !== sessionId
2995
3041
  }
2996
3042
 
2997
3043
  function bytesToBase64(bytes) {
@@ -3208,12 +3254,13 @@ async function sendSessionContent(text, images, requestedMode = 'queue') {
3208
3254
  composerSending = true
3209
3255
  const buttons = [$('btn-send'), $('btn-fs-send')].filter(Boolean)
3210
3256
  buttons.forEach(button => { button.disabled = true })
3211
- state.pendingPrompts.add(sessionId)
3257
+ const pendingPrompts = state.pendingPrompts, sessionActivity = state.sessionActivity
3258
+ pendingPrompts.add(sessionId)
3212
3259
  try {
3213
3260
  if (mode === 'steer') setComposerSendFeedback(context, 'send.steerPending', 'pending')
3214
3261
  else { composerSendFeedback.delete(context); renderComposerSend() }
3215
3262
  if (images.length === 0 && clean && await runSlashCommand(clean)) {
3216
- state.sessionActivity.add(sessionId)
3263
+ sessionActivity.add(sessionId)
3217
3264
  return true
3218
3265
  }
3219
3266
  const content = [...await encodeComposerImagesFor(images)]
@@ -3257,7 +3304,7 @@ async function sendSessionContent(text, images, requestedMode = 'queue') {
3257
3304
  }
3258
3305
  return false
3259
3306
  } finally {
3260
- state.pendingPrompts.delete(sessionId)
3307
+ pendingPrompts.delete(sessionId)
3261
3308
  composerSending = false
3262
3309
  buttons.forEach(button => { button.disabled = false })
3263
3310
  renderComposerSend()
@@ -3309,16 +3356,21 @@ function mobileEnterAction() {
3309
3356
 
3310
3357
  async function loadSessionModels() {
3311
3358
  if (!state.current || state.models.loading) return
3312
- state.models.loading = true
3359
+ const connection = captureConnection(), sessionId = state.current, models = state.models
3360
+ const request = models.request = (models.request || 0) + 1
3361
+ const valid = () => connection.valid() && state.current === sessionId && state.models === models && models.request === request
3362
+ models.loading = true
3313
3363
  renderModelMenu()
3314
3364
  try {
3315
- const v = await rpc('session.models', { sessionId: state.current })
3316
- state.models.groups = v.groups || []
3317
- state.models.current = v.current || null
3318
- state.models.failures = v.failures || []
3319
- state.models.loaded = true
3365
+ const v = await rpc('session.models', { sessionId })
3366
+ if (!valid()) return
3367
+ models.groups = v.groups || []
3368
+ models.current = v.current || null
3369
+ models.failures = v.failures || []
3370
+ models.loaded = true
3320
3371
  } catch (e) {
3321
- if (e.message === 'AUTH') { authFailure(); return }
3372
+ if (!valid()) return
3373
+ if (e.message === 'AUTH') { models.loading = false; renderModelMenu(); authFailure(); return }
3322
3374
  toast(t('models.loadFailed', { msg: e.message }), 'err')
3323
3375
  }
3324
3376
  state.models.loading = false
@@ -3391,9 +3443,12 @@ function reasoningEffortOptions(model) {
3391
3443
  async function selectSessionEffort(effortId) {
3392
3444
  const cur = state.models.current
3393
3445
  if (!state.current || !cur) return
3446
+ const connection = captureConnection(), sessionId = state.current, models = state.models
3447
+ const request = models.request = (models.request || 0) + 1
3394
3448
  const v = await safeRpc('session.selectModel', {
3395
- sessionId: state.current, provider: cur.provider, model: cur.model, reasoningEffort: effortId
3449
+ sessionId, provider: cur.provider, model: cur.model, reasoningEffort: effortId
3396
3450
  }, t('models.effortFailed'))
3451
+ if (!connection.valid() || state.current !== sessionId || state.models !== models || models.request !== request) return
3397
3452
  if (v?.selected) {
3398
3453
  state.models.current = v.selected
3399
3454
  renderEffortMenu()
@@ -3403,12 +3458,15 @@ async function selectSessionEffort(effortId) {
3403
3458
 
3404
3459
  async function selectSessionModel(provider, modelId) {
3405
3460
  if (!state.current) return
3461
+ const connection = captureConnection(), sessionId = state.current, models = state.models
3462
+ const request = models.request = (models.request || 0) + 1
3406
3463
  const group = (state.models.groups || []).find(g => g.id === provider)
3407
3464
  const model = (group?.models || []).find(m => m.id === modelId)
3408
- const payload = { sessionId: state.current, provider, model: modelId }
3465
+ const payload = { sessionId, provider, model: modelId }
3409
3466
  const effort = model?.reasoning?.defaultEffort || model?.reasoning?.efforts?.[0]?.id
3410
3467
  if (effort) payload.reasoningEffort = effort
3411
3468
  const v = await safeRpc('session.selectModel', payload, t('models.switchFailed'))
3469
+ if (!connection.valid() || state.current !== sessionId || state.models !== models || models.request !== request) return
3412
3470
  if (v?.selected) {
3413
3471
  state.models.current = v.selected
3414
3472
  renderModelMenu()
@@ -3482,22 +3540,27 @@ function closeNewSessionModal() {
3482
3540
  $('modal-new-session').classList.add('hidden')
3483
3541
  }
3484
3542
  async function createSessionInWorkspace() {
3543
+ if (createSessionInWorkspace.busy) return
3544
+ const connection = captureConnection()
3485
3545
  const workspaceId = $('new-session-workspace').value
3486
3546
  if (!workspaceById(workspaceId)) return toast(t('newSession.chooseWorkspace'), 'err')
3487
3547
  const button = $('new-session-create')
3548
+ createSessionInWorkspace.busy = true
3488
3549
  button.disabled = true
3489
- const v = await safeRpc('session.create', { workspaceId: workspaceId }, t('home.createFailed'))
3490
- button.disabled = false
3491
- if (!v?.sessionId) return
3492
- state.workspaceFilter = workspaceId
3493
- state.fs.workspaceId = workspaceId
3494
- LS.set('workspaceFilterV1', workspaceId)
3495
- LS.set('fsWorkspaceIdV1', workspaceId)
3496
- LS.set('lastNewSessionWorkspaceV1', workspaceId)
3497
- closeNewSessionModal()
3498
- toast(t('home.created'), 'ok')
3499
- await refreshSessions()
3500
- openSession(v.sessionId)
3550
+ try {
3551
+ const v = await safeRpc('session.create', { workspaceId: workspaceId }, t('home.createFailed'))
3552
+ if (!connection.valid() || !v?.sessionId) return
3553
+ state.workspaceFilter = workspaceId
3554
+ state.fs.workspaceId = workspaceId
3555
+ LS.set('workspaceFilterV1', workspaceId)
3556
+ LS.set('fsWorkspaceIdV1', workspaceId)
3557
+ LS.set('lastNewSessionWorkspaceV1', workspaceId)
3558
+ closeNewSessionModal()
3559
+ toast(t('home.created'), 'ok')
3560
+ await refreshSessions()
3561
+ if (!connection.valid()) return
3562
+ openSession(v.sessionId)
3563
+ } finally { createSessionInWorkspace.busy = false; button.disabled = false }
3501
3564
  }
3502
3565
 
3503
3566
  let archivePendingSessionId = null
@@ -3608,7 +3671,7 @@ async function probeOverviewLinks(signal) {
3608
3671
  const controller=new AbortController(),cancel=()=>controller.abort()
3609
3672
  signal.addEventListener('abort',cancel,{once:true});if(signal.aborted)controller.abort()
3610
3673
  timer=setTimeout(cancel,4000)
3611
- const healthRequest=fetch(base+'/health?t='+Date.now(),{signal:controller.signal,cache:'no-store'}).then(async response=>{
3674
+ const healthRequest=fetch(base+'/health?probe=live&t='+Date.now(),{signal:controller.signal,cache:'no-store'}).then(async response=>{
3612
3675
  if(!response.ok)throw Error('health')
3613
3676
  const health=await response.json();if(health?.ok!==true)throw Error('health')
3614
3677
  return health
@@ -3801,18 +3864,21 @@ function renderSessionPending() {
3801
3864
  }
3802
3865
 
3803
3866
  async function approveApproval(id, allow) {
3867
+ const connection = captureConnection()
3804
3868
  const a = state.approvals.find(x => x.approvalId === id)
3805
3869
  if (!a) return
3806
3870
  let ok
3807
3871
  try {
3808
3872
  ok = await respond(a.rpcId, { sessionId: a.sessionId, approvalId: a.approvalId, outcome: allow ? 'allowed-once' : 'rejected' })
3809
3873
  } catch (e) {
3874
+ if (!connection.valid()) return
3810
3875
  if (e.message === 'AUTH') authFailure()
3811
3876
  else toast(t('pending.submitFailed', { msg: e.message || t('fs.networkError') }), 'err')
3812
3877
  return
3813
3878
  }
3879
+ if (!connection.valid()) return
3814
3880
  toast(ok ? (allow ? t('pending.allowed') : t('pending.rejected')) : t('pending.stale'), ok ? 'ok' : 'err')
3815
- state.approvals = state.approvals.filter(x => x.approvalId !== id)
3881
+ state.approvals = state.approvals.filter(x => x.rpcId !== a.rpcId)
3816
3882
  renderPending()
3817
3883
  }
3818
3884
 
@@ -3830,6 +3896,7 @@ function openQuestionModal(q) {
3830
3896
  }
3831
3897
 
3832
3898
  async function submitQuestion() {
3899
+ const connection = captureConnection()
3833
3900
  const q = state.questionModal
3834
3901
  if (!q) return
3835
3902
  const answers = q.questions.map((item, i) => {
@@ -3845,11 +3912,18 @@ async function submitQuestion() {
3845
3912
  try {
3846
3913
  ok = await respond(q.rpcId, { sessionId: q.sessionId, answer: { answers } })
3847
3914
  } catch (e) {
3915
+ if (!connection.valid()) return
3848
3916
  if (e.message === 'AUTH') authFailure()
3849
3917
  else toast(t('question.submitFailed', { msg: e.message || t('fs.networkError') }), 'err')
3850
3918
  return
3851
3919
  }
3852
- if (ok) { toast(t('question.submitted'), 'ok'); $('modal-question').classList.add('hidden'); state.questions = state.questions.filter(x => x.rpcId !== q.rpcId); renderPending() }
3920
+ if (!connection.valid()) return
3921
+ if (ok) {
3922
+ toast(t('question.submitted'), 'ok')
3923
+ if (state.questionModal === q) { $('modal-question').classList.add('hidden'); state.questionModal = null }
3924
+ state.questions = state.questions.filter(x => x.rpcId !== q.rpcId)
3925
+ renderPending()
3926
+ }
3853
3927
  else toast(t('question.stale'), 'err')
3854
3928
  }
3855
3929
 
@@ -4580,6 +4654,7 @@ function bindFsPullRefresh() {
4580
4654
  /* ---------------- goal 编辑 ---------------- */
4581
4655
  function openGoalModal(goal) {
4582
4656
  state.goalEdit = goal
4657
+ state.goalEditContext = { connection: captureConnection(), sessionId: state.current, history: state.history }
4583
4658
  $('goal-body').innerHTML = `
4584
4659
  <div class="kv"><span class="k">phase</span><span class="v">${esc(goal.phase || '?')}</span></div>
4585
4660
  <div class="kv"><span class="k">revision</span><span class="v">${goal.revision ?? '?'}</span></div>
@@ -4591,10 +4666,13 @@ function openGoalModal(goal) {
4591
4666
  async function submitGoalEdit() {
4592
4667
  const goal = state.goalEdit
4593
4668
  if (!goal) return
4669
+ const context = state.goalEditContext
4670
+ const valid = () => context?.connection.valid() && state.current === context.sessionId && state.history === context.history && state.goalEdit === goal
4671
+ if (!valid()) { $('modal-goal').classList.add('hidden'); return }
4594
4672
  const objective = $('goal-edit-text')?.value?.trim()
4595
4673
  if (!objective) return toast(t('goal.cannotEmpty'), 'err')
4596
- const result = await safeRpc('goal.edit', { sessionId: state.current, ref: { id: goal.id, revision: goal.revision }, objective }, t('goal.updateFailed'))
4597
- if (result == null) return
4674
+ const result = await safeRpc('goal.edit', { sessionId: context.sessionId, ref: { id: goal.id, revision: goal.revision }, objective }, t('goal.updateFailed'))
4675
+ if (result == null || !valid()) return
4598
4676
  $('modal-goal').classList.add('hidden')
4599
4677
  toast(t('goal.updated'), 'ok')
4600
4678
  scheduleRefresh()
@@ -5646,6 +5724,7 @@ function modelReasoningError(models) {
5646
5724
  }
5647
5725
 
5648
5726
  async function loadModelSettings(force = false) {
5727
+ const connection = captureConnection()
5649
5728
  if (!state.token) {
5650
5729
  state.modelSettings = { ...state.modelSettings, status: 'error', error: t('token.notSetHint') }
5651
5730
  renderModelSettings()
@@ -5660,6 +5739,7 @@ async function loadModelSettings(force = false) {
5660
5739
  rpc('llm.providers', {}),
5661
5740
  rpc('settings.describe', {})
5662
5741
  ])
5742
+ if (!connection.valid()) return
5663
5743
  const namespaces = Array.isArray(settingsValue?.namespaces) ? settingsValue.namespaces : []
5664
5744
  const providers = Array.isArray(providersValue?.providers) ? providersValue.providers : []
5665
5745
  const rows = providers.map(entry => {
@@ -5681,6 +5761,7 @@ async function loadModelSettings(force = false) {
5681
5761
  let credentials = {}
5682
5762
  if (refs.length > 0) {
5683
5763
  const value = await rpc('credentials.describe', { refs })
5764
+ if (!connection.valid()) return
5684
5765
  credentials = value?.credentials && typeof value.credentials === 'object' ? value.credentials : {}
5685
5766
  }
5686
5767
  state.modelSettings = {
@@ -5694,6 +5775,7 @@ async function loadModelSettings(force = false) {
5694
5775
  }
5695
5776
  state.modelEditor = null
5696
5777
  } catch (error) {
5778
+ if (!connection.valid()) return
5697
5779
  state.modelSettings = { ...state.modelSettings, status: 'error', error: error?.message || String(error) }
5698
5780
  }
5699
5781
  renderModelSettings()
@@ -5897,6 +5979,7 @@ function setModelEditorError(message) {
5897
5979
  async function discoverModelSettings() {
5898
5980
  const editor = state.modelEditor
5899
5981
  if (!editor || editor.busy) return
5982
+ const connection = captureConnection(), valid = () => connection.valid() && state.modelEditor === editor
5900
5983
  collectModelEditorForm()
5901
5984
  editor.busy = true
5902
5985
  editor.error = ''
@@ -5908,17 +5991,19 @@ async function discoverModelSettings() {
5908
5991
  if (editor.api) payload.api = editor.api
5909
5992
  if (editor.keyDraft.trim()) payload.apiKey = editor.keyDraft.trim()
5910
5993
  const value = await rpc('llm.discoverModels', payload)
5994
+ if (!valid()) return
5911
5995
  const found = Array.isArray(value?.models) ? value.models.filter(model => model && typeof model.id === 'string' && model.id.trim()) : []
5912
5996
  if (!found.length) throw new Error(t('settings.modelFetchEmpty'))
5913
5997
  const known = new Set(editor.models.map(model => model.id))
5914
5998
  editor.discovered = found
5915
5999
  editor.discoverySelected = new Set(found.filter(model => !known.has(model.id)).map(model => model.id))
5916
6000
  } catch (error) {
6001
+ if (!valid()) return
5917
6002
  editor.error = t('settings.modelFetchFailed', { msg: error?.message || String(error) })
5918
6003
  } finally {
5919
6004
  editor.busy = false
5920
6005
  }
5921
- renderModelSettings()
6006
+ if (valid()) renderModelSettings()
5922
6007
  }
5923
6008
 
5924
6009
  function addDiscoveredModels() {
@@ -5940,6 +6025,7 @@ function addDiscoveredModels() {
5940
6025
  async function saveModelEditor() {
5941
6026
  const editor = state.modelEditor
5942
6027
  if (!editor || editor.busy) return
6028
+ const connection = captureConnection(), valid = () => connection.valid() && state.modelEditor === editor
5943
6029
  collectModelEditorForm()
5944
6030
  if (!state.modelSettings.writable) return setModelEditorError(t('settings.modelReadOnly'))
5945
6031
  const models = editor.models || []
@@ -5970,6 +6056,7 @@ async function saveModelEditor() {
5970
6056
  })
5971
6057
  if (ops.length) {
5972
6058
  const value = await rpc('settings.mutate', { ns: editor.settingsNs, ops, expectedRevision: editor.namespace.revision })
6059
+ if (!valid()) return
5973
6060
  editor.namespace = value
5974
6061
  }
5975
6062
  if (editor.keyDraft.trim()) {
@@ -5977,10 +6064,13 @@ async function saveModelEditor() {
5977
6064
  } else if (editor.clearKey && editor.keyConfigured && editor.keyRef) {
5978
6065
  await rpc('credentials.unset', { ref: editor.keyRef })
5979
6066
  }
6067
+ if (!valid()) return
5980
6068
  state.modelEditor = null
5981
6069
  await loadModelSettings(true)
6070
+ if (!connection.valid()) return
5982
6071
  toast(t('settings.modelSaved'), 'ok')
5983
6072
  } catch (error) {
6073
+ if (!valid()) return
5984
6074
  editor.error = t('settings.modelSaveFailed', { msg: error?.message || String(error) })
5985
6075
  } finally {
5986
6076
  if (state.modelEditor === editor) {