dsh-remote-plugin 0.7.2 → 0.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/public/app.js CHANGED
@@ -27,7 +27,7 @@ const CLIENT_ID = (() => {
27
27
  })()
28
28
  function clientIdHeaders() { return CLIENT_ID ? { 'x-dsh-remote-client-id': CLIENT_ID } : {} }
29
29
 
30
- /* 离线缓存: 会话列表 + 每会话聊天记录。只在网络失败时兜底展示, 不会替代线上数据。 */
30
+ /* 按连接身份隔离:本地缓存先显示,远端历史在后台校验与合并。 */
31
31
  const CACHE = {
32
32
  get sessions() { return connectionCacheKey('sessions') },
33
33
  get history() { return connectionCacheKey('history') }
@@ -43,18 +43,6 @@ function cacheRead(key, d = null) {
43
43
  function cacheWrite(key, value) {
44
44
  try { LS.set(key, JSON.stringify(value)) } catch { LS.del(key) }
45
45
  }
46
- function readHistoryCache() { return cacheRead(CACHE.history, {}) || {} }
47
- function writeHistoryCache(cache) {
48
- try { LS.set(CACHE.history, JSON.stringify(cache)); return }
49
- catch {
50
- // localStorage 配额不足: 每会话只留最近 50 条再试一次
51
- try {
52
- for (const k of Object.keys(cache)) cache[k].events = (cache[k].events || []).slice(-50)
53
- LS.set(CACHE.history, JSON.stringify(cache))
54
- } catch { LS.del(CACHE.history) }
55
- }
56
- }
57
-
58
46
  const state = {
59
47
  token: '',
60
48
  wsTicket: { token: '', server: '', value: '', expiresAt: 0 },
@@ -127,14 +115,33 @@ for (const key of ['server', 'token']) {
127
115
  set(next) {
128
116
  if (next === value) return
129
117
  value = next; connectionGeneration++
118
+ clearTimeout(state.refreshTimer); state.refreshTimer = null
130
119
  state.sessions = []; state.byId.clear(); state.pendingProjections.clear()
120
+ state.hostInfo = null
121
+ if(typeof closeStream==='function'&&typeof streamMeta!=='undefined'){closeStream('mux');closeStream('host')}
131
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()
132
129
  state.fs.path = null; state.fs.initial = null; state.fs.loaded = false; state.fs.roots = []; state.fs.rootIndex = 0
133
130
  state.wb = null; state.wbProjects = []; state.wbArchived = []; state.workspaceFilter = ''; state.fs.workspaceId = ''; clearTimeout(scheduleHistoryCacheSave._t)
134
131
  window.DshPluginCenter?.close()
135
132
  window.DshInsights?.close()
133
+ if(typeof document!=='undefined') {
134
+ const identityGeneration=connectionGeneration
135
+ queueMicrotask(()=>{if(identityGeneration===connectionGeneration&&typeof startOverviewDetection==='function')startOverviewDetection(true,true)})
136
+ document.getElementById('history')?.replaceChildren?.()
137
+ const generation=connectionGeneration
138
+ queueMicrotask(()=>{if(generation!==connectionGeneration)return;if(typeof conversationView!=='undefined')conversationView?.reset();restoreCachedSessionList()})
139
+ }
136
140
  if (typeof document !== 'undefined') {
137
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()
138
145
  const generation = connectionGeneration
139
146
  queueMicrotask(() => {
140
147
  if (generation === connectionGeneration && document.getElementById('view-plugins')?.classList.contains('hidden') === false) openPluginPage()
@@ -331,6 +338,9 @@ function openFeedbackModal() {
331
338
  $('fb-msg').value = ''
332
339
  $('fb-contact').value = ''
333
340
  $('fb-include-diagnostics').checked = false
341
+ $('fb-include-crashes').checked = false
342
+ $('fb-crash-details').open = false
343
+ void loadCrashPreview()
334
344
  $('modal-feedback').classList.remove('hidden')
335
345
  setTimeout(() => $('fb-msg').focus(), 50)
336
346
  }
@@ -343,11 +353,22 @@ function closeFeedbackSuccess() {
343
353
  $('modal-feedback-success').classList.add('hidden')
344
354
  $('btn-feedback')?.focus()
345
355
  }
356
+ async function loadCrashPreview() {
357
+ const connection=captureConnection(),preview=$('fb-crash-preview')
358
+ preview.textContent=t('feedback.crashLoading')
359
+ try {
360
+ const response=await fetch(updateBase()+'/crash-logs',{headers:{authorization:'Bearer '+connection.token},signal:AbortSignal.timeout(5000),cache:'no-store'})
361
+ if(!response.ok)throw new Error('unavailable')
362
+ const data=await response.json()
363
+ if(connection.valid())preview.textContent=JSON.stringify(data.upload,null,2)
364
+ }catch{if(connection.valid())preview.textContent=t('feedback.crashUnavailable')}
365
+ }
346
366
  async function submitFeedback() {
347
367
  const type = state.feedbackType || 'bug'
348
368
  const message = $('fb-msg').value.trim()
349
369
  const contact = $('fb-contact').value.trim()
350
370
  const includeDiagnostics = $('fb-include-diagnostics').checked
371
+ const includeCrashLogs = $('fb-include-crashes').checked
351
372
  if (!message) { toast(t('feedback.empty'), 'err'); return }
352
373
  if (message.length > 2000) { toast(t('feedback.tooLong'), 'err'); return }
353
374
  const btn = $('fb-submit')
@@ -358,7 +379,7 @@ async function submitFeedback() {
358
379
  const res = await fetch(base + '/feedback', {
359
380
  method: 'POST',
360
381
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token },
361
- body: JSON.stringify({ type, message, contact, appVersion: state.localVersion, includeDiagnostics })
382
+ body: JSON.stringify({ type, message, contact, appVersion: state.localVersion, includeDiagnostics, includeCrashLogs })
362
383
  })
363
384
  let json = {}
364
385
  try { json = await res.json() } catch {}
@@ -422,14 +443,16 @@ function apiUrl(path) {
422
443
  }
423
444
 
424
445
  let wsTicketPromise = null
446
+ let wsTicketConnection = null
425
447
  async function getWsTicket() {
426
448
  const now = Date.now()
427
449
  if (state.wsTicket.token === state.token && state.wsTicket.server === state.server &&
428
450
  state.wsTicket.value && state.wsTicket.expiresAt > now + 15000) return state.wsTicket.value
429
- if (wsTicketPromise) return wsTicketPromise
451
+ if (wsTicketPromise && wsTicketConnection?.valid()) return wsTicketPromise
452
+ const connection = captureConnection()
430
453
  const token = state.token
431
454
  const server = state.server
432
- wsTicketPromise = (async () => {
455
+ const job = (async () => {
433
456
  if (activeGatewayCapability('wsTicket') === false) throw new Error('ws ticket unsupported')
434
457
  const res = await fetch(apiUrl('/api/ws-ticket'), {
435
458
  method: 'POST',
@@ -441,11 +464,14 @@ async function getWsTicket() {
441
464
  })
442
465
  if (!res.ok) throw new Error('ws ticket HTTP ' + res.status)
443
466
  const data = await res.json()
467
+ if (!connection.valid()) throw new Error('stale ws ticket')
444
468
  if (!data?.ticket || !Number(data.expiresAt)) throw new Error('invalid ws ticket')
445
469
  state.wsTicket = { token, server, value: data.ticket, expiresAt: Number(data.expiresAt) }
446
470
  return data.ticket
447
471
  })()
448
- 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 } }
449
475
  }
450
476
 
451
477
  function updateBase() {
@@ -514,7 +540,7 @@ async function respond(rpcId, value) {
514
540
 
515
541
  async function safeRpc(method, payload, errText) {
516
542
  const connection = captureConnection()
517
- try { return await rpc(method, payload) }
543
+ try { const value = await rpc(method, payload); return connection.valid() ? value : null }
518
544
  catch (e) {
519
545
  if (!connection.valid()) return null
520
546
  if (e.message === 'AUTH') authFailure()
@@ -524,6 +550,7 @@ async function safeRpc(method, payload, errText) {
524
550
  }
525
551
 
526
552
  let hostDescribePromise = null
553
+ let hostDescribeConnection = null
527
554
  let hostDescribeRetryTimer = null
528
555
  let hostDescribeFailures = 0
529
556
 
@@ -539,12 +566,13 @@ function scheduleHostDescribeRetry() {
539
566
 
540
567
  async function refreshHostDescription({ notify = false } = {}) {
541
568
  if (!state.token) return null
542
- if (hostDescribePromise) return hostDescribePromise
543
- const server = state.server
544
- hostDescribePromise = (async () => {
569
+ if (hostDescribePromise && hostDescribeConnection?.valid()) return hostDescribePromise
570
+ const connection = captureConnection()
571
+ hostDescribeConnection = connection
572
+ const job = (async () => {
545
573
  try {
546
574
  const host = await rpc('host.describe', {}, 5000)
547
- if (server !== state.server) return null
575
+ if (!connection.valid()) return null
548
576
  state.hostInfo = host
549
577
  const health = activeGatewayHealth()
550
578
  if (health) health.upstreamReachable = true
@@ -556,7 +584,7 @@ async function refreshHostDescription({ notify = false } = {}) {
556
584
  renderOverview()
557
585
  return host
558
586
  } catch (error) {
559
- if (server !== state.server) return null
587
+ if (!connection.valid()) return null
560
588
  if (error.message === 'AUTH') authFailure()
561
589
  else {
562
590
  hostDescribeFailures++
@@ -565,11 +593,11 @@ async function refreshHostDescription({ notify = false } = {}) {
565
593
  }
566
594
  return null
567
595
  } finally {
568
- hostDescribePromise = null
569
- if (server !== state.server) scheduleHostDescribeRetry()
596
+ if (hostDescribePromise === job) { hostDescribePromise = null; hostDescribeConnection = null }
570
597
  }
571
598
  })()
572
- return hostDescribePromise
599
+ hostDescribePromise = job
600
+ return job
573
601
  }
574
602
 
575
603
  function authFailure() {
@@ -705,7 +733,7 @@ async function pingServer(base) {
705
733
  const ctrl = new AbortController()
706
734
  const timer = setTimeout(() => ctrl.abort(), 3500)
707
735
  try {
708
- 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' })
709
737
  if (!res.ok) return Infinity
710
738
  const health = await res.json().catch(() => null)
711
739
  if (health && typeof health === 'object') {
@@ -738,7 +766,10 @@ function dshReachable() {
738
766
  }
739
767
 
740
768
  async function selectFastestServer({ silent = false, reconnect = true } = {}) {
741
- 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])
742
773
  state.selectingServer = true
743
774
  try {
744
775
  if (!silent) toast(t('speed.testing'))
@@ -750,6 +781,7 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
750
781
 
751
782
  if (state.autoSelect[state.activeGroup] !== false) {
752
783
  const measured = await Promise.all(candidates.map(async (server) => [server, await pingServer(server.url)]))
784
+ if (!valid()) return null
753
785
  for (const [server, latency] of measured) state.serverLatency[serverKey(server)] = latency
754
786
  best = candidates
755
787
  .filter(server => Number.isFinite(state.serverLatency[serverKey(server)]))
@@ -770,6 +802,8 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
770
802
  }
771
803
  }
772
804
 
805
+ if (!valid()) return null
806
+ if (typeof window !== 'undefined') window.DshNetwork?.observeLatency(ms)
773
807
  renderServers()
774
808
  if (chosen !== state.server || chosenToken !== state.token) {
775
809
  state.hostInfo = null
@@ -800,7 +834,7 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
800
834
  await maybeWarnAppBehindGateway()
801
835
  return chosen
802
836
  } finally {
803
- state.selectingServer = false
837
+ if (request === selectFastestServer.request) state.selectingServer = false
804
838
  }
805
839
  }
806
840
 
@@ -1210,12 +1244,12 @@ function openStreams() {
1210
1244
  function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1211
1245
  if (!state.token) return
1212
1246
  if (ticket === null) {
1213
- const token = state.token
1247
+ const token = state.token, connection=captureConnection()
1214
1248
  void getWsTicket().then((value) => {
1215
- if (state.token === token) openStream(kind, handler, refreshOnOpen, isRestore, value)
1249
+ if (connection.valid()) openStream(kind, handler, refreshOnOpen, isRestore, value)
1216
1250
  }).catch(() => {
1217
1251
  // 兼容旧网关/插件副本: ticket 接口不可用时临时回退旧 token 握手。
1218
- if (state.token === token) openStream(kind, handler, refreshOnOpen, isRestore, '')
1252
+ if (connection.valid()) openStream(kind, handler, refreshOnOpen, isRestore, '')
1219
1253
  })
1220
1254
  return
1221
1255
  }
@@ -1332,43 +1366,46 @@ function enterPollMode() {
1332
1366
  }
1333
1367
 
1334
1368
  function stopPolling() {
1335
- clearInterval(pollTimer)
1336
- pollTimer = null
1337
- clearTimeout(wsRetryTimer)
1338
- wsRetryTimer = null
1369
+ pollInFlight?.stop()
1370
+ pollInFlight = null
1371
+ clearInterval(pollTimer); pollTimer = null
1372
+ clearInterval(wsRetryTimer); wsRetryTimer = null
1339
1373
  }
1340
-
1341
1374
  function startPolling() {
1342
1375
  stopPolling()
1343
1376
  pollTimer = setInterval(pollOnce, 4000)
1344
1377
  wsRetryTimer = setInterval(tryRestoreWs, 30000)
1345
- pollOnce()
1378
+ void pollOnce()
1346
1379
  }
1347
-
1348
- let pollInFlight = false
1380
+ let pollInFlight = null
1349
1381
  async function pollOnce() {
1350
- if (state.streamMode !== 'poll' || pollInFlight) return
1351
- pollInFlight = true
1352
- try {
1353
- await Promise.all([pollKind('mux'), pollKind('host')])
1354
- } finally {
1355
- pollInFlight = false
1356
- }
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()
1357
1389
  }
1358
1390
 
1359
- async function pollKind(kind) {
1391
+ async function pollKind(kind, cancellation) {
1360
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
1361
1395
  const since = state.pollSeq[kind] || 0
1362
1396
  let res
1363
1397
  try {
1364
- 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
1365
1400
  const headers = { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }
1366
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 })
1367
1402
  } catch { return }
1403
+ if (!valid()) return
1368
1404
  if (res.status === 401) { authFailure(); return }
1369
1405
  if (!res.ok) return
1370
1406
  let data
1371
1407
  try { data = await res.json() } catch { return }
1408
+ if (!valid()) return
1372
1409
  if (!data || !Array.isArray(data.events)) return
1373
1410
  // 网关重启或客户端离线过久后,游标可能落后于内存环形缓冲;
1374
1411
  // 从当前缓冲重新接收,并刷新权威会话列表,避免静默漏事件。
@@ -1390,6 +1427,7 @@ async function pollKind(kind) {
1390
1427
  else onHostFrame(item.event)
1391
1428
  }
1392
1429
  }
1430
+ return data.waitSupported === true ? 100 : 4000
1393
1431
  }
1394
1432
 
1395
1433
  function tryRestoreWs() {
@@ -1420,13 +1458,13 @@ document.addEventListener('visibilitychange', () => {
1420
1458
  if (document.visibilityState === 'visible') {
1421
1459
  onResume()
1422
1460
  if (state.servers.length) selectFastestServer({ silent: true })
1423
- else if (state.token && (streams.mux?.readyState !== WebSocket.OPEN || streams.host?.readyState !== WebSocket.OPEN)) openStreams()
1461
+ else if (state.token) repairMissingStreams()
1424
1462
  }
1425
1463
  })
1426
1464
  window.addEventListener('pageshow', onResume)
1427
1465
  setInterval(() => {
1428
1466
  if (document.visibilityState === 'visible' && state.token) {
1429
- if (streams.mux?.readyState !== WebSocket.OPEN || streams.host?.readyState !== WebSocket.OPEN) openStreams()
1467
+ repairMissingStreams()
1430
1468
  }
1431
1469
  }, 15000)
1432
1470
  // 多服务器: 每 5 分钟重测一次延迟, 网络环境变化(离开 Wi-Fi / 挂上 Tailscale)时自动换线
@@ -1617,8 +1655,9 @@ function onSessionEvent(sessionId, event) {
1617
1655
 
1618
1656
  /* ---------------- 数据刷新 ---------------- */
1619
1657
  function scheduleRefresh() {
1620
- clearTimeout(state.refreshTimer)
1621
- 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)
1622
1661
  }
1623
1662
 
1624
1663
  async function refreshAll() {
@@ -1628,6 +1667,7 @@ async function refreshAll() {
1628
1667
  }
1629
1668
 
1630
1669
  async function refreshSessions() {
1670
+ if(typeof restoreCachedSessionList==='function')restoreCachedSessionList()
1631
1671
  const connection = captureConnection(), request = ++sessionsRequest
1632
1672
  const v = await safeRpc('session.list', {}, t('err.sessionList'))
1633
1673
  if (!connection.valid() || request !== sessionsRequest) return
@@ -1654,6 +1694,7 @@ async function refreshSessions() {
1654
1694
 
1655
1695
  function removeLocalSessionRecord(sessionId) {
1656
1696
  if (!sessionId) return
1697
+ void window.DshHistory.cacheRemove(historyCacheScope(),sessionId)
1657
1698
  state.sessions = state.sessions.filter(session => session?.sessionId !== sessionId)
1658
1699
  state.byId.delete(sessionId)
1659
1700
  state.pendingProjections.delete(sessionId)
@@ -1661,11 +1702,7 @@ function removeLocalSessionRecord(sessionId) {
1661
1702
  state.pendingPrompts.delete(sessionId)
1662
1703
  delete state.queues[sessionId]
1663
1704
  delete state.jobs[sessionId]
1664
- const historyCache = readHistoryCache()
1665
- if (Object.prototype.hasOwnProperty.call(historyCache, sessionId)) {
1666
- delete historyCache[sessionId]
1667
- writeHistoryCache(historyCache)
1668
- }
1705
+ LS.del(historyCacheScope()) // Also discard the obsolete monolithic cache.
1669
1706
  cacheWrite(CACHE.sessions, state.sessions.slice(0, 80))
1670
1707
  }
1671
1708
 
@@ -1749,7 +1786,11 @@ function short(id) { return '…' + String(id).slice(-8) }
1749
1786
  function isTopLevelSession(session) {
1750
1787
  return !!session && !session.parentSessionId && session.origin !== 'subagent'
1751
1788
  }
1752
- function topLevelSessions() { return state.sessions.filter(isTopLevelSession) }
1789
+ // DSH marks sessions created via "new session" but never prompted as blank and hides
1790
+ // them in its own UI; keep the same semantics here so they do not occupy the list,
1791
+ // the workspace tree or the home stats.
1792
+ function isVisibleSession(session) { return isTopLevelSession(session) && !session?.blank }
1793
+ function topLevelSessions() { return state.sessions.filter(isVisibleSession) }
1753
1794
  const GOAL_TERMINAL_PHASES = new Set(['complete', 'cleared'])
1754
1795
  function isGoalTerminal(goal) {
1755
1796
  return !!goal && GOAL_TERMINAL_PHASES.has(goal.phase)
@@ -2025,7 +2066,7 @@ function renderWorkbench() {
2025
2066
  const projectHtml = projects.map(w => {
2026
2067
  const id = String(w.workspaceId || '')
2027
2068
  const open = !!state.wbOpenProjects[id]
2028
- const sessions = orderedWorkspaceSessions(id, (w.sessionIds || []).map(sid => state.byId.get(sid)).filter(isTopLevelSession).filter(s => !archivedSet.has(s.sessionId)))
2069
+ const sessions = orderedWorkspaceSessions(id, (w.sessionIds || []).map(sid => state.byId.get(sid)).filter(isVisibleSession).filter(s => !archivedSet.has(s.sessionId)))
2029
2070
  const body = open ? `<div class="wb-sessions">${sessions.length ? sessions.map(s => `
2030
2071
  <div class="session-swipe" data-session-swipe data-id="${esc(s.sessionId)}">
2031
2072
  <button class="wb-session" type="button" data-wb-session="${esc(s.sessionId)}" data-motion-key="${esc(s.sessionId)}">
@@ -2196,9 +2237,9 @@ function renderSessions() {
2196
2237
 
2197
2238
  /* ---------------- 会话详情 ---------------- */
2198
2239
  const emptySessionCleanup = new Set()
2199
- async function archiveEmptySessionOnLeave(sessionId) {
2200
- const base = state.server
2201
- const protectedSession = () => state.server !== base || state.current !== sessionId
2240
+ async function archiveEmptySessionOnLeave(sessionId, leaving = false) {
2241
+ const base = state.server, connection=captureConnection()
2242
+ const protectedSession = () => !connection.valid() || state.server !== base || (!leaving && state.current !== sessionId)
2202
2243
  || !state.byId.has(sessionId) || state.byId.get(sessionId)?.running
2203
2244
  || state.sessionActivity?.has(sessionId) || state.pendingPrompts?.has(sessionId)
2204
2245
  || (state.queues[sessionId] || []).length > 0
@@ -2219,10 +2260,11 @@ async function archiveEmptySessionOnLeave(sessionId) {
2219
2260
  }
2220
2261
 
2221
2262
  async function openSession(id) {
2222
- if (state.current && state.current !== id) await archiveEmptySessionOnLeave(state.current)
2263
+ if (state.current && state.current !== id) void archiveEmptySessionOnLeave(state.current,true)
2223
2264
  state.current = id
2224
2265
  setSessionRecovery('loading')
2225
2266
  state.history = emptyHistory()
2267
+ const openingHistory=state.history, openingConnection=captureConnection()
2226
2268
  document.body.classList.add('in-session')
2227
2269
  showView('view-session')
2228
2270
  $('btn-rename-session').classList.remove('hidden')
@@ -2233,7 +2275,9 @@ async function openSession(id) {
2233
2275
  renderQueue()
2234
2276
  renderSessionPending()
2235
2277
  void refreshCompactionStatus(id)
2236
- restoreCachedHistory()
2278
+ getConversationView().reset()
2279
+ await restoreCachedHistory()
2280
+ if(state.current!==id||state.history!==openingHistory||!openingConnection.valid())return
2237
2281
  await loadHistory(true)
2238
2282
  renderSessionCards()
2239
2283
  refreshSessions()
@@ -2312,13 +2356,10 @@ function renderSessionTitle() {
2312
2356
  function renderSessionSub() {
2313
2357
  const s = state.byId.get(state.current)
2314
2358
  if (!s) { $('session-sub').textContent = ''; return }
2315
- const parts = [short(s.sessionId)]
2316
- if (s.cwd) parts.push(s.cwd)
2317
- if (s.running) parts.push(t('session.running'))
2318
- else if (s.error) parts.push(t('session.interrupted'))
2319
- const recovery = recoveryLabel()
2320
- if (recovery) parts.push(recovery)
2321
- $('session-sub').textContent = parts.join(' · ')
2359
+ const workspace = s.cwd || ''
2360
+ const name = workspace.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || workspace
2361
+ $('session-sub').textContent = '📁 ' + (name || t('session.noWorkspace')) + ' ›'
2362
+ $('session-sub').title = workspace || t('session.noWorkspace')
2322
2363
  }
2323
2364
 
2324
2365
  /** 顶栏状态: 运行中=蓝色流动渐变, 中断/出错=橙红渐变, 空闲=原样式 */
@@ -2330,7 +2371,8 @@ function updateSessionStatus() {
2330
2371
  const composerStatus = $('composer-status')
2331
2372
  const compact = activeCompaction()
2332
2373
  if (composerStatus) {
2333
- composerStatus.classList.toggle('hidden', !s?.running && !compact)
2374
+ const queued = (state.queues[state.current] || []).some(i => i.placement !== 'context')
2375
+ composerStatus.classList.toggle('hidden', !s?.running && !compact && !queued)
2334
2376
  composerStatus.classList.toggle('compacting', !!compact)
2335
2377
  }
2336
2378
  const composerText = $('composer-status-text')
@@ -2349,6 +2391,7 @@ function updateCancelBtn() {
2349
2391
  const s = state.byId.get(state.current)
2350
2392
  const running = s?.running || (state.queues[state.current] || []).some(i => i.placement !== 'context')
2351
2393
  $('btn-cancel').classList.toggle('hidden', !running)
2394
+ $('composer-status')?.classList.toggle('hidden', !running && !activeCompaction())
2352
2395
  }
2353
2396
 
2354
2397
  const HISTORY_MAX_VISIBLE = 5000 // 已加载的可显示事件上限(消息/工具/状态, 不含 chunk)
@@ -2443,137 +2486,103 @@ function partialReasoningHtml() {
2443
2486
  .join('')
2444
2487
  }
2445
2488
 
2446
- function trimVisible() {
2447
- const h = state.history
2448
- if (h.visible.length <= HISTORY_MAX_VISIBLE) return
2449
- const drop = h.visible.splice(0, h.visible.length - HISTORY_MAX_VISIBLE)
2450
- for (const e of drop) h.seqs.delete(e.seq)
2451
- h.renderStart = Math.max(0, h.renderStart - drop.length)
2452
- h.renderEnd = Math.max(h.renderStart, h.renderEnd - drop.length)
2489
+
2490
+ function restoreCachedSessionList() {
2491
+ if(state.sessions.length)return
2492
+ try{const items=JSON.parse(LS.get(CACHE.sessions,''));if(!Array.isArray(items))return;state.sessions=items.filter(item=>typeof item?.sessionId==='string').slice(0,80);state.byId=new Map(state.sessions.map(item=>[item.sessionId,item]));renderSessions()}catch{}
2453
2493
  }
2454
2494
 
2455
- /* 聊天记录本地缓存: 每会话最多 250 条, 全局最多 10 个会话 */
2495
+ let conversationView = null
2496
+ function historyCacheScope() { return CACHE.history }
2497
+ function historySource(value) {
2498
+ state.history.source=value
2499
+ const el=$('history-source')
2500
+ if(el)el.textContent=t(({cache:'history.cached',syncing:'history.syncing',synced:'history.synced',saved:'history.saved',offline:'history.offline',saveFailed:'history.cacheFailed'})[value]||'history.synced')
2501
+ }
2502
+ function getConversationView() {
2503
+ if(!conversationView)conversationView=new window.DshHistory.HistoryView($('history'),{
2504
+ html:entry=>eventHtml(entry, {toolNames:state.history.toolNames}),
2505
+ older:()=>loadHistory(false),olderLabel:()=>t('history.earlier'),loadingLabel:()=>t('history.loadingEarlier'),live:partialReasoningHtml,
2506
+ changed:view=>{state.history.renderStart=view.start;state.history.renderEnd=view.end;$('btn-history-latest')?.classList.toggle('hidden',!view.reading&&view.end>=view.entries.length&&!state.history.tailEvicted);updateRail(view.domChanged)},
2507
+ scrolled:()=>{updateRail()}
2508
+ })
2509
+ return conversationView
2510
+ }
2456
2511
  function scheduleHistoryCacheSave() {
2457
2512
  clearTimeout(scheduleHistoryCacheSave._t)
2458
- const connection = captureConnection()
2459
- scheduleHistoryCacheSave._t = setTimeout(() => { if (connection.valid()) saveHistoryCache() }, 400)
2460
- }
2461
-
2462
- function saveHistoryCache() {
2463
- const id = state.current
2464
- if (!id || !state.history.visible.length) return
2465
- const s = state.byId.get(id)
2466
- const cache = readHistoryCache()
2467
- cache[id] = {
2468
- title: s ? titleOf(s) : '',
2469
- updatedAt: Date.now(),
2470
- events: state.history.visible.slice(-250).map(e => ({ seq: e.seq, event: e.event }))
2471
- }
2472
- const keys = Object.entries(cache)
2473
- .sort((a, b) => (b[1].updatedAt || 0) - (a[1].updatedAt || 0))
2474
- .slice(0, 10)
2475
- .map(([k]) => k)
2476
- const pruned = {}
2477
- for (const k of keys) pruned[k] = cache[k]
2478
- writeHistoryCache(pruned)
2479
- }
2480
-
2481
- /** 网关不可达时回填本地缓存的历史; 返回是否命中。 */
2482
- function restoreCachedHistory() {
2483
- const id = state.current
2484
- if (!id) return false
2485
- const cached = readHistoryCache()[id]
2486
- if (!cached?.events?.length) return false
2487
- if (cached.title) hydrateSessionProjections(id, { values: { title: cached.title }, asOfSeq: 0 })
2488
- const h = emptyHistory()
2489
- for (const e of cached.events) {
2490
- if (e?.seq == null) continue
2491
- h.seqs.add(e.seq)
2492
- h.visible.push(e)
2493
- }
2494
- h.visible.sort((a, b) => a.seq - b.seq)
2495
- h.loaded = true
2496
- state.history = h
2497
- $('history-hint').textContent = t('history.offlineCache', { n: h.visible.length })
2498
- renderHistory(true)
2513
+ const connection=captureConnection(),id=state.current,history=state.history,scope=historyCacheScope()
2514
+ scheduleHistoryCacheSave._t=setTimeout(()=>{if(connection.valid()&&state.current===id&&state.history===history)void saveHistoryCache(scope,id,history)},500)
2515
+ }
2516
+ async function saveHistoryCache(scope=historyCacheScope(),id=state.current,history=state.history) {
2517
+ if(!id||!history.visible.length||history.tailEvicted)return
2518
+ const saved=await window.DshHistory.cacheSave(scope,id,{title:titleOf(state.byId.get(id)),events:history.visible.slice(-250),minSeq:history.visible.slice(-250)[0]?.seq??history.minSeq,hasMore:history.hasMore||history.visible.length>250,partialReasoning:[...history.partialReasoning.values()]})
2519
+ if(!saved&&state.current===id&&state.history===history&&scope===historyCacheScope())historySource('saveFailed')
2520
+ if(saved&&state.current===id&&state.history===history&&scope===historyCacheScope()&&['synced','saveFailed'].includes(history.source))historySource('saved')
2521
+ }
2522
+ async function restoreCachedHistory() {
2523
+ const connection=captureConnection(),id=state.current,history=state.history,scope=historyCacheScope()
2524
+ if(!id)return false
2525
+ const cached=await window.DshHistory.cacheLoad(scope,id,legacyId=>window.DshHistory.decodeLegacy(LS.get(scope,''),legacyId))
2526
+ if(!connection.valid()||state.current!==id||state.history!==history||!cached?.events?.length)return false
2527
+ history.visible=cached.events.slice(-250).filter(entry=>entry?.seq!=null&&shouldShowEvent(entry.event?.type,entry.event)).sort((a,b)=>a.seq-b.seq)
2528
+ history.seqs=new Set(history.visible.map(entry=>entry.seq));history.loaded=true;history.cached=true;history.hasMore=cached.events.length>250||cached.hasMore!==false;history.minSeq=cached.events.length>250?(history.visible[0]?.seq??Infinity):Number.isFinite(cached.minSeq)?cached.minSeq:history.visible[0]?.seq??Infinity
2529
+ if(cached.title&&!hasSessionTitle(state.byId.get(id)))hydrateSessionProjections(id,{values:{title:cached.title},asOfSeq:0})
2530
+ applyReasoningBaseline(cached.partialReasoning||[]);historySource('cache');setSessionRecovery('cached');renderHistory(true)
2499
2531
  return true
2500
2532
  }
2501
-
2502
- async function loadHistory(reset) {
2503
- const connection = captureConnection()
2504
- const id = state.current
2505
- if (!id || state.history.loading) return
2506
- const history = state.history
2507
- const reasoningVersion = history.reasoningVersion || 0
2508
- history.loading = true
2509
- if (reset) setSessionRecovery('loading')
2510
- const moreBtn = $('history-more')
2511
- if (moreBtn) moreBtn.classList.add('hidden')
2512
- const payload = { sessionId: id, maxMessages: 60 }
2513
- if (!reset && state.history.minSeq !== Infinity) payload.beforeSeq = state.history.minSeq
2514
-
2533
+ function trimVisible(direction='tail') {
2534
+ const h=state.history,excess=h.visible.length-5000
2535
+ if(excess<=0)return
2536
+ const older=direction==='older'||conversationView?.reading
2537
+ const removed=older?h.visible.splice(5000):h.visible.splice(0,excess)
2538
+ for(const entry of removed)h.seqs.delete(entry.seq)
2539
+ if(older)h.tailEvicted=true
2540
+ else{h.minSeq=h.visible[0]?.seq??Infinity;h.headEvicted=true;h.hasMore=true}
2541
+ }
2542
+
2543
+ async function loadHistory(reset = true) {
2544
+ const connection=captureConnection(),id=state.current,history=state.history
2545
+ if(!id||history.loading||(!reset&&Date.now()<(history.retryAfter||0)))return
2546
+ const reasoningVersion=history.reasoningVersion||0,hadContent=history.visible.length>0
2547
+ history.loading=true
2548
+ if(reset){if(hadContent)historySource('syncing');else setSessionRecovery('loading')}
2549
+ const network=window.DshNetwork?.profile() || {historyPageSize:60,readTimeout:45000}
2550
+ const payload={sessionId:id,maxMessages:network.historyPageSize}
2551
+ if(!reset&&Number.isFinite(history.minSeq))payload.beforeSeq=history.minSeq
2552
+ getConversationView().more.disabled=true
2553
+ getConversationView().more.textContent=getConversationView().options.loadingLabel()
2515
2554
  let v
2516
- try {
2517
- v = await rpc('session.history', payload)
2518
- } catch (e) {
2519
- if (!connection.valid() || state.current !== id || state.history !== history) return
2520
- history.loading = false
2521
- if (e.message === 'AUTH') { authFailure(); return }
2522
- if (restoreCachedHistory()) {
2523
- setSessionRecovery('cached', e.message)
2524
- toast(t('history.cacheFallback'), 'ok')
2525
- return
2526
- }
2527
- const msg = e.message || t('err.dshError')
2528
- setSessionRecovery('error', msg)
2529
- const box = $('history')
2530
- if (box && (reset || !state.history.visible.length)) {
2531
- box.innerHTML = `<div class="empty"><div>${esc(t('history.loadFailed', { msg }))}</div><button type="button" class="mini-btn" id="btn-history-retry" style="margin-top:10px">${esc(t('history.retry'))}</button></div>`
2532
- const retry = $('btn-history-retry')
2533
- if (retry) retry.addEventListener('click', () => loadHistory(true))
2534
- } else {
2535
- toast(t('history.loadFailed', { msg }), 'err')
2536
- }
2555
+ try{v=await rpc('session.history',payload,network.readTimeout)}catch(error){
2556
+ if(!connection.valid()||state.current!==id||state.history!==history)return
2557
+ history.loading=false;history.retryAfter=Date.now()+1500
2558
+ if(error.message==='AUTH'){authFailure();return}
2559
+ if(hadContent){historySource('offline');setSessionRecovery('cached',error.message);renderHistory(false,'fixed');return}
2560
+ setSessionRecovery('error',error.message)
2561
+ $('history').innerHTML='<div class="history-empty">'+esc(error.message)+'</div>'
2562
+ const retry=document.createElement('button');retry.type='button';retry.className='history-page-control';retry.textContent=t('history.retry');retry.addEventListener('click',()=>{void loadHistory(true)});$('history').append(retry)
2537
2563
  return
2538
2564
  }
2539
-
2540
- if (!connection.valid() || state.current !== id || state.history !== history) return
2541
- const liveReasoning = (history.reasoningVersion || 0) !== reasoningVersion ? new Map(history.partialReasoning) : null
2542
- hydrateSessionProjections(id, v.projections)
2543
- history.loaded = true
2544
- const incoming = v.events || []
2545
- let added = 0
2546
- if (reset) state.history.partialReasoning.clear()
2565
+ if(!connection.valid()||state.current!==id||state.history!==history)return
2566
+ const liveReasoning=(history.reasoningVersion||0)!==reasoningVersion?new Map(history.partialReasoning):null
2567
+ hydrateSessionProjections(id,v.projections);history.loaded=true
2568
+ const incoming=v.events||[],prepared=[]
2547
2569
  for (const entry of incoming) {
2548
- const ev = entry?.event
2549
- const seq = ev?.seq
2550
- if (ev?.type === 'turn/start' || ev?.type === 'turn/end') noteSessionTurnTime(id, ev)
2570
+ const ev=entry?.event
2551
2571
  applyReasoningStreamEvent(ev)
2552
- if (seq == null || state.history.seqs.has(seq)) continue
2553
- if (!shouldShowEvent(ev.type, ev)) continue // chunk 与非用户上下文不保留
2554
- state.history.seqs.add(seq)
2555
- state.history.visible.push({ seq, event: ev, view: entry.view })
2556
- added++
2557
- }
2558
- // 向前翻页游标 = 本页最旧的 raw seq(即使它本身被过滤)
2559
- if (liveReasoning) history.partialReasoning = liveReasoning
2560
- else applyReasoningBaseline(v.partialReasoning)
2561
- const firstSeq = incoming[0]?.event?.seq
2562
- if (firstSeq != null) state.history.minSeq = Math.min(state.history.minSeq, firstSeq)
2563
- state.history.visible.sort((a, b) => a.seq - b.seq)
2564
- trimVisible()
2565
- state.history.hasMore = !!v.hasMore
2566
- history.loading = false
2567
- setSessionRecovery('ready')
2568
- renderSessionTitle(); renderSessionSub(); renderSessionCards()
2569
- try {
2570
- if (reset) renderHistory(true)
2571
- else if (added) renderHistory(false, 'keep')
2572
- } catch (e) {
2573
- console.error('renderHistory failed', e)
2574
- }
2575
- if (moreBtn) moreBtn.classList.toggle('hidden', !state.history.hasMore)
2576
- $('history-hint').textContent = state.history.visible.length ? t('history.count', { n: state.history.visible.length }) : ''
2572
+ if(ev?.type==='turn/start'||ev?.type==='turn/end')noteSessionTurnTime(id,ev)
2573
+ if(ev?.seq==null||!shouldShowEvent(ev.type,ev))continue
2574
+ prepared.push({seq:ev.seq,event:ev,view:entry.view})
2575
+ }
2576
+ const rawSeqs=incoming.map(entry=>entry?.event?.seq).filter(Number.isFinite),floor=rawSeqs.length?Math.min(...rawSeqs):Infinity
2577
+ if(reset){const retainedOlder=!!v.hasMore&&history.visible.some(entry=>entry.seq<floor);const ceiling=rawSeqs.length?Math.max(...rawSeqs)+1:Infinity;history.visible=rawSeqs.length?window.DshHistory.reconcile(history.visible,prepared,floor,!!v.hasMore,ceiling):[];history.minSeq=retainedOlder?Math.min(history.minSeq,floor):floor;history.tailEvicted=false}
2578
+ else{history.visible=window.DshHistory.reconcile(history.visible,prepared,floor,true,payload.beforeSeq);history.minSeq=Math.min(history.minSeq,floor)}
2579
+ history.seqs=new Set(history.visible.map(entry=>entry.seq));history.headEvicted=false;trimVisible(reset?'tail':'older')
2580
+ if(liveReasoning)history.partialReasoning=liveReasoning;else applyReasoningBaseline(v.partialReasoning)
2581
+ history.hasMore=(!!v.hasMore||(reset&&history.headEvicted)) && rawSeqs.length>0 && (reset || floor<payload.beforeSeq)
2582
+ history.loading=false;history.cached=false;historySource('synced');setSessionRecovery('ready')
2583
+ renderSessionTitle();renderSessionSub();renderSessionCards()
2584
+ renderHistory(!hadContent,reset?'fixed':'keep')
2585
+ $('history-hint').textContent=t('history.count',{n:history.visible.length})
2577
2586
  scheduleHistoryCacheSave()
2578
2587
  }
2579
2588
 
@@ -2590,21 +2599,9 @@ function insertLiveEvent(event) {
2590
2599
  return
2591
2600
  }
2592
2601
  h.seqs.add(seq)
2593
- h.visible.push({ seq, event })
2594
- h.visible.sort((a, b) => a.seq - b.seq)
2602
+ window.DshHistory.insertSorted(h.visible, { seq, event })
2595
2603
  trimVisible()
2596
- const box = $('history')
2597
- const nearBottom = box.scrollHeight - box.scrollTop - box.clientHeight < 240
2598
- if (nearBottom) {
2599
- h.renderEnd = h.visible.length
2600
- h.renderStart = Math.max(0, h.renderEnd - 200)
2601
- renderHistory(false, 'bottom')
2602
- } else {
2603
- // 图片异步撑高历史区后,用户可能瞬间不再满足 nearBottom。新回复仍须
2604
- // 扩展可见窗口,但保持当前阅读位置,不能等到重新进入会话才出现。
2605
- h.renderEnd = h.visible.length
2606
- renderHistory(false, 'fixed')
2607
- }
2604
+ renderHistory(false, 'fixed')
2608
2605
  scheduleHistoryCacheSave()
2609
2606
  }
2610
2607
 
@@ -2617,74 +2614,33 @@ function filteredEntries() {
2617
2614
  return f
2618
2615
  }
2619
2616
 
2620
- function renderHistory(reset, mode = 'bottom') {
2621
- const box = $('history')
2622
- const h = state.history
2623
- const filtered = filteredEntries()
2624
- const len = filtered.length
2625
- const reasoningHtml = partialReasoningHtml()
2626
- if (!len && !reasoningHtml) {
2627
- box.innerHTML = '<div class="empty">' + t('history.empty') + '</div>'
2628
- h.renderStart = 0; h.renderEnd = 0
2629
- updateRail()
2630
- return
2631
- }
2632
- if (reset) {
2633
- h.renderEnd = len
2634
- h.renderStart = Math.max(0, len - 200)
2635
- }
2636
- const start = Math.min(h.renderStart, len)
2637
- const end = Math.min(h.renderEnd, len) || len
2638
- const oldH = box.scrollHeight
2639
- const oldTop = box.scrollTop
2640
- // callId → 工具名, 供 tool/result 折叠标题显示
2641
- const toolNames = new Map()
2642
- for (const e of state.history.visible) {
2643
- if (e.event?.type !== 'tool/call') continue
2644
- const d = e.event.data || {}
2645
- if (d.callId && d.name) toolNames.set(d.callId, d.name)
2646
- }
2647
- box.innerHTML = filtered.slice(start, end).map(e => eventHtml(e, { toolNames })).join('') + reasoningHtml
2648
- if (reset || mode === 'bottom') box.scrollTop = box.scrollHeight
2649
- else if (mode === 'keep') box.scrollTop = Math.max(0, oldTop + (box.scrollHeight - oldH))
2650
- else if (mode === 'fixed') box.scrollTop = oldTop
2651
- updateRail()
2617
+ function renderHistory(reset=false,mode='auto') {
2618
+ const filtered=filteredEntries(),toolNames=new Map()
2619
+ for(const entry of state.history.visible){const d=entry.event?.data;if(entry.event?.type==='tool/call'&&d?.callId&&d.name)toolNames.set(d.callId,d.name)}
2620
+ state.history.toolNames=toolNames
2621
+ $('history-hint').textContent=t('history.count',{n:state.history.visible.length})
2622
+ getConversationView().set(filtered,{reset,follow:mode==='bottom',live:partialReasoningHtml(),hasMore:state.history.hasMore,loading:state.history.loading,emptyLabel:t('history.empty')})
2652
2623
  }
2653
2624
 
2654
2625
  /* 右侧导航条: 用户发言节点 + 拖动快速定位 */
2655
- function updateRail() {
2656
- const box = $('history')
2657
- const thumb = $('rail-thumb')
2658
- const nodesBox = $('rail-nodes')
2659
- if (!box || !thumb || !nodesBox) return
2660
- const sh = box.scrollHeight
2661
- const ch = box.clientHeight
2662
- if (sh <= ch) {
2663
- thumb.style.display = 'none'
2664
- nodesBox.innerHTML = ''
2665
- return
2666
- }
2667
- thumb.style.display = ''
2668
- const trackH = Math.max(1, ch - 8)
2669
- const thumbH = Math.max(32, ch / sh * trackH)
2670
- const maxTop = trackH - thumbH
2671
- const ratio = box.scrollTop / Math.max(1, sh - ch)
2672
- thumb.style.height = thumbH + 'px'
2673
- thumb.style.top = (4 + ratio * maxTop) + 'px'
2674
-
2675
- const boxTop = box.getBoundingClientRect().top
2676
- const userNodes = [...box.querySelectorAll('.msg.user')]
2677
- nodesBox.innerHTML = userNodes.map(el => {
2678
- const off = el.getBoundingClientRect().top - boxTop + box.scrollTop
2679
- const pos = Math.min(4 + trackH, 4 + off / Math.max(1, sh) * trackH)
2680
- return `<div class="rail-node" data-offset="${Math.round(off)}" style="top:${pos}px"></div>`
2681
- }).join('')
2682
- let activeIdx = -1
2683
- userNodes.forEach((el, i) => {
2684
- const off = el.getBoundingClientRect().top - boxTop + box.scrollTop
2685
- if (off <= box.scrollTop + 60) activeIdx = i
2686
- })
2687
- if (activeIdx >= 0) nodesBox.children[activeIdx]?.classList.add('active')
2626
+ let historyRailLayout=null
2627
+ function updateRail(rebuild=false) {
2628
+ const box=$('history'),thumb=$('rail-thumb'),nodesBox=$('rail-nodes')
2629
+ if(!box||!thumb||!nodesBox)return
2630
+ const sh=box.scrollHeight,ch=box.clientHeight
2631
+ if(sh<=ch){thumb.style.display='none';nodesBox.replaceChildren();historyRailLayout=null;return}
2632
+ thumb.style.display=''
2633
+ const trackH=Math.max(1,ch-8),thumbH=Math.max(32,ch/sh*trackH),ratio=box.scrollTop/Math.max(1,sh-ch)
2634
+ thumb.style.height=thumbH+'px';thumb.style.top=(4+ratio*(trackH-thumbH))+'px'
2635
+ if(rebuild||!historyRailLayout||historyRailLayout.height!==sh||historyRailLayout.width!==box.clientWidth){
2636
+ const top=box.getBoundingClientRect().top
2637
+ const allOffsets=[...box.querySelectorAll('.msg.user')].map(el=>el.getBoundingClientRect().top-top+box.scrollTop)
2638
+ const count=Math.min(24,allOffsets.length),offsets=Array.from({length:count},(_,i)=>allOffsets[Math.round(i*(allOffsets.length-1)/Math.max(1,count-1))])
2639
+ nodesBox.innerHTML=offsets.map(off=>'<div class="rail-node" data-offset="'+Math.round(off)+'" style="top:'+Math.min(4+trackH,4+off/Math.max(1,sh)*trackH)+'px"></div>').join('')
2640
+ historyRailLayout={height:sh,width:box.clientWidth,offsets}
2641
+ }
2642
+ let active=-1;historyRailLayout.offsets.forEach((offset,i)=>{if(offset<=box.scrollTop+60)active=i})
2643
+ for(let i=0;i<nodesBox.children.length;i++)nodesBox.children[i].classList.toggle('active',i===active)
2688
2644
  }
2689
2645
 
2690
2646
  function bindRail() {
@@ -2695,6 +2651,8 @@ function bindRail() {
2695
2651
  nodesBox.addEventListener('click', (e) => {
2696
2652
  const node = e.target.closest('.rail-node')
2697
2653
  if (!node) return
2654
+ getConversationView().intentUntil=Date.now()+1500
2655
+ getConversationView().reading=true
2698
2656
  box.scrollTo({ top: Math.max(0, Number(node.dataset.offset) - 10), behavior: 'smooth' })
2699
2657
  })
2700
2658
  let drag = null
@@ -2704,6 +2662,8 @@ function bindRail() {
2704
2662
  })
2705
2663
  thumb.addEventListener('pointermove', (e) => {
2706
2664
  if (!drag) return
2665
+ getConversationView().intentUntil=Date.now()+1500
2666
+ getConversationView().reading=true
2707
2667
  const trackH = Math.max(1, box.clientHeight - 8)
2708
2668
  const delta = (e.clientY - drag.y) / trackH * Math.max(1, box.scrollHeight - box.clientHeight)
2709
2669
  box.scrollTop = Math.max(0, Math.min(box.scrollHeight - box.clientHeight, drag.top + delta))
@@ -2722,8 +2682,7 @@ const INTERESTING_EVENTS = new Set([
2722
2682
  'goal/created', 'goal/updated', 'goal/completed', 'goal/cleared',
2723
2683
  'todo/updated', 'plan/updated',
2724
2684
  'question/asked', 'question/resolved',
2725
- 'approval/asked', 'approval/resolved',
2726
- 'session/title', 'title'
2685
+ 'approval/asked', 'approval/resolved'
2727
2686
  ])
2728
2687
  function messageSource(data) {
2729
2688
  const source = data?.source ?? data?.message?.source
@@ -2838,8 +2797,20 @@ function statsHtml(s) {
2838
2797
  return html || '<div class="empty">' + t('stats.empty') + '</div>'
2839
2798
  }
2840
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
+ }
2841
2811
  let sessionCardsRenderGeneration = 0
2842
2812
  async function renderSessionCards() {
2813
+ const connection = captureConnection()
2843
2814
  window.DshInsights?.update()
2844
2815
  const renderGeneration = ++sessionCardsRenderGeneration
2845
2816
  const sessionId = state.current
@@ -2891,8 +2862,8 @@ async function renderSessionCards() {
2891
2862
  }))
2892
2863
 
2893
2864
  // 子代理
2894
- const sub = await safeRpc('subagent.list', { parentSessionId: sessionId })
2895
- if (renderGeneration !== sessionCardsRenderGeneration || state.current !== sessionId) return
2865
+ const sub = await loadSessionSubagents(sessionId)
2866
+ if (!connection.valid() || renderGeneration !== sessionCardsRenderGeneration || state.current !== sessionId) return
2896
2867
  if (sub?.entries?.length) {
2897
2868
  const expanded = state.subagentExpandedSession === sessionId
2898
2869
  const toggleLabel = expanded ? t('subagent.collapse') : t('subagent.expand')
@@ -2928,6 +2899,8 @@ function setGoalPhaseLocal(phase) {
2928
2899
  }
2929
2900
 
2930
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
2931
2904
  const s = state.byId.get(state.current)
2932
2905
  const goal = goalOf(s)
2933
2906
  if (!goal) return toast(t('goal.none'))
@@ -2938,8 +2911,8 @@ async function goalAction(kind) {
2938
2911
  if (!method) return
2939
2912
  if (kind === 'clear' && !confirm(t('goal.confirmClear'))) return
2940
2913
  if (kind === 'complete' && !confirm(t('goal.confirmComplete'))) return
2941
- const result = await safeRpc(method, { sessionId: state.current, ref }, t('goal.actionFailed'))
2942
- if (result == null) return
2914
+ const result = await safeRpc(method, { sessionId, ref }, t('goal.actionFailed'))
2915
+ if (result == null || !valid()) return
2943
2916
  if (kind === 'complete') setGoalPhaseLocal('complete')
2944
2917
  if (kind === 'clear') setGoalPhaseLocal('cleared')
2945
2918
  toast(t('goal.actionSubmitted'), 'ok')
@@ -2980,19 +2953,22 @@ function sessionLogExportUrl(sessionId, includeToken = false) {
2980
2953
  }
2981
2954
 
2982
2955
  async function downloadSessionExport(sessionId) {
2956
+ const connection = captureConnection()
2983
2957
  const nativePlatform = !!CAP?.isNativePlatform?.()
2984
2958
  const nativeDownload = !!(nativePlatform && window.NativeFile?.downloadToDownloads)
2985
2959
  if (nativePlatform && !nativeDownload) {
2986
2960
  toast(t('fs.downloadUnsupported'), 'err')
2987
2961
  return
2988
2962
  }
2989
- 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))
2990
2965
  const headers = state.token ? { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() } : {}
2991
2966
  try {
2992
2967
  const signal = typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'
2993
2968
  ? AbortSignal.timeout(LONG_RUNNING_SLASH_COMMAND_TIMEOUT_MS)
2994
2969
  : undefined
2995
2970
  const preflight = await fetch(url, { method: 'HEAD', headers, ...(signal ? { signal } : {}) })
2971
+ if (!connection.valid()) return
2996
2972
  if (preflight.status === 401) { authFailure(); return }
2997
2973
  if (!preflight.ok) throw new Error('HTTP ' + preflight.status)
2998
2974
  const filename = sessionLogFilename(sessionId)
@@ -3018,6 +2994,7 @@ async function downloadSessionExport(sessionId) {
3018
2994
  async function runSlashCommand(text) {
3019
2995
  const clean = String(text || '').trim()
3020
2996
  if (!clean.startsWith('/') || !state.current) return false
2997
+ const sessionId = state.current, connection = captureConnection()
3021
2998
  const command = slashCommandName(clean)
3022
2999
  const noFallback = NO_FALLBACK_SLASH_COMMANDS.has(command)
3023
3000
  const longRunning = command === 'export'
@@ -3028,37 +3005,39 @@ async function runSlashCommand(text) {
3028
3005
  const res = await fetch(apiUrl('/remote/api/command'), {
3029
3006
  method: 'POST',
3030
3007
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() },
3031
- body: JSON.stringify({ sessionId: state.current, line: clean }),
3008
+ body: JSON.stringify({ sessionId, line: clean }),
3032
3009
  ...(signal ? { signal } : {})
3033
3010
  })
3011
+ if (!connection.valid()) return true
3034
3012
  if (res.status === 401) { authFailure(); return true }
3035
3013
  if (!res.ok) {
3036
3014
  if (noFallback) toast(t('session.commandTimedOut'), 'err')
3037
3015
  return noFallback
3038
3016
  }
3039
3017
  const data = await res.json().catch(() => null)
3018
+ if (!connection.valid()) return true
3040
3019
  if (data?.ok === false) { toast(data.message || t('send.failed'), 'err'); return true }
3041
3020
  if (data?.ok && data.executed === true) {
3042
3021
  if (data.accepted) {
3043
3022
  if (command === 'compact') {
3044
- setCompactionStatus(state.current, { ...(data.operation || data.compact), active: true, command, source: 'command' })
3023
+ setCompactionStatus(sessionId, { ...(data.operation || data.compact), active: true, command, source: 'command' })
3045
3024
  } else {
3046
- const sessionId = state.current
3047
3025
  state.pendingCommands[sessionId] = command
3048
- setTimeout(() => { if (state.current === sessionId) void refreshCompactionStatus(sessionId) }, 600)
3026
+ setTimeout(() => { if (connection.valid() && state.current === sessionId) void refreshCompactionStatus(sessionId) }, 600)
3049
3027
  }
3050
- } else if (command === 'export') await downloadSessionExport(state.current)
3028
+ } else if (command === 'export') await downloadSessionExport(sessionId)
3051
3029
  else toast(t('send.commandExecuted'), 'ok')
3052
3030
  return true
3053
3031
  }
3054
3032
  } catch (e) {
3033
+ if (!connection.valid() || state.current !== sessionId) return true
3055
3034
  console.error('slash command bridge failed', e)
3056
3035
  if (noFallback) {
3057
3036
  toast(t('session.commandTimedOut'), 'err')
3058
3037
  return true
3059
3038
  }
3060
3039
  }
3061
- return false
3040
+ return !connection.valid() || state.current !== sessionId
3062
3041
  }
3063
3042
 
3064
3043
  function bytesToBase64(bytes) {
@@ -3275,12 +3254,13 @@ async function sendSessionContent(text, images, requestedMode = 'queue') {
3275
3254
  composerSending = true
3276
3255
  const buttons = [$('btn-send'), $('btn-fs-send')].filter(Boolean)
3277
3256
  buttons.forEach(button => { button.disabled = true })
3278
- state.pendingPrompts.add(sessionId)
3257
+ const pendingPrompts = state.pendingPrompts, sessionActivity = state.sessionActivity
3258
+ pendingPrompts.add(sessionId)
3279
3259
  try {
3280
3260
  if (mode === 'steer') setComposerSendFeedback(context, 'send.steerPending', 'pending')
3281
3261
  else { composerSendFeedback.delete(context); renderComposerSend() }
3282
3262
  if (images.length === 0 && clean && await runSlashCommand(clean)) {
3283
- state.sessionActivity.add(sessionId)
3263
+ sessionActivity.add(sessionId)
3284
3264
  return true
3285
3265
  }
3286
3266
  const content = [...await encodeComposerImagesFor(images)]
@@ -3324,7 +3304,7 @@ async function sendSessionContent(text, images, requestedMode = 'queue') {
3324
3304
  }
3325
3305
  return false
3326
3306
  } finally {
3327
- state.pendingPrompts.delete(sessionId)
3307
+ pendingPrompts.delete(sessionId)
3328
3308
  composerSending = false
3329
3309
  buttons.forEach(button => { button.disabled = false })
3330
3310
  renderComposerSend()
@@ -3376,16 +3356,21 @@ function mobileEnterAction() {
3376
3356
 
3377
3357
  async function loadSessionModels() {
3378
3358
  if (!state.current || state.models.loading) return
3379
- 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
3380
3363
  renderModelMenu()
3381
3364
  try {
3382
- const v = await rpc('session.models', { sessionId: state.current })
3383
- state.models.groups = v.groups || []
3384
- state.models.current = v.current || null
3385
- state.models.failures = v.failures || []
3386
- 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
3387
3371
  } catch (e) {
3388
- if (e.message === 'AUTH') { authFailure(); return }
3372
+ if (!valid()) return
3373
+ if (e.message === 'AUTH') { models.loading = false; renderModelMenu(); authFailure(); return }
3389
3374
  toast(t('models.loadFailed', { msg: e.message }), 'err')
3390
3375
  }
3391
3376
  state.models.loading = false
@@ -3458,9 +3443,12 @@ function reasoningEffortOptions(model) {
3458
3443
  async function selectSessionEffort(effortId) {
3459
3444
  const cur = state.models.current
3460
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
3461
3448
  const v = await safeRpc('session.selectModel', {
3462
- sessionId: state.current, provider: cur.provider, model: cur.model, reasoningEffort: effortId
3449
+ sessionId, provider: cur.provider, model: cur.model, reasoningEffort: effortId
3463
3450
  }, t('models.effortFailed'))
3451
+ if (!connection.valid() || state.current !== sessionId || state.models !== models || models.request !== request) return
3464
3452
  if (v?.selected) {
3465
3453
  state.models.current = v.selected
3466
3454
  renderEffortMenu()
@@ -3470,12 +3458,15 @@ async function selectSessionEffort(effortId) {
3470
3458
 
3471
3459
  async function selectSessionModel(provider, modelId) {
3472
3460
  if (!state.current) return
3461
+ const connection = captureConnection(), sessionId = state.current, models = state.models
3462
+ const request = models.request = (models.request || 0) + 1
3473
3463
  const group = (state.models.groups || []).find(g => g.id === provider)
3474
3464
  const model = (group?.models || []).find(m => m.id === modelId)
3475
- const payload = { sessionId: state.current, provider, model: modelId }
3465
+ const payload = { sessionId, provider, model: modelId }
3476
3466
  const effort = model?.reasoning?.defaultEffort || model?.reasoning?.efforts?.[0]?.id
3477
3467
  if (effort) payload.reasoningEffort = effort
3478
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
3479
3470
  if (v?.selected) {
3480
3471
  state.models.current = v.selected
3481
3472
  renderModelMenu()
@@ -3549,22 +3540,27 @@ function closeNewSessionModal() {
3549
3540
  $('modal-new-session').classList.add('hidden')
3550
3541
  }
3551
3542
  async function createSessionInWorkspace() {
3543
+ if (createSessionInWorkspace.busy) return
3544
+ const connection = captureConnection()
3552
3545
  const workspaceId = $('new-session-workspace').value
3553
3546
  if (!workspaceById(workspaceId)) return toast(t('newSession.chooseWorkspace'), 'err')
3554
3547
  const button = $('new-session-create')
3548
+ createSessionInWorkspace.busy = true
3555
3549
  button.disabled = true
3556
- const v = await safeRpc('session.create', { workspaceId: workspaceId }, t('home.createFailed'))
3557
- button.disabled = false
3558
- if (!v?.sessionId) return
3559
- state.workspaceFilter = workspaceId
3560
- state.fs.workspaceId = workspaceId
3561
- LS.set('workspaceFilterV1', workspaceId)
3562
- LS.set('fsWorkspaceIdV1', workspaceId)
3563
- LS.set('lastNewSessionWorkspaceV1', workspaceId)
3564
- closeNewSessionModal()
3565
- toast(t('home.created'), 'ok')
3566
- await refreshSessions()
3567
- 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 }
3568
3564
  }
3569
3565
 
3570
3566
  let archivePendingSessionId = null
@@ -3648,36 +3644,88 @@ function bindSessionSwipe() {
3648
3644
  }
3649
3645
 
3650
3646
  /* ---------------- 系统总览 / 待办 ---------------- */
3647
+ let overviewDetector = null
3648
+ let overviewPulse = null
3649
+ function setOverviewText(id,value){const node=$(id);if(overviewPulse)overviewPulse.text(node,value);else if(node)node.textContent=value}
3650
+ let overviewStarting = true
3651
+ function overviewChecks() {
3652
+ const confirmed=overviewDetector?.model.gateway===true,health=activeGatewayHealth()
3653
+ return {
3654
+ gateway: !!state.token && (!!state.server || /^https?:$/.test(location.protocol)) && confirmed,
3655
+ dsh: dshReachable() && confirmed,
3656
+ mux: !!state.streamsOk?.mux && confirmed && health?.events?.mux?.connected!==false,
3657
+ host: !!state.streamsOk?.host && confirmed && health?.events?.host?.connected!==false
3658
+ }
3659
+ }
3660
+ function repairMissingStreams() {
3661
+ if(!state.token||!navigator.onLine||state.selectingServer||overviewStarting)return
3662
+ if(state.streamMode==='poll'){tryRestoreWs();return}
3663
+ for(const [kind,handler,refresh] of [['mux',onMuxFrame,true],['host',onHostFrame,false]]) {
3664
+ const ws=streams[kind]
3665
+ if((!ws||ws.readyState===WebSocket.CLOSED)&&!streamMeta[kind].retryTimer)openStream(kind,handler,refresh)
3666
+ }
3667
+ }
3668
+ async function probeOverviewLinks(signal) {
3669
+ const connection=captureConnection(),base=String(connection.server||location.origin).replace(/\/+$/,'')
3670
+ let timer
3671
+ const controller=new AbortController(),cancel=()=>controller.abort()
3672
+ signal.addEventListener('abort',cancel,{once:true});if(signal.aborted)controller.abort()
3673
+ timer=setTimeout(cancel,4000)
3674
+ const healthRequest=fetch(base+'/health?probe=live&t='+Date.now(),{signal:controller.signal,cache:'no-store'}).then(async response=>{
3675
+ if(!response.ok)throw Error('health')
3676
+ const health=await response.json();if(health?.ok!==true)throw Error('health')
3677
+ return health
3678
+ }).catch(()=>null).finally(()=>{clearTimeout(timer);signal.removeEventListener('abort',cancel)})
3679
+ const [health,host]=await Promise.all([healthRequest,refreshHostDescription()])
3680
+ if(!connection.valid()||signal.aborted)throw Error('stale check')
3681
+ if(health){if(host)health.upstreamReachable=true;state.gatewayHealth[base]=health}
3682
+ else delete state.gatewayHealth[base]
3683
+ return {gateway:!!health}
3684
+ }
3685
+ function startOverviewDetection(force=false,identityChanged=false) {
3686
+ if(identityChanged)overviewDetector?.pause()
3687
+ if(!window.DshLinkCheck)return
3688
+ if(!overviewDetector)overviewDetector=new window.DshLinkCheck.LinkCheck({
3689
+ active:()=>document.visibilityState==='visible'&&!$('view-activity').classList.contains('hidden'),
3690
+ configured:()=>!!state.token&&(!!state.server||/^https?:$/.test(location.protocol)),online:()=>navigator.onLine,
3691
+ snapshot:overviewChecks,repair:repairMissingStreams,probe:probeOverviewLinks,changed:renderOverview
3692
+ })
3693
+ overviewDetector.start(force)
3694
+ }
3695
+ window.addEventListener('online',()=>startOverviewDetection(true))
3696
+ window.addEventListener('offline',()=>startOverviewDetection(true))
3697
+ document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible')startOverviewDetection(true);else {overviewDetector?.pause();overviewPulse?.pause()}})
3698
+
3651
3699
  function renderOverview() {
3652
3700
  const ring = $('overview-pulse-ring')
3653
3701
  if (!ring) return
3654
- const checks = {
3655
- // 独立网关页面默认走同源,此时 state.server 合法地为空;不能因此把
3656
- // 已连接网关误报为离线。Capacitor 等非 HTTP 页面仍要求显式服务器。
3657
- gateway: !!state.token && (!!state.server || /^https?:$/.test(location.protocol)),
3658
- dsh: dshReachable(),
3659
- mux: !!state.streamsOk?.mux,
3660
- host: !!state.streamsOk?.host
3661
- }
3702
+ const checks = overviewChecks()
3703
+ const detection=overviewDetector?.model,checking=detection?.phase==='checking'||(detection?.phase==='degraded'&&detection?.probing===true)
3662
3704
  const online = Object.values(checks).filter(Boolean).length
3705
+ $('overview-refresh').disabled=detection?.probing===true
3663
3706
  const status = online === 4 ? 'nominal' : online > 0 ? 'degraded' : 'offline'
3664
3707
  const pulseCard = document.querySelector('.overview-pulse-card')
3665
3708
  if (pulseCard) {
3709
+ if(!overviewPulse&&window.DshLinkCheck?.PulseVisual)overviewPulse=new window.DshLinkCheck.PulseVisual({card:pulseCard,active:()=>document.visibilityState==='visible'&&!$('view-activity').classList.contains('hidden')})
3710
+ overviewPulse?.setChecking(checking)
3711
+ overviewPulse?.setLinks(checks)
3666
3712
  pulseCard.classList.remove('status-nominal', 'status-degraded', 'status-offline')
3713
+ pulseCard.classList.toggle('status-checking',checking)
3714
+ pulseCard.setAttribute('aria-busy',String(checking))
3667
3715
  pulseCard.classList.add('status-' + status)
3668
3716
  }
3669
- ring.style.setProperty('--pulse-pct', `${online / 4 * 100}%`)
3670
- $('overview-health').textContent = online === 4 ? t('overview.live') : online ? `${online}/4` : t('overview.offlineCore')
3671
- $('overview-health-caption').textContent = online === 4 ? t('overview.allLinked') : online ? t('overview.components', { n: online }) : t('overview.offlineShort')
3672
- $('overview-status').textContent = t(`overview.${status}`)
3673
- $('overview-status-desc').textContent = t('overview.components', { n: online })
3717
+ setOverviewText('overview-health',checking ? t('overview.checking') : online === 4 ? t('overview.live') : online ? `${online}/4` : t('overview.offlineCore'))
3718
+ setOverviewText('overview-health-caption',checking ? `${online}/4` : online === 4 ? t('overview.allLinked') : online ? t('overview.confirmedShort') : t('overview.offlineShort'))
3719
+ setOverviewText('overview-status',checking ? t('overview.checking') : t(`overview.${status}`))
3720
+ setOverviewText('overview-status-desc',checking ? t('overview.autoChecking',{n:online}) : detection?.phase==='degraded' ? t('overview.autoRetry',{n:online}) : t('overview.components',{n:online}))
3674
3721
  for (const [name, ok] of Object.entries(checks)) {
3675
3722
  const item = document.querySelector(`[data-overview-link="${name}"]`)
3676
3723
  if (!item) continue
3677
3724
  item.classList.toggle('ok', ok)
3678
- item.classList.toggle('off', !ok)
3725
+ item.classList.toggle('off', !ok&&!checking)
3726
+ item.classList.toggle('pending',!ok&&checking)
3679
3727
  const value = item.querySelector('b')
3680
- if (value) value.textContent = ok ? t('overview.online') : t('overview.offlineShort')
3728
+ if (value) setOverviewText(value.id || (value.id=`overview-link-${name}`), ok ? t('overview.online') : checking ? t('overview.checkingShort') : t('overview.offlineShort'))
3681
3729
  }
3682
3730
 
3683
3731
  const pending = [
@@ -3816,18 +3864,21 @@ function renderSessionPending() {
3816
3864
  }
3817
3865
 
3818
3866
  async function approveApproval(id, allow) {
3867
+ const connection = captureConnection()
3819
3868
  const a = state.approvals.find(x => x.approvalId === id)
3820
3869
  if (!a) return
3821
3870
  let ok
3822
3871
  try {
3823
3872
  ok = await respond(a.rpcId, { sessionId: a.sessionId, approvalId: a.approvalId, outcome: allow ? 'allowed-once' : 'rejected' })
3824
3873
  } catch (e) {
3874
+ if (!connection.valid()) return
3825
3875
  if (e.message === 'AUTH') authFailure()
3826
3876
  else toast(t('pending.submitFailed', { msg: e.message || t('fs.networkError') }), 'err')
3827
3877
  return
3828
3878
  }
3879
+ if (!connection.valid()) return
3829
3880
  toast(ok ? (allow ? t('pending.allowed') : t('pending.rejected')) : t('pending.stale'), ok ? 'ok' : 'err')
3830
- state.approvals = state.approvals.filter(x => x.approvalId !== id)
3881
+ state.approvals = state.approvals.filter(x => x.rpcId !== a.rpcId)
3831
3882
  renderPending()
3832
3883
  }
3833
3884
 
@@ -3845,6 +3896,7 @@ function openQuestionModal(q) {
3845
3896
  }
3846
3897
 
3847
3898
  async function submitQuestion() {
3899
+ const connection = captureConnection()
3848
3900
  const q = state.questionModal
3849
3901
  if (!q) return
3850
3902
  const answers = q.questions.map((item, i) => {
@@ -3860,11 +3912,18 @@ async function submitQuestion() {
3860
3912
  try {
3861
3913
  ok = await respond(q.rpcId, { sessionId: q.sessionId, answer: { answers } })
3862
3914
  } catch (e) {
3915
+ if (!connection.valid()) return
3863
3916
  if (e.message === 'AUTH') authFailure()
3864
3917
  else toast(t('question.submitFailed', { msg: e.message || t('fs.networkError') }), 'err')
3865
3918
  return
3866
3919
  }
3867
- 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
+ }
3868
3927
  else toast(t('question.stale'), 'err')
3869
3928
  }
3870
3929
 
@@ -4595,6 +4654,7 @@ function bindFsPullRefresh() {
4595
4654
  /* ---------------- goal 编辑 ---------------- */
4596
4655
  function openGoalModal(goal) {
4597
4656
  state.goalEdit = goal
4657
+ state.goalEditContext = { connection: captureConnection(), sessionId: state.current, history: state.history }
4598
4658
  $('goal-body').innerHTML = `
4599
4659
  <div class="kv"><span class="k">phase</span><span class="v">${esc(goal.phase || '?')}</span></div>
4600
4660
  <div class="kv"><span class="k">revision</span><span class="v">${goal.revision ?? '?'}</span></div>
@@ -4606,10 +4666,13 @@ function openGoalModal(goal) {
4606
4666
  async function submitGoalEdit() {
4607
4667
  const goal = state.goalEdit
4608
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 }
4609
4672
  const objective = $('goal-edit-text')?.value?.trim()
4610
4673
  if (!objective) return toast(t('goal.cannotEmpty'), 'err')
4611
- const result = await safeRpc('goal.edit', { sessionId: state.current, ref: { id: goal.id, revision: goal.revision }, objective }, t('goal.updateFailed'))
4612
- 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
4613
4676
  $('modal-goal').classList.add('hidden')
4614
4677
  toast(t('goal.updated'), 'ok')
4615
4678
  scheduleRefresh()
@@ -5266,11 +5329,9 @@ async function verifyUpdateApk(info, url) {
5266
5329
  phase = 'verifying'
5267
5330
  updateDownloadProgress({ phase, received, total: total || received })
5268
5331
  const expected = String(info.sha256 || '').trim().toLowerCase()
5269
- if (expected) {
5270
- if (!/^[0-9a-f]{64}$/.test(expected)) return { ok: false, corrupted: true }
5271
- const actual = await sha256Hex(await blob.arrayBuffer())
5272
- if (actual !== expected) return { ok: false, corrupted: true }
5273
- }
5332
+ if (!/^[0-9a-f]{64}$/.test(expected)) return { ok: false, corrupted: true }
5333
+ const actual = await sha256Hex(await blob.arrayBuffer())
5334
+ if (actual !== expected) return { ok: false, corrupted: true }
5274
5335
  return { ok: true, blob }
5275
5336
  } catch (err) { return { ok: false, network: true, msg: err?.message || '' } }
5276
5337
  finally { clearTimeout(timer); clearInterval(progressTimer) }
@@ -5280,13 +5341,19 @@ async function downloadUpdate() {
5280
5341
  const info = state.updateInfo
5281
5342
  if (!info || updateDownloadBusy) return
5282
5343
  const url = new URL(info.apkUrl || 'dsh-remote.apk', updateBase() + '/').href
5344
+ const sha256 = String(info.sha256 || '').trim().toLowerCase()
5345
+ if (!/^[0-9a-f]{64}$/.test(sha256)) {
5346
+ // 无 SHA-256 的更新包一律不下载、不安装
5347
+ updateDownloadProgress({ phase: 'error', error: t('update.hashMissing') })
5348
+ return
5349
+ }
5283
5350
  updateDownloadBusy = true
5284
5351
  updateDownloadSample = null
5285
5352
  $('btn-download-update').disabled = true
5286
5353
  updateDownloadProgress({ phase: 'downloading', received: 0, total: 0 })
5287
5354
  if (CAP?.isNativePlatform?.() && window.NativeUpdate?.downloadVerifiedAndInstall && window.NativeUpdate?.getDownloadStatus) {
5288
5355
  try {
5289
- if (!window.NativeUpdate.downloadVerifiedAndInstall(url, String(info.sha256 || '').trim())) throw new Error(t('update.busy'))
5356
+ if (!window.NativeUpdate.downloadVerifiedAndInstall(url, sha256)) throw new Error(t('update.busy'))
5290
5357
  const poll = () => {
5291
5358
  try {
5292
5359
  const value = JSON.parse(window.NativeUpdate.getDownloadStatus())
@@ -5302,11 +5369,8 @@ async function downloadUpdate() {
5302
5369
  try {
5303
5370
  const result = await verifyUpdateApk(info, url)
5304
5371
  if (!result.ok) throw new Error(result.corrupted ? t('update.corrupted') : result.status ? t('update.serverFileMissing') : result.msg || t('fs.networkError'))
5305
- if (CAP?.isNativePlatform?.() && window.NativeUpdate?.downloadAndInstall) {
5306
- // 旧壳不具备进度桥;安装本次新版后即可使用单次下载和完整进度。
5307
- window.NativeUpdate.downloadAndInstall(url)
5308
- updateDownloadProgress({ phase: 'legacy', received: 0, total: 0 })
5309
- } else {
5372
+ {
5373
+ // 无校验的原生安装入口已移除: 新旧壳统一走下方"下载并本地校验"路径。
5310
5374
  const objectUrl = URL.createObjectURL(result.blob)
5311
5375
  const link = document.createElement('a')
5312
5376
  link.href = objectUrl
@@ -5660,6 +5724,7 @@ function modelReasoningError(models) {
5660
5724
  }
5661
5725
 
5662
5726
  async function loadModelSettings(force = false) {
5727
+ const connection = captureConnection()
5663
5728
  if (!state.token) {
5664
5729
  state.modelSettings = { ...state.modelSettings, status: 'error', error: t('token.notSetHint') }
5665
5730
  renderModelSettings()
@@ -5674,6 +5739,7 @@ async function loadModelSettings(force = false) {
5674
5739
  rpc('llm.providers', {}),
5675
5740
  rpc('settings.describe', {})
5676
5741
  ])
5742
+ if (!connection.valid()) return
5677
5743
  const namespaces = Array.isArray(settingsValue?.namespaces) ? settingsValue.namespaces : []
5678
5744
  const providers = Array.isArray(providersValue?.providers) ? providersValue.providers : []
5679
5745
  const rows = providers.map(entry => {
@@ -5695,6 +5761,7 @@ async function loadModelSettings(force = false) {
5695
5761
  let credentials = {}
5696
5762
  if (refs.length > 0) {
5697
5763
  const value = await rpc('credentials.describe', { refs })
5764
+ if (!connection.valid()) return
5698
5765
  credentials = value?.credentials && typeof value.credentials === 'object' ? value.credentials : {}
5699
5766
  }
5700
5767
  state.modelSettings = {
@@ -5708,6 +5775,7 @@ async function loadModelSettings(force = false) {
5708
5775
  }
5709
5776
  state.modelEditor = null
5710
5777
  } catch (error) {
5778
+ if (!connection.valid()) return
5711
5779
  state.modelSettings = { ...state.modelSettings, status: 'error', error: error?.message || String(error) }
5712
5780
  }
5713
5781
  renderModelSettings()
@@ -5911,6 +5979,7 @@ function setModelEditorError(message) {
5911
5979
  async function discoverModelSettings() {
5912
5980
  const editor = state.modelEditor
5913
5981
  if (!editor || editor.busy) return
5982
+ const connection = captureConnection(), valid = () => connection.valid() && state.modelEditor === editor
5914
5983
  collectModelEditorForm()
5915
5984
  editor.busy = true
5916
5985
  editor.error = ''
@@ -5922,17 +5991,19 @@ async function discoverModelSettings() {
5922
5991
  if (editor.api) payload.api = editor.api
5923
5992
  if (editor.keyDraft.trim()) payload.apiKey = editor.keyDraft.trim()
5924
5993
  const value = await rpc('llm.discoverModels', payload)
5994
+ if (!valid()) return
5925
5995
  const found = Array.isArray(value?.models) ? value.models.filter(model => model && typeof model.id === 'string' && model.id.trim()) : []
5926
5996
  if (!found.length) throw new Error(t('settings.modelFetchEmpty'))
5927
5997
  const known = new Set(editor.models.map(model => model.id))
5928
5998
  editor.discovered = found
5929
5999
  editor.discoverySelected = new Set(found.filter(model => !known.has(model.id)).map(model => model.id))
5930
6000
  } catch (error) {
6001
+ if (!valid()) return
5931
6002
  editor.error = t('settings.modelFetchFailed', { msg: error?.message || String(error) })
5932
6003
  } finally {
5933
6004
  editor.busy = false
5934
6005
  }
5935
- renderModelSettings()
6006
+ if (valid()) renderModelSettings()
5936
6007
  }
5937
6008
 
5938
6009
  function addDiscoveredModels() {
@@ -5954,6 +6025,7 @@ function addDiscoveredModels() {
5954
6025
  async function saveModelEditor() {
5955
6026
  const editor = state.modelEditor
5956
6027
  if (!editor || editor.busy) return
6028
+ const connection = captureConnection(), valid = () => connection.valid() && state.modelEditor === editor
5957
6029
  collectModelEditorForm()
5958
6030
  if (!state.modelSettings.writable) return setModelEditorError(t('settings.modelReadOnly'))
5959
6031
  const models = editor.models || []
@@ -5984,6 +6056,7 @@ async function saveModelEditor() {
5984
6056
  })
5985
6057
  if (ops.length) {
5986
6058
  const value = await rpc('settings.mutate', { ns: editor.settingsNs, ops, expectedRevision: editor.namespace.revision })
6059
+ if (!valid()) return
5987
6060
  editor.namespace = value
5988
6061
  }
5989
6062
  if (editor.keyDraft.trim()) {
@@ -5991,10 +6064,13 @@ async function saveModelEditor() {
5991
6064
  } else if (editor.clearKey && editor.keyConfigured && editor.keyRef) {
5992
6065
  await rpc('credentials.unset', { ref: editor.keyRef })
5993
6066
  }
6067
+ if (!valid()) return
5994
6068
  state.modelEditor = null
5995
6069
  await loadModelSettings(true)
6070
+ if (!connection.valid()) return
5996
6071
  toast(t('settings.modelSaved'), 'ok')
5997
6072
  } catch (error) {
6073
+ if (!valid()) return
5998
6074
  editor.error = t('settings.modelSaveFailed', { msg: error?.message || String(error) })
5999
6075
  } finally {
6000
6076
  if (state.modelEditor === editor) {
@@ -6084,6 +6160,8 @@ function showView(id) {
6084
6160
  for (const v of ['view-home', 'view-files', 'view-session', 'view-activity', 'view-plugins', 'view-settings']) $(v).classList.toggle('hidden', v !== id)
6085
6161
  // 离开会话页必须清掉 in-session, 否则其他页面顶栏被 body 样式隐藏
6086
6162
  document.body.classList.toggle('in-session', id === 'view-session')
6163
+ $('session-actions')?.close()
6164
+ $('session-info')?.close()
6087
6165
  document.querySelectorAll('.nav-btn').forEach(b => b.classList.toggle('active', b.dataset.view === id))
6088
6166
  // 主页已有上下文明确的刷新按钮,避免顶栏出现第二个同义入口。
6089
6167
  $('btn-refresh')?.classList.toggle('hidden', id === 'view-activity')
@@ -6096,6 +6174,7 @@ function showView(id) {
6096
6174
  if (id === 'view-plugins') openPluginPage()
6097
6175
  else window.DshPluginCenter?.close()
6098
6176
  if (id === 'view-settings') showSettingsHome()
6177
+ if(id==='view-activity')startOverviewDetection(true);else {overviewDetector?.pause();overviewPulse?.pause()}
6099
6178
  }
6100
6179
 
6101
6180
  const SETTINGS_GROUPS = ['general', 'model', 'tests', 'servers', 'notify', 'theme', 'about']
@@ -6116,6 +6195,7 @@ function showSettingsPage(name) {
6116
6195
  }
6117
6196
 
6118
6197
  function updateConn() {
6198
+ overviewDetector?.observe()
6119
6199
  const el = $('conn-badge')
6120
6200
  // mux/host 的打开顺序不稳定;连接状态改变时同步重绘总览,避免后打开的
6121
6201
  // 通道只更新顶栏、总览却永久停留在 3/4。
@@ -6186,8 +6266,8 @@ function updateComposerFullscreenButton() {
6186
6266
  function setComposerFullscreen(on) {
6187
6267
  const wrap = $('composer-wrap')
6188
6268
  if (!wrap) return
6189
- $('btn-stats')?.classList.toggle('hidden', !!on)
6190
- $('btn-insights')?.classList.toggle('hidden', !!on)
6269
+ $('btn-session-more')?.classList.toggle('hidden', !!on)
6270
+ $('session-actions')?.close()
6191
6271
  $('btn-fs-send')?.classList.toggle('hidden', !on)
6192
6272
  if (on) {
6193
6273
  $('composer-image-menu')?.classList.add('hidden')
@@ -6239,7 +6319,7 @@ function bindComposerFullscreenGesture() {
6239
6319
 
6240
6320
  /* ---------------- 初始化 ---------------- */
6241
6321
  /** 解析 dshremote://pair?token=..&server=.. 配对二维码;server 可重复以携带多个主机地址。 */
6242
- function applyPairUrl(url) {
6322
+ function applyPairUrl(url, options = {}) {
6243
6323
  try {
6244
6324
  const u = new URL(String(url).trim())
6245
6325
  if (u.protocol !== 'dshremote:' || u.hostname !== 'pair') return false
@@ -6248,6 +6328,13 @@ function applyPairUrl(url) {
6248
6328
  .map(value => value.trim().replace(/\/+$/, ''))
6249
6329
  .filter(value => /^https?:\/\//i.test(value)))]
6250
6330
  if (!tok || !servers.length) return false
6331
+ const alreadyPaired = (state.servers || []).some(s => normalizedServerToken(s.token) === tok
6332
+ && servers.includes(String(s.url || '').replace(/\/+$/, '')))
6333
+ if (options.confirmExisting && !alreadyPaired && (state.token || (state.servers || []).length)) {
6334
+ // 深链可被任意应用/网页触发: 已有配置时必须由用户确认,不能静默换服务器和令牌
6335
+ const confirmed = window.confirm(t('scan.pairConfirm', { servers: servers.join('\n') }))
6336
+ if (!confirmed) return false
6337
+ }
6251
6338
  const previousServer = state.server
6252
6339
  const previousToken = state.token
6253
6340
  state.token = tok
@@ -6535,14 +6622,14 @@ function bindNativeLinks() {
6535
6622
  if (!CAP?.isNativePlatform?.()) return
6536
6623
  try {
6537
6624
  CAP.Plugins?.App?.addListener?.('appUrlOpen', (data) => {
6538
- if (data?.url && applyPairUrl(data.url)) {
6625
+ if (data?.url && applyPairUrl(data.url, { confirmExisting: true })) {
6539
6626
  toast(t('scan.pairedLink'), 'ok')
6540
6627
  openStreams()
6541
6628
  refreshAll()
6542
6629
  }
6543
6630
  })
6544
6631
  CAP.Plugins?.App?.getLaunchUrl?.().then((data) => {
6545
- if (data?.url) applyPairUrl(data.url)
6632
+ if (data?.url) applyPairUrl(data.url, { confirmExisting: true })
6546
6633
  }).catch(() => {})
6547
6634
  } catch {}
6548
6635
  }
@@ -6688,7 +6775,10 @@ function renderDshControlStatus(value) {
6688
6775
  return
6689
6776
  }
6690
6777
  dshControlButtonsBusy(false, true)
6778
+ $('btn-dsh-start').disabled = value.running === true || value.canStart === false
6779
+ $('btn-dsh-restart').disabled = value.canRestart === false || value.running === false
6691
6780
  if (box && !dshControlPollPromise) box.classList.add('hidden')
6781
+ if (value.canStart === false && value.code) { desc.textContent=dshControlFailureText(value); return }
6692
6782
  const service = value.service || 'dsh-web'
6693
6783
  const serviceState = `${value.activeState || value.state || 'unknown'}/${value.subState || 'unknown'}`
6694
6784
  desc.textContent = value.running
@@ -6813,7 +6903,31 @@ function openDonateModal() {
6813
6903
  if (m) m.classList.remove('hidden')
6814
6904
  }
6815
6905
 
6906
+
6907
+ function bindSessionDialogs() {
6908
+ if (typeof ResizeObserver !== 'undefined') {
6909
+ const wrap=$('composer-wrap')
6910
+ const observer=new ResizeObserver(()=>{
6911
+ if(!wrap.classList.contains('fs'))document.documentElement.style.setProperty('--composer-height', wrap.getBoundingClientRect().height+'px')
6912
+ if(document.body.classList.contains('in-session'))document.documentElement.style.setProperty('--composer-top', $('session-sub').getBoundingClientRect().bottom+'px')
6913
+ })
6914
+ observer.observe(wrap)
6915
+ observer.observe($('session-head'))
6916
+ observer.observe($('session-sub'))
6917
+ }
6918
+ const actions=$('session-actions'), info=$('session-info');
6919
+ $('btn-session-more').addEventListener('click',()=>actions.showModal());
6920
+ actions.addEventListener('click',e=>{if(e.target===actions)actions.close();else if(e.target.closest('button'))actions.close()},true);
6921
+ const openInfo=()=>{const s=state.byId.get(state.current);if(!s)return; $('session-info-name').textContent=titleOf(s);$('session-info-path').textContent=s.cwd||t('session.noWorkspace');$('session-info-id').textContent=s.sessionId;$('btn-copy-session-workspace').disabled=!s.cwd;info.showModal()};
6922
+ $('session-title').addEventListener('click',openInfo);
6923
+ $('session-sub').addEventListener('click',openInfo);
6924
+ $('btn-session-info').addEventListener('click',openInfo);
6925
+ info.addEventListener('click',e=>{if(e.target===info||e.target.closest('[data-session-dialog-close]'))info.close()});
6926
+ $('btn-copy-session-workspace').addEventListener('click',async()=>{const value=state.byId.get(state.current)?.cwd;if(value&&await copyText(value))toast(t('feedback.copied'),'ok')});
6927
+ }
6928
+
6816
6929
  function bindUi() {
6930
+ bindSessionDialogs()
6817
6931
  renderLangBtn()
6818
6932
  renderThemeBtn()
6819
6933
  $('btn-lang').addEventListener('click', () => {
@@ -6928,7 +7042,7 @@ function bindUi() {
6928
7042
  $('btn-refresh').addEventListener('click', () => { toast(t('common.refreshing')); openStreams(); refreshAll() })
6929
7043
  $('overview-refresh').addEventListener('click', () => {
6930
7044
  toast(t('common.refreshing'))
6931
- openStreams()
7045
+ startOverviewDetection(true)
6932
7046
  void Promise.all([refreshAll(), checkAnnouncements()])
6933
7047
  })
6934
7048
  // 反馈
@@ -7190,8 +7304,10 @@ function bindUi() {
7190
7304
  $('modal-app-version-warning').addEventListener('click', (e) => {
7191
7305
  if (e.target === $('modal-app-version-warning')) closeAppVersionWarning(false)
7192
7306
  })
7193
- $('btn-reset').addEventListener('click', () => {
7307
+ $('btn-reset').addEventListener('click', async () => {
7194
7308
  if (!confirm(t('settings.confirmReset'))) return
7309
+ clearTimeout(scheduleHistoryCacheSave._t)
7310
+ await window.DshHistory.cacheClear()
7195
7311
  LS.del('token'); LS.del('notify'); LS.del('server'); LS.del('mobileEnterAction'); LS.del('steerSendingEnabled'); LS.del('busySendMode'); LS.del(ANNOUNCEMENTS_KEY); LS.del(ANNOUNCEMENT_HISTORY_KEY); LS.del(ANNOUNCEMENT_VOTES_KEY)
7196
7312
  if (bgBridge()?.saveBackgroundConfig) saveBgConfig(false)
7197
7313
  location.reload()
@@ -7305,27 +7421,8 @@ function bindUi() {
7305
7421
 
7306
7422
  initCustomSelects()
7307
7423
 
7308
- // 向上翻历史 / 向下回最新
7309
- $('history').addEventListener('scroll', () => {
7310
- const box = $('history')
7311
- const h = state.history
7312
- updateRail()
7313
- if (!state.current || !h.filtered?.length) return
7314
- if (box.scrollTop < 80) {
7315
- if (h.renderStart > 0) {
7316
- h.renderStart = Math.max(0, h.renderStart - 100)
7317
- renderHistory(false, 'keep')
7318
- } else if (h.hasMore && !h.loading) {
7319
- loadHistory(false)
7320
- }
7321
- } else if (box.scrollHeight - box.scrollTop - box.clientHeight < 240) {
7322
- if (h.renderEnd < h.filtered.length) {
7323
- h.renderEnd = h.filtered.length
7324
- h.renderStart = Math.max(0, h.renderEnd - 200)
7325
- renderHistory(false, 'bottom')
7326
- }
7327
- }
7328
- })
7424
+ $('btn-history-latest').addEventListener('click',()=>{getConversationView().latest();if(state.history.tailEvicted)void loadHistory(true)})
7425
+ $('history').addEventListener('load',()=>updateRail(true),true)
7329
7426
  }
7330
7427
 
7331
7428
  /* App 内真实系统栏 inset(刘海/状态栏/手势条) */
@@ -7352,14 +7449,15 @@ async function boot() {
7352
7449
  await loadLocalVersion()
7353
7450
  if (!state.token) {
7354
7451
  showView('view-activity')
7452
+ overviewStarting=false
7355
7453
  $('token-desc').textContent = t('token.notSetHint')
7356
7454
  } else {
7357
7455
  // 多服务器: 启动时静默测速一次, 选最快的连接(同源页面也参与比较)
7358
7456
  await selectFastestServer({ silent: true, reconnect: false })
7359
7457
  await maybeWarnAppBehindGateway({ probe: true })
7458
+ overviewStarting=false
7360
7459
  openStreams()
7361
- await refreshAll()
7362
- await refreshHostDescription()
7460
+ await Promise.all([refreshAll(),refreshHostDescription()])
7363
7461
  loadDshControl()
7364
7462
  }
7365
7463
  // 网关从中央 HTTPS 公告源读取并在不可达时回退内置文件。前台每 30 秒检查,
@@ -7383,4 +7481,3 @@ function openPluginPage() {
7383
7481
  valid: connection.valid,
7384
7482
  }, $('plugin-page'))
7385
7483
  }
7386
- document.getElementById('btn-plugin-center')?.addEventListener('click', () => showView('view-plugins'))