dsh-remote-plugin 0.8.0-rc.2 → 0.8.0-rc.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
@@ -103,7 +103,7 @@ const state = {
103
103
  wbArchived: [],
104
104
  wbOpen: false,
105
105
  wbOpenProjects: {},
106
- subagentExpandedSession: ''
106
+ subagentSessions: {}
107
107
  }
108
108
 
109
109
  // Increment on every identity transition, including A -> B -> A and token edits.
@@ -120,7 +120,7 @@ for (const key of ['server', 'token']) {
120
120
  state.sessions = []; state.byId.clear(); state.pendingProjections.clear()
121
121
  state.hostInfo = null
122
122
  if(typeof closeStream==='function'&&typeof streamMeta!=='undefined'){closeStream('mux');closeStream('host')}
123
- state.current = null; state.history = emptyHistory()
123
+ state.current = null; state.history = emptyHistory(); state.subagentSessions = {}; window.DshSubagents?.reset()
124
124
  state.models = { loaded: false, loading: false, groups: [], current: null, failures: [] }
125
125
  state.modelSettings = { status: 'idle', error: '', writable: false, hasDocument: false, providers: [], namespaces: [], credentials: {} }; state.modelEditor = null
126
126
  state.goalEdit = null; state.goalEditContext = null
@@ -377,6 +377,7 @@ async function submitFeedback() {
377
377
  if (message.length > 2000) { toast(t('feedback.tooLong'), 'err'); return }
378
378
  const btn = $('fb-submit')
379
379
  btn.disabled = true
380
+ const diagnostic=globalThis.DshDiagnostics?.start('feedback.submit')
380
381
  try {
381
382
  const base = updateBase()
382
383
  if (!base) throw new Error(t('feedback.networkError'))
@@ -385,12 +386,14 @@ async function submitFeedback() {
385
386
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token },
386
387
  body: JSON.stringify({ type, message, contact, appVersion: state.localVersion, includeDiagnostics, includeCrashLogs })
387
388
  })
389
+ diagnostic?.end({phase:res.ok?'complete':'failed',httpStatus:res.status})
388
390
  let json = {}
389
391
  try { json = await res.json() } catch {}
390
392
  if (res.ok && json.ok) { closeFeedbackModal(); openFeedbackSuccess() }
391
393
  else if (res.status === 429) { toast(json.retryAfter ? t('feedback.rateLimitedAt', { n: json.retryAfter }) : t('feedback.rateLimited'), 'err') }
392
394
  else { toast(t('feedback.submitFailed', { msg: json.error || res.status }), 'err') }
393
- } catch {
395
+ } catch(error) {
396
+ diagnostic?.fail(error)
394
397
  toast(t('feedback.submitFailed', { msg: t('feedback.networkError') }), 'err')
395
398
  } finally {
396
399
  btn.disabled = false
@@ -449,24 +452,24 @@ function apiUrl(path) {
449
452
  let wsTicketPromise = null
450
453
  let wsTicketConnection = null
451
454
  async function getWsTicket() {
452
- const now = Date.now()
453
- if (state.wsTicket.token === state.token && state.wsTicket.server === state.server &&
454
- state.wsTicket.value && state.wsTicket.expiresAt > now + 15000) return state.wsTicket.value
455
+ // Share only an in-flight request. A completed ticket may be exhausted or
456
+ // belong to the gateway instance that just exited.
455
457
  if (wsTicketPromise && wsTicketConnection?.valid()) return wsTicketPromise
456
458
  const connection = captureConnection()
457
459
  const token = state.token
458
460
  const server = state.server
459
461
  const job = (async () => {
460
- if (activeGatewayCapability('wsTicket') === false) throw new Error('ws ticket unsupported')
462
+ if (activeGatewayCapability('wsTicket') === false) throw Object.assign(new Error('ws ticket unsupported'), { unsupported: true })
461
463
  const res = await fetch(apiUrl('/api/ws-ticket'), {
462
464
  method: 'POST',
465
+ signal: AbortSignal.timeout(8000),
463
466
  headers: {
464
467
  authorization: 'Bearer ' + token,
465
468
  'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web',
466
469
  ...clientIdHeaders(),
467
470
  }
468
471
  })
469
- if (!res.ok) throw new Error('ws ticket HTTP ' + res.status)
472
+ if (!res.ok) throw Object.assign(new Error('ws ticket HTTP ' + res.status), { unsupported: [404, 405, 501].includes(res.status) })
470
473
  const data = await res.json()
471
474
  if (!connection.valid()) throw new Error('stale ws ticket')
472
475
  if (!data?.ticket || !Number(data.expiresAt)) throw new Error('invalid ws ticket')
@@ -505,6 +508,8 @@ function bucketTokens(b) {
505
508
  }
506
509
 
507
510
  async function rpc(method, payload = {}, timeoutMs = 45000) {
511
+ const diagnostic=globalThis.DshDiagnostics?.start('rpc',{method,sessionId:payload.sessionId,server:state.server})
512
+ try {
508
513
  const opts = {
509
514
  method: 'POST',
510
515
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() },
@@ -517,17 +522,21 @@ async function rpc(method, payload = {}, timeoutMs = 45000) {
517
522
  const connection = operation ? captureConnection() : null
518
523
  const receipt = operation ? await window.DshOperations.execute({ method, payload, url: apiUrl, headers: opts.headers, valid: () => connection.valid() }) : null
519
524
  const res = receipt ? { status: 200, ok: true, json: async () => receipt } : await fetch(apiUrl('/api/' + method), opts)
525
+ diagnostic?.end({phase:'response',httpStatus:res.status})
520
526
  if (res.status === 401) throw new Error('AUTH')
521
527
  if (!res.ok) throw new Error('HTTP ' + res.status)
522
528
  const full = await res.json()
523
529
  if (!full?.result) throw new Error(t('err.badResponse'))
524
530
  if (!full.result.ok) {
525
531
  const err = full.result.error || {}
526
- const error = new Error(err.message || t('err.dshError'))
532
+ const error = new Error(err.code === 'session/migration-required' ? t('session.migrationRequired') : err.message || t('err.dshError'))
533
+ error.code = err.code
527
534
  error.rpcRejected = true
528
535
  throw error
529
536
  }
537
+ diagnostic?.end({phase:'complete'})
530
538
  return full.result.value
539
+ } catch(error) { diagnostic?.fail(error);throw error }
531
540
  }
532
541
 
533
542
  async function respond(rpcId, value) {
@@ -560,6 +569,11 @@ let hostDescribePromise = null
560
569
  let hostDescribeConnection = null
561
570
  let hostDescribeRetryTimer = null
562
571
  let hostDescribeFailures = 0
572
+ function hostDescriptionText(host) {
573
+ const detail = t('settings.hostDesc', { version: host.version || t('settings.unknown'), cwd: host.cwd || t('settings.unknown'), n: Number.isSafeInteger(host.attachedSessions) ? host.attachedSessions : t('settings.unknown') })
574
+ const health = activeGatewayHealth()
575
+ return health ? detail + ' · ' + t('settings.hostHealth', { status: t(health.upstreamOk ? 'conn.on' : 'conn.off'), http: health.upstreamStatus || '—', mux: health.events?.mux?.connected ? '✓' : '×', host: health.events?.host?.connected ? '✓' : '×', time: health.upstreamCheckedAt ? new Date(health.upstreamCheckedAt).toLocaleTimeString() : '—' }) : detail
576
+ }
563
577
 
564
578
  function scheduleHostDescribeRetry() {
565
579
  if (!state.token || hostDescribeRetryTimer) return
@@ -578,16 +592,21 @@ async function refreshHostDescription({ notify = false } = {}) {
578
592
  hostDescribeConnection = connection
579
593
  const job = (async () => {
580
594
  try {
595
+ if (notify) {
596
+ const base = String(connection.server || location.origin).replace(/\/+$/, '')
597
+ const response = await fetch(base + '/health?probe=fresh', { cache: 'no-store', signal: AbortSignal.timeout(6500) })
598
+ const health = await response.json()
599
+ if (!connection.valid()) return null
600
+ if (response.ok && health?.service === 'dsh-remote') state.gatewayHealth[base] = health
601
+ }
581
602
  const host = await rpc('host.describe', {}, 5000)
582
603
  if (!connection.valid()) return null
583
604
  state.hostInfo = host
584
- const health = activeGatewayHealth()
585
- if (health) health.upstreamReachable = true
586
605
  hostDescribeFailures = 0
587
606
  if (hostDescribeRetryTimer) clearTimeout(hostDescribeRetryTimer)
588
607
  hostDescribeRetryTimer = null
589
608
  const desc = $('host-desc')
590
- if (desc && host) desc.textContent = t('settings.hostDesc', { version: host.version, cwd: host.cwd, n: host.attachedSessions })
609
+ if (desc && host) desc.textContent = hostDescriptionText(host)
591
610
  renderOverview()
592
611
  return host
593
612
  } catch (error) {
@@ -768,8 +787,9 @@ function activeGatewayHealth() {
768
787
 
769
788
  function dshReachable() {
770
789
  const health = activeGatewayHealth()
790
+ if (health && typeof health.upstreamOk === 'boolean') return health.upstreamOk
771
791
  if (health && typeof health.upstreamReachable === 'boolean') return health.upstreamReachable
772
- return !!state.hostInfo
792
+ return !!state.hostInfo && state.hostInfo.metadataOnly !== true
773
793
  }
774
794
 
775
795
  async function selectFastestServer({ silent = false, reconnect = true } = {}) {
@@ -854,6 +874,7 @@ function renderGroupSelect() {
854
874
  const menu = $('group-select-menu')
855
875
  if (!label || !menu) return
856
876
  label.textContent = state.activeGroup
877
+ $('group-select-btn')?.setAttribute('aria-label', t('groups.currentLabel', { group: state.activeGroup }))
857
878
  menu.innerHTML = state.groups.map(g =>
858
879
  `<button type="button" class="group-option ${g === state.activeGroup ? 'current' : ''}" data-group-option="${esc(g)}">${esc(g)}${g === state.activeGroup ? ' ✓' : ''}</button>`).join('')
859
880
  menu.querySelectorAll('[data-group-option]').forEach(b =>
@@ -955,7 +976,7 @@ function renderServers() {
955
976
  const activeManual = state.groupActive[g] || ''
956
977
  return `<div class="srv-group" data-group="${esc(g)}">
957
978
  <div class="srv-group-head">
958
- <button class="srv-group-name" data-group-name="${esc(g)}">${g === state.activeGroup ? '▾' : '▸'} ${esc(g)} <span class="srv-group-count">${list.length}</span></button>
979
+ <button class="srv-group-name" data-group-name="${esc(g)}"><span class="srv-group-label">${g === state.activeGroup ? '▾' : '▸'} ${esc(g)}</span><span class="srv-group-count">${list.length}</span></button>
959
980
  <button class="srv-group-speed mini-btn" data-speed-group="${esc(g)}" title="${t('groups.speedTest')}">⚡</button>
960
981
  <label class="switch small" title="${t('groups.autoSelect')}">
961
982
  <input type="checkbox" data-auto-group="${esc(g)}" ${auto ? 'checked' : ''}>
@@ -966,14 +987,17 @@ function renderServers() {
966
987
  <div class="srv-group-body ${g === state.activeGroup ? '' : 'hidden'}">
967
988
  ${list.map(s => {
968
989
  const ms = state.serverLatency[serverKey(s)]
969
- let badge = `<span class="server-badge">${t('servers.untested')}</span>`
970
990
  const active = s.url === state.server && serverToken(s) === state.token
971
- if (Number.isFinite(ms)) badge = `<span class="server-badge ${active ? 'good' : ''}">${ms}ms${active ? t('servers.current') : ''}</span>`
991
+ // 只显示一条最有用的状态,避免地址被状态文案挤成竖排。
992
+ let badge = `<span class="server-badge">${t('servers.untested')}</span>`
993
+ if (!s.token) badge = `<span class="server-badge bad">${t('servers.tokenMissing')}</span>`
994
+ else if (Number.isFinite(ms)) badge = `<span class="server-badge ${active ? 'good' : ''}">${ms}ms${active ? t('servers.current') : ''}</span>`
972
995
  else if (ms !== undefined) badge = '<span class="server-badge bad">' + t('servers.unreachable') + '</span>'
996
+ else if (active) badge = `<span class="server-badge good">${t('servers.currentOnly')}</span>`
973
997
  const activeInGroup = auto ? active : s.id === activeManual
974
998
  return `<div class="server-row ${activeInGroup ? 'active' : ''}" data-use-server="${esc(s.id)}">
975
- <span class="server-main"><span class="server-note">${esc(serverTitle(s))}</span>${s.note ? `<span class="server-url">${esc(s.url)}</span>` : ''}<span class="server-token-badge">${s.token ? t('servers.tokenSet') : t('servers.tokenMissing')}</span></span>${badge}
976
- <button class="server-edit" data-edit-server="${esc(s.id)}" title="${t('servers.edit')}">✎</button>
999
+ <span class="server-main"><span class="server-note" title="${esc(serverTitle(s))}">${esc(serverTitle(s))}</span>${s.note ? `<span class="server-url">${esc(s.url)}</span>` : ''}</span>${badge}
1000
+ <button class="server-edit" data-edit-server="${esc(s.id)}" title="${t('servers.edit')}" aria-label="${t('servers.edit')}">✎</button>
977
1001
  <button class="server-del" data-del-server="${esc(s.id)}" aria-label="${t('servers.delete')}">✕</button>
978
1002
  </div>`
979
1003
  }).join('') || '<div class="server-empty">' + t('groups.noServer') + '</div>'}
@@ -1031,7 +1055,7 @@ function renderServers() {
1031
1055
  const curGroup = cur ? cur.group : state.activeGroup
1032
1056
  const curMs = cur ? state.serverLatency[serverKey(cur)] : undefined
1033
1057
  $('server-desc').textContent = state.server
1034
- ? t('servers.currentDescGroup', { group: curGroup, url: curNote, ms: Number.isFinite(curMs) ? curMs + 'ms' : '—' })
1058
+ ? t('servers.currentDescGroup', { group: curGroup, url: curNote }) + (Number.isFinite(curMs) ? ' · ' + curMs + 'ms' : '')
1035
1059
  : (CAP?.isNativePlatform?.() ? t('servers.notSet') : t('servers.defaultDesc'))
1036
1060
  updateConn()
1037
1061
  }
@@ -1251,12 +1275,25 @@ function openStreams() {
1251
1275
  function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1252
1276
  if (!state.token) return
1253
1277
  if (ticket === null) {
1254
- const token = state.token, connection=captureConnection()
1278
+ if (streams[kind] && [WebSocket.OPEN, WebSocket.CONNECTING].includes(streams[kind].readyState)) return
1279
+ const connection=captureConnection(), generation=streamMeta[kind].generation
1280
+ const valid=()=>connection.valid() && generation===streamMeta[kind].generation
1255
1281
  void getWsTicket().then((value) => {
1256
- if (connection.valid()) openStream(kind, handler, refreshOnOpen, isRestore, value)
1257
- }).catch(() => {
1282
+ if (valid()) openStream(kind, handler, refreshOnOpen, isRestore, value)
1283
+ }).catch((error) => {
1258
1284
  // 兼容旧网关/插件副本: ticket 接口不可用时临时回退旧 token 握手。
1259
- if (connection.valid()) openStream(kind, handler, refreshOnOpen, isRestore, '')
1285
+ if (!valid()) return
1286
+ if (error.unsupported) openStream(kind, handler, refreshOnOpen, isRestore, '')
1287
+ else {
1288
+ clearStreamRetry(kind)
1289
+ const meta = streamMeta[kind]
1290
+ meta.failures++
1291
+ aggregateStreamFailures()
1292
+ if (state.streamMode !== 'poll' && meta.failures >= 3) { enterPollMode(); return }
1293
+ const delay = Math.round(Math.min(1500 * 2 ** Math.min(meta.attempt++, 6), 60000) * (0.8 + Math.random() * 0.4))
1294
+ meta.retryTimer = setTimeout(() => { meta.retryTimer = null; if (valid() && navigator.onLine) openStream(kind, handler, refreshOnOpen, isRestore) }, delay)
1295
+ setReconnect(delay)
1296
+ }
1260
1297
  })
1261
1298
  return
1262
1299
  }
@@ -1289,6 +1326,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1289
1326
  ws._isRestore = !!isRestore
1290
1327
  ws.onopen = () => {
1291
1328
  if (!streamIsCurrent(kind, ws, generation)) return
1329
+ globalThis.DshDiagnostics?.record('stream.state',{channel:kind,status:'open',attempt:meta.failures})
1292
1330
  state.streamsOk[kind] = true
1293
1331
  markStreamInfo(kind, { status: 'open', lastOpenAt: Date.now(), lastCloseCode: 0, lastCloseReason: '' })
1294
1332
  meta.attempt = 0
@@ -1326,7 +1364,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1326
1364
  handler(full)
1327
1365
  } catch {}
1328
1366
  }
1329
- ws.onclose = () => {
1367
+ ws.onclose = (event) => {
1330
1368
  clearStreamTimers(ws)
1331
1369
  if (!streamIsCurrent(kind, ws, generation)) return
1332
1370
  streams[kind] = null
@@ -1334,9 +1372,10 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1334
1372
  markStreamInfo(kind, {
1335
1373
  status: 'closed',
1336
1374
  lastCloseAt: Date.now(),
1337
- lastCloseCode: Number(ws.code) || 0,
1338
- lastCloseReason: String(ws.reason || ''),
1375
+ lastCloseCode: Number(event.code) || 0,
1376
+ lastCloseReason: String(event.reason || '').slice(0, 200),
1339
1377
  })
1378
+ globalThis.DshDiagnostics?.record('stream.state',{channel:kind,status:'closed',closeCode:Number(event.code)||0,attempt:meta.failures+1})
1340
1379
  meta.failures++
1341
1380
  aggregateStreamFailures()
1342
1381
  updateConn()
@@ -1349,6 +1388,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1349
1388
  const attempt = meta.attempt++
1350
1389
  const baseDelay = Math.min(1500 * Math.pow(2, attempt), 60000)
1351
1390
  const delay = Math.round(baseDelay * (0.8 + Math.random() * 0.4))
1391
+ globalThis.DshDiagnostics?.record('stream.retry',{channel:kind,attempt:meta.attempt,delayMs:delay})
1352
1392
  setReconnect(delay)
1353
1393
  clearStreamRetry(kind)
1354
1394
  meta.retryTimer = setTimeout(() => {
@@ -1361,6 +1401,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1361
1401
 
1362
1402
  /* ---------------- 轮询降级模式 ---------------- */
1363
1403
  function enterPollMode() {
1404
+ globalThis.DshDiagnostics?.record('poll.state',{status:'poll'})
1364
1405
  if (state.streamMode === 'poll') return
1365
1406
  state.streamMode = 'poll'
1366
1407
  state.pollSeq = { mux: 0, host: 0 }
@@ -1531,6 +1572,7 @@ function onMuxFrame(full) {
1531
1572
  if (f.type === 'session/jobs') { state.jobs[f.sessionId] = f.jobs || []; renderJobs(); return }
1532
1573
  if (f.type === 'session/projection') { applyProjection(f.sessionId, f.key, f.value, f.seq); return }
1533
1574
  if (f.type === 'stream/error') { toast(t('stream.error', { msg: f.error?.message || '' }), 'err') }
1575
+ if (f.type === 'session/stream-error' && f.sessionId === state.current) { setSessionRecovery('error', f.error?.code === 'session/migration-required' ? t('session.migrationRequired') : f.error?.message); toast(f.error?.code === 'session/migration-required' ? t('session.migrationRequired') : f.error?.message, 'err') }
1534
1576
  }
1535
1577
  function onHostFrame(full) {
1536
1578
  const f = full.payload
@@ -1727,6 +1769,12 @@ async function refreshSessions() {
1727
1769
  }
1728
1770
  state.sessions = v.items || []
1729
1771
  state.byId = new Map(state.sessions.map(s => [s.sessionId, s]))
1772
+ for (const [id, child] of Object.entries(state.subagentSessions || {})) {
1773
+ const listed = state.byId.get(id)
1774
+ const merged = listed ? { ...child, ...listed, parentSessionId: child.parentSessionId, subagentMode: child.subagentMode, origin: 'subagent' } : child
1775
+ state.byId.set(id, merged)
1776
+ state.subagentSessions[id] = merged
1777
+ }
1730
1778
  applyPendingProjections()
1731
1779
  cacheWrite(CACHE.sessions, state.sessions.slice(0, 80))
1732
1780
  renderSessions()
@@ -1785,9 +1833,15 @@ function hydrateSessionProjections(sessionId, projections) {
1785
1833
  if (!s || !projections || typeof projections !== 'object') return
1786
1834
  const incomingSeq = Number(projections.asOfSeq) || 0
1787
1835
  const current = s.projections || { asOfSeq: 0, values: {} }
1836
+ if (projections.kind === 'cached' && current.kind === 'sequenced') return
1837
+ if (current.kind === 'cached' || projections.kind === 'cached') {
1838
+ s.projections = { ...projections, asOfSeq: incomingSeq, kind: projections.kind || 'sequenced', values: { ...(current.values || {}), ...(projections.values || {}) } }
1839
+ return
1840
+ }
1788
1841
  const currentSeq = Number(current.asOfSeq) || 0
1789
1842
  if (incomingSeq < currentSeq) return
1790
1843
  s.projections = {
1844
+ kind: projections.kind || current.kind || 'sequenced',
1791
1845
  asOfSeq: Math.max(currentSeq, incomingSeq),
1792
1846
  values: { ...(current.values || {}), ...(projections.values || {}) }
1793
1847
  }
@@ -1808,6 +1862,7 @@ function applyProjection(sessionId, key, value, seq) {
1808
1862
  state.pendingProjections.set(sessionId, pending)
1809
1863
  return
1810
1864
  }
1865
+ if (s.projections?.kind === 'cached') s.projections = { kind: 'sequenced', asOfSeq: 0, values: { ...(s.projections.values || {}) } }
1811
1866
  const currentSeq = Number(s.projections?.asOfSeq) || 0
1812
1867
  if (seq && seq < currentSeq) return
1813
1868
  s.projections = s.projections || { asOfSeq: 0, values: {} }
@@ -1853,7 +1908,8 @@ function sessionLabelOf(s) {
1853
1908
  }
1854
1909
  function short(id) { return '…' + String(id).slice(-8) }
1855
1910
  function isTopLevelSession(session) {
1856
- return !!session && !session.parentSessionId && session.origin !== 'subagent'
1911
+ // Ordinary forks also carry parentSessionId; only explicit subagents leave the main list.
1912
+ return !!session && session.origin !== 'subagent'
1857
1913
  }
1858
1914
  // DSH marks sessions created via "new session" but never prompted as blank and hides
1859
1915
  // them in its own UI; keep the same semantics here so they do not occupy the list,
@@ -2316,6 +2372,7 @@ const emptySessionCleanup = new Set()
2316
2372
  async function archiveEmptySessionOnLeave(sessionId, leaving = false) {
2317
2373
  const base = state.server, connection=captureConnection()
2318
2374
  const protectedSession = () => !connection.valid() || state.server !== base || (!leaving && state.current !== sessionId)
2375
+ || !!state.byId.get(sessionId)?.parentSessionId || state.byId.get(sessionId)?.origin === 'subagent'
2319
2376
  || !state.byId.has(sessionId) || state.byId.get(sessionId)?.running
2320
2377
  || state.sessionActivity?.has(sessionId) || state.pendingPrompts?.has(sessionId)
2321
2378
  || (state.queues[sessionId] || []).length > 0
@@ -2336,6 +2393,7 @@ async function archiveEmptySessionOnLeave(sessionId, leaving = false) {
2336
2393
  }
2337
2394
 
2338
2395
  async function openSession(id) {
2396
+ globalThis.DshDiagnostics?.record('session.open',{phase:'start',sessionId:id,server:state.server})
2339
2397
  if (state.current && state.current !== id) void archiveEmptySessionOnLeave(state.current,true)
2340
2398
  state.current = id
2341
2399
  setSessionRecovery('loading')
@@ -2347,12 +2405,19 @@ async function openSession(id) {
2347
2405
  $('btn-archive-session').classList.toggle('hidden', (state.wbArchived || []).includes(id))
2348
2406
  $('session-cards').innerHTML = ''
2349
2407
  renderSessionTitle(); renderSessionSub(); updateCancelBtn(); updateSessionStatus()
2408
+ renderSessionCards()
2350
2409
  $('history').innerHTML = '<div class="empty">' + t('history.loading') + '</div>'
2351
2410
  renderQueue()
2352
2411
  renderSessionPending()
2353
2412
  void refreshCompactionStatus(id)
2354
2413
  getConversationView().reset()
2355
- await restoreCachedHistory()
2414
+ try { const restored=await restoreCachedHistory();globalThis.DshDiagnostics?.record('history.cache',{phase:restored?'hit':'miss',sessionId:id}) } catch(error) {
2415
+ globalThis.DshDiagnostics?.record('history.cache',{phase:'failed',sessionId:id,...globalThis.DshDiagnostics.errorFacts(error)})
2416
+ if(state.current!==id||state.history!==openingHistory||!openingConnection.valid())return
2417
+ // A broken local cache must not prevent fetching the authoritative history.
2418
+ Object.assign(openingHistory,emptyHistory())
2419
+ getConversationView().reset()
2420
+ }
2356
2421
  if(state.current!==id||state.history!==openingHistory||!openingConnection.valid())return
2357
2422
  await loadHistory(true)
2358
2423
  renderSessionCards()
@@ -2366,42 +2431,43 @@ function sessionHasPendingActivity(sessionId, session) {
2366
2431
  || (state.queues[sessionId] || []).some(item => item?.placement !== 'context')
2367
2432
  }
2368
2433
 
2369
- async function shouldDiscardEmptySession(sessionId) {
2434
+ function shouldDiscardEmptySession(sessionId) {
2370
2435
  const session = state.byId.get(sessionId)
2371
2436
  if (!session || sessionHasPendingActivity(sessionId, session)) return false
2372
- const deadline = Date.now() + 3500
2373
- while (state.current === sessionId && state.history.loading && Date.now() < deadline) {
2374
- await new Promise(resolve => setTimeout(resolve, 25))
2375
- }
2376
- if (state.current !== sessionId || sessionHasPendingActivity(sessionId, session)) return false
2377
- return isEmptySessionHistory(state.history)
2437
+ return state.current === sessionId && !state.history.loading && !state.history.renderError
2438
+ && !(state.composerImages || []).length && !$('composer-input')?.value?.trim()
2439
+ && isEmptySessionHistory(state.history)
2378
2440
  }
2379
2441
 
2380
2442
  async function closeSession() {
2381
- if (closeSession.pending) return closeSession.pending
2443
+ globalThis.DshDiagnostics?.record('session.back',{phase:'start',sessionId:state.current,loading:state.history.loading,loaded:state.history.loaded,renderErrors:state.history.renderError?1:0})
2382
2444
  const sessionId = state.current
2383
2445
  if (!sessionId) return
2384
- const task = (async () => {
2385
- const discard = await shouldDiscardEmptySession(sessionId) && await archiveEmptySessionOnLeave(sessionId)
2386
- if (state.current !== sessionId) return
2387
- state.current = null
2388
- renderSessionPending()
2389
- if (discard) removeLocalSessionRecord(sessionId)
2390
- setComposerFullscreen(false)
2391
- clearComposerImages()
2392
- setSessionRecovery('idle')
2393
- $('btn-rename-session').classList.add('hidden')
2394
- $('btn-archive-session').classList.add('hidden')
2395
- state.history = emptyHistory()
2396
- document.body.classList.remove('in-session')
2397
- hideComposerMenu()
2398
- renderSessions()
2399
- renderWorkbench()
2400
- showView('view-home')
2401
- })()
2402
- closeSession.pending = task
2403
- try { await task } finally {
2404
- if (closeSession.pending === task) closeSession.pending = null
2446
+ const parentId = state.byId.get(sessionId)?.parentSessionId
2447
+ if (parentId && parentId !== sessionId) {
2448
+ setComposerFullscreen(false);clearComposerImages();hideComposerMenu()
2449
+ return openSession(parentId)
2450
+ }
2451
+ const connection=captureConnection(),discard=shouldDiscardEmptySession(sessionId)
2452
+ state.current = null
2453
+ state.history = emptyHistory()
2454
+ document.body.classList.remove('in-session')
2455
+ showView('view-home')
2456
+ globalThis.DshDiagnostics?.record('session.back',{phase:'navigate',sessionId})
2457
+ renderSessionPending()
2458
+ setComposerFullscreen(false)
2459
+ clearComposerImages()
2460
+ setSessionRecovery('idle')
2461
+ $('btn-rename-session').classList.add('hidden')
2462
+ $('btn-archive-session').classList.add('hidden')
2463
+ hideComposerMenu()
2464
+ renderSessions()
2465
+ renderWorkbench()
2466
+ // Navigation must never wait for history reads or archive RPCs. A later session
2467
+ // owns its own navigation even while this best-effort cleanup is still pending.
2468
+ if(discard && await archiveEmptySessionOnLeave(sessionId,true) && connection.valid()) {
2469
+ removeLocalSessionRecord(sessionId)
2470
+ renderSessions();renderWorkbench()
2405
2471
  }
2406
2472
  }
2407
2473
 
@@ -2412,13 +2478,24 @@ function bindNativeBack() {
2412
2478
  CAP.Plugins?.App?.addListener?.('backButton', () => {
2413
2479
  if ($('composer-wrap')?.classList.contains('fs')) { setComposerFullscreen(false); return }
2414
2480
  if (customSelectCurrent) { closeCustomSelect(); return }
2481
+ if (groupDrawerOpen()) { closeGroupDrawer(); return }
2482
+ if (typeof window !== 'undefined' && window.DshImagePreview?.isOpen?.()) { window.DshImagePreview.close(); return }
2483
+ const dialog = document.querySelector('dialog[open]')
2484
+ if (dialog) { dialog.close(); return }
2415
2485
  const openModal = [...document.querySelectorAll('.modal')].find(m => !m.classList.contains('hidden'))
2416
2486
  if (openModal) { if (openModal.id === 'modal-notes') closeNotesModal(); else if (openModal.id === 'modal-archive') closeArchiveConfirm(); else if (openModal.id === 'modal-rename') closeRenameSession(); else if (openModal.id === 'modal-app-version-warning') closeAppVersionWarning(false); else if (openModal.id === 'modal-scan-live') closeLiveScan(''); else openModal.classList.add('hidden'); return } // 先关弹窗
2487
+ if (!$('view-settings').classList.contains('hidden')) {
2488
+ if ($('settings-home').classList.contains('hidden')) showSettingsHome()
2489
+ else showView('view-home')
2490
+ return
2491
+ }
2492
+ if (!$('view-plugins').classList.contains('hidden')) { showView('view-settings'); return }
2417
2493
  if (document.body.classList.contains('in-session')) { void closeSession(); return } // 会话页 → 回主页
2418
2494
  if (!$('view-files').classList.contains('hidden')) { // 文件页 → 上级目录 → 主页
2419
2495
  if (state.fs.path && state.fs.initial && state.fs.path !== state.fs.initial) { fsUp(); return }
2420
2496
  showView('view-home'); return
2421
2497
  }
2498
+ if ($('view-home').classList.contains('hidden')) { showView('view-home'); return }
2422
2499
  try { CAP.Plugins?.App?.exitApp?.() } catch {} // 主页再返回 → 退出(与系统一致)
2423
2500
  })
2424
2501
  } catch {}
@@ -2543,7 +2620,9 @@ function applyReasoningStreamEvent(event) {
2543
2620
  }
2544
2621
 
2545
2622
  let reasoningRenderTimer = null
2623
+ function weakStreamTrim() { return !!window.DshNetwork?.streamTrimmed?.() }
2546
2624
  function scheduleReasoningRender() {
2625
+ if (weakStreamTrim()) return
2547
2626
  if (reasoningRenderTimer) return
2548
2627
  reasoningRenderTimer = setTimeout(() => {
2549
2628
  reasoningRenderTimer = null
@@ -2553,10 +2632,11 @@ function scheduleReasoningRender() {
2553
2632
  }
2554
2633
 
2555
2634
  function partialReasoningHtml() {
2635
+ if (weakStreamTrim()) return ''
2556
2636
  return [...state.history.partialReasoning.values()]
2557
2637
  .filter(item => item.text)
2558
2638
  .sort((a, b) => (a.turn ?? 0) - (b.turn ?? 0) || (a.step ?? 0) - (b.step ?? 0) || (a.index ?? 0) - (b.index ?? 0))
2559
- .map(item => `<div class="msg assistant reasoning-live"><div class="role">${esc(t('role.dsh'))}</div><details class="tool" open><summary>${esc(t('block.thinkingLive'))}</summary><div class="tool-text">${esc(truncate(item.text, 12000))}</div></details></div>`)
2639
+ .map(item => window.DshActivity ? window.DshActivity.reasoning({text:item.text,live:true,key:window.DshActivity.reasoningKey(item,item.index,'live-reasoning')}) : `<div class="msg assistant reasoning-live"><div class="role">${esc(t('role.dsh'))}</div><details class="tool" open><summary>${esc(t('block.thinkingLive'))}</summary><div class="tool-text">${esc(truncate(item.text, 12000))}</div></details></div>`)
2560
2640
  .join('')
2561
2641
  }
2562
2642
 
@@ -2571,13 +2651,15 @@ function historyCacheScope() { return CACHE.history }
2571
2651
  function historySource(value) {
2572
2652
  state.history.source=value
2573
2653
  const el=$('history-source')
2574
- 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')
2654
+ if(el)el.textContent=t(({cache:'history.cached',syncing:'history.syncing',synced:'history.synced',saved:'history.saved',offline:'history.offline',saveFailed:'history.cacheFailed',error:'history.renderFailed'})[value]||'history.synced')
2575
2655
  }
2576
2656
  function getConversationView() {
2577
2657
  if(!conversationView)conversationView=new window.DshHistory.HistoryView($('history'),{
2578
2658
  html:entry=>eventHtml(entry, {toolNames:state.history.toolNames}),
2659
+ errorLabel:()=>t('history.renderFailed'),
2579
2660
  older:()=>loadHistory(false),olderLabel:()=>t('history.earlier'),loadingLabel:()=>t('history.loadingEarlier'),live:partialReasoningHtml,
2580
- 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);const latest=$('btn-history-latest');if(latest)latest.textContent=t('history.latest')+(view.unread?' ('+view.unread+')':view.hasPending?' · '+(I18N.lang==='en'?'New content':'有新内容'):'');updateRail(view.domChanged)},
2661
+ retry:()=>loadHistory(true),retryLabel:()=>t('history.retry'),unreadableLabel:()=>I18N.lang==='en'?'No displayable messages on this page. Load earlier records or retry. If DSH reports a migration failure, open the original session in DSH.':'本页历史没有可显示的消息,请加载更早记录或重试。如提示格式迁移失败,请先在 DSH 中打开原会话。',
2662
+ changed:view=>{state.history.renderStart=view.start;state.history.renderEnd=view.end;const latest=$('btn-history-latest');if(latest){latest.classList.toggle('hidden',view.atBottom&&view.unread===0&&!state.history.tailEvicted);latest.textContent=t('history.latest')+(view.unread?' ('+view.unread+')':view.hasPending?' · '+(I18N.lang==='en'?'New content':'有新内容'):'')}updateRail(view.domChanged)},
2581
2663
  scrolled:()=>{updateRail()}
2582
2664
  })
2583
2665
  return conversationView
@@ -2617,47 +2699,70 @@ function trimVisible(direction='tail') {
2617
2699
  async function loadHistory(reset = true) {
2618
2700
  const connection=captureConnection(),id=state.current,history=state.history
2619
2701
  if(!id||history.loading||(!reset&&Date.now()<(history.retryAfter||0)))return
2702
+ const diagnostic=globalThis.DshDiagnostics?.start('history.load',{sessionId:id,server:state.server,reset,cached:!!history.cached,count:history.visible.length})
2620
2703
  const reasoningVersion=history.reasoningVersion||0,hadContent=history.visible.length>0
2621
2704
  history.loading=true
2622
2705
  if(reset){if(hadContent)historySource('syncing');else setSessionRecovery('loading')}
2623
2706
  const network=window.DshNetwork?.profile() || {historyPageSize:60,readTimeout:45000}
2624
2707
  const payload={sessionId:id,maxMessages:network.historyPageSize}
2708
+ const child=state.subagentSessions?.[id] || state.byId.get(id)
2709
+ if(child?.origin==='subagent' && child.parentSessionId) Object.assign(payload,{parentSessionId:child.parentSessionId,subagentMode:child.subagentMode || 'unknown'})
2625
2710
  if(!reset&&Number.isFinite(history.minSeq))payload.beforeSeq=history.minSeq
2626
2711
  getConversationView().more.disabled=true
2627
2712
  getConversationView().more.textContent=getConversationView().options.loadingLabel()
2628
2713
  let v
2629
- try{v=await rpc('session.history',payload,network.readTimeout)}catch(error){
2630
- if(!connection.valid()||state.current!==id||state.history!==history)return
2714
+ // Contain preparation and final DOM failures as well as network errors. Reset
2715
+ // the view before replacing its DOM so an identical retry cannot reuse stale nodes.
2716
+ const failLoad = (error,renderFailure=false) => {
2717
+ diagnostic?.fail(error)
2631
2718
  history.loading=false;history.retryAfter=Date.now()+1500
2632
2719
  if(error.message==='AUTH'){authFailure();return}
2633
- if(hadContent){historySource('offline');setSessionRecovery('cached',error.message);renderHistory(false,'fixed');return}
2720
+ if(hadContent&&!renderFailure){try{renderHistory(false,'fixed');history.renderError=!!getConversationView().renderErrors;historySource(history.renderError?'error':'offline');setSessionRecovery(history.renderError?'error':'cached',error.message);return}catch{}}
2721
+ history.renderError=true;historySource('error')
2634
2722
  setSessionRecovery('error',error.message)
2723
+ getConversationView().reset?.()
2635
2724
  $('history').innerHTML='<div class="history-empty">'+esc(error.message)+'</div>'
2636
2725
  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)
2726
+ }
2727
+ try{v=await rpc('session.history',payload,network.readTimeout);globalThis.DshDiagnostics?.record('history.load',{phase:'response',traceId:diagnostic?.traceId,sessionId:id,rawCount:Array.isArray(v?.events)?v.events.length:0})}catch(error){
2728
+ if(!connection.valid()||state.current!==id||state.history!==history)return
2729
+ failLoad(error)
2637
2730
  return
2638
2731
  }
2639
2732
  if(!connection.valid()||state.current!==id||state.history!==history)return
2640
- const liveReasoning=(history.reasoningVersion||0)!==reasoningVersion?new Map(history.partialReasoning):null
2641
- hydrateSessionProjections(id,v.projections);history.loaded=true
2642
- const incoming=v.events||[],prepared=[]
2643
- for (const entry of incoming) {
2644
- const ev=entry?.event
2645
- applyReasoningStreamEvent(ev)
2646
- if(ev?.type==='turn/start'||ev?.type==='turn/end')noteSessionTurnTime(id,ev)
2647
- if(ev?.seq==null||!shouldShowEvent(ev.type,ev))continue
2648
- prepared.push({seq:ev.seq,event:ev,view:entry.view})
2649
- }
2650
- const rawSeqs=incoming.map(entry=>entry?.event?.seq).filter(Number.isFinite),floor=rawSeqs.length?Math.min(...rawSeqs):Infinity
2651
- 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}
2652
- else{history.visible=window.DshHistory.reconcile(history.visible,prepared,floor,true,payload.beforeSeq);history.minSeq=Math.min(history.minSeq,floor)}
2653
- history.seqs=new Set(history.visible.map(entry=>entry.seq));history.headEvicted=false;trimVisible(reset?'tail':'older')
2654
- if(liveReasoning)history.partialReasoning=liveReasoning;else applyReasoningBaseline(v.partialReasoning)
2655
- history.hasMore=(!!v.hasMore||(reset&&history.headEvicted)) && rawSeqs.length>0 && (reset || floor<payload.beforeSeq)
2656
- history.loading=false;history.cached=false;historySource('synced');setSessionRecovery('ready')
2657
- renderSessionTitle();renderSessionSub();renderSessionCards()
2658
- renderHistory(!hadContent,reset?'fixed':'keep')
2659
- $('history-hint').textContent=t('history.count',{n:history.visible.length})
2660
- scheduleHistoryCacheSave()
2733
+ let liveReasoning, rawSeqs, floor
2734
+ try {
2735
+ liveReasoning=(history.reasoningVersion||0)!==reasoningVersion?new Map(history.partialReasoning):null
2736
+ hydrateSessionProjections(id,v.projections);history.loaded=true
2737
+ const incoming=v.events||[],prepared=[]
2738
+ for (const entry of incoming) {
2739
+ const ev=entry?.event
2740
+ applyReasoningStreamEvent(ev)
2741
+ if(ev?.type==='turn/start'||ev?.type==='turn/end')noteSessionTurnTime(id,ev)
2742
+ if(ev?.seq==null||!shouldShowEvent(ev.type,ev))continue
2743
+ prepared.push({seq:ev.seq,event:ev,view:entry.view})
2744
+ }
2745
+ rawSeqs=incoming.map(entry=>entry?.event?.seq).filter(Number.isFinite);floor=rawSeqs.length?Math.min(...rawSeqs):Infinity
2746
+ 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}
2747
+ else{history.visible=window.DshHistory.reconcile(history.visible,prepared,floor,true,payload.beforeSeq);history.minSeq=Math.min(history.minSeq,floor)}
2748
+ history.seqs=new Set(history.visible.map(entry=>entry.seq));history.headEvicted=false;trimVisible(reset?'tail':'older')
2749
+ if(liveReasoning)history.partialReasoning=liveReasoning;else applyReasoningBaseline(v.partialReasoning)
2750
+ history.hasMore=(!!v.hasMore||(reset&&history.headEvicted)) && rawSeqs.length>0 && (reset || floor<payload.beforeSeq)
2751
+ } catch (error) {
2752
+ failLoad(error)
2753
+ return
2754
+ }
2755
+ try {
2756
+ history.loading=false;history.cached=false
2757
+ renderSessionTitle();renderSessionSub();renderSessionCards()
2758
+ globalThis.DshDiagnostics?.record('history.render',{phase:'start',traceId:diagnostic?.traceId,sessionId:id,count:history.visible.length})
2759
+ renderHistory(!hadContent,reset?'fixed':'keep')
2760
+ history.renderError=!!getConversationView().renderErrors
2761
+ historySource(history.renderError?'error':'synced');setSessionRecovery(history.renderError?'error':'ready')
2762
+ $('history-hint').textContent=t('history.count',{n:history.visible.filter(entry=>!['turn/start','turn/end'].includes(entry.event?.type)).length})
2763
+ diagnostic?.end({phase:history.renderError?'failed':'rendered',count:history.visible.length,renderedCount:getConversationView().end-getConversationView().start,renderErrors:getConversationView().renderErrors||0})
2764
+ if(!history.renderError)scheduleHistoryCacheSave()
2765
+ } catch(error) { failLoad(error,true) }
2661
2766
  }
2662
2767
 
2663
2768
  function insertLiveEvent(event) {
@@ -2681,6 +2786,19 @@ function insertLiveEvent(event) {
2681
2786
 
2682
2787
  function isToolEvent(type) { return type === 'tool/call' || type === 'tool/result' }
2683
2788
 
2789
+ /** One collapsed row for a turn's tools and reasoning, matching the desktop conversation rhythm. */
2790
+ function activityGroupHtml(group, ctx) {
2791
+ const items = group.items || []
2792
+ if (!items.length) return ''
2793
+ const tools = items.filter(item => item.kind === 'tool').map(item => item.entry)
2794
+ const running = !!group.running
2795
+ const failed = tools.some(entry => entry.view?.toolActivity?.error || entry.event?.data?.error)
2796
+ const body = items.map(item => item.kind === 'reasoning'
2797
+ ? window.DshActivity.reasoning({ text: item.text, key: item.key })
2798
+ : eventHtml(item.entry, ctx)).join('')
2799
+ return `<details class="chat-activity-group${failed ? ' is-error' : ''}${running ? ' is-running' : ''}" data-activity-key="activity-group:${items[0]?.seq ?? ''}"><summary><span class="activity-group-title">${esc(t('activity.group', { n: items.length }))}</span>${running ? `<span class="activity-group-live"><i aria-hidden="true"></i>${esc(t('activity.groupRunning'))}</span>` : ''}<span class="activity-chevron" aria-hidden="true"></span></summary><div class="activity-group-body">${body}</div></details>`
2800
+ }
2801
+
2684
2802
  function filteredEntries() {
2685
2803
  const showTools = LS.get('showTools', '1') !== '0'
2686
2804
  const f = state.history.visible.filter(e => showTools || !isToolEvent(e.event?.type))
@@ -2688,13 +2806,60 @@ function filteredEntries() {
2688
2806
  return f
2689
2807
  }
2690
2808
 
2809
+ function canForkTurnResult() {
2810
+ const session = state.byId.get(state.current)
2811
+ return !!session && session.origin !== 'subagent' && session.formatStatus !== 'migration-required' && activeGatewayCapability('operations') === true
2812
+ }
2813
+ function bindTurnResultActions() {
2814
+ window.DshTurnResults.bind($('history'), {
2815
+ capture: () => {
2816
+ const connection = captureConnection(), sessionId = state.current, history = state.history
2817
+ return { sessionId, entries: history.visible, key: JSON.stringify([connection.server, connection.token]), canFork: canForkTurnResult(),
2818
+ valid: () => connection.valid() && state.current === sessionId && state.history === history }
2819
+ },
2820
+ copy: copyText,
2821
+ fork: payload => rpc('session.fork', payload),
2822
+ open: async (id, context) => {
2823
+ const parent = state.byId.get(context.sessionId)
2824
+ try { await refreshSessions() } catch {} // A successful fork remains usable if the roster refresh fails.
2825
+ if (!context.valid()) return
2826
+ if (!state.byId.has(id)) {
2827
+ const branch = { ...parent, sessionId: id, parentSessionId: context.sessionId, origin: 'fork', running: false, blank: false }
2828
+ state.byId.set(id, branch)
2829
+ state.sessions.unshift(branch)
2830
+ renderSessions()
2831
+ }
2832
+ await openSession(id)
2833
+ }
2834
+ })
2835
+ }
2836
+
2691
2837
  function renderHistory(reset=false,mode='auto') {
2692
2838
  const filtered=filteredEntries(),toolNames=new Map()
2693
2839
  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)}
2694
2840
  state.history.toolNames=toolNames
2695
- $('history-hint').textContent=t('history.count',{n:state.history.visible.length})
2696
- getConversationView().set(filtered,{reset,follow:mode==='bottom',live:partialReasoningHtml(),hasMore:state.history.hasMore,loading:state.history.loading,emptyLabel:t('history.empty')})
2697
- }
2841
+ $('history-hint').textContent=t('history.count',{n:state.history.visible.filter(entry=>!['turn/start','turn/end'].includes(entry.event?.type)).length})
2842
+ let prepared=window.DshActivity?.prepare(filtered)||filtered
2843
+ // 弱网精简:尚未返回的调用在完成前不展示,只留已完成的消息与工具结果。
2844
+ if(weakStreamTrim())prepared=prepared.filter(entry=>entry.event?.type!=='tool/call'||entry.view?.toolActivity)
2845
+ // DSH 0.2.1 also embeds tool blocks in messages; the separated events own the grouped rows.
2846
+ state.history.suppressBlockTools = state.history.visible.some(entry => entry.event?.type === 'tool/call')
2847
+ if(window.DshActivity?.group)prepared=window.DshActivity.group(prepared)
2848
+ // Running is a property of the session's current turn, not of an unpaired call:
2849
+ // a finished turn may keep an unmatched call after an interrupt, and the model may be
2850
+ // thinking between tools while the last group is still the active one.
2851
+ const sessionRunning = !!state.byId.get(state.current)?.running
2852
+ const groups = prepared.filter(entry => entry.view?.activityGroup)
2853
+ const activeGroup = groups.at(-1)
2854
+ if (activeGroup) activeGroup.view.activityGroup.running = sessionRunning
2855
+ if (window.DshTurnResults) {
2856
+ prepared = window.DshTurnResults.decorate(prepared, state.history.visible, { sessionId: state.current, canFork: canForkTurnResult() })
2857
+ bindTurnResultActions()
2858
+ }
2859
+ getConversationView().set(prepared,{reset,follow:mode==='bottom',live:partialReasoningHtml(),hasMore:state.history.hasMore,loading:state.history.loading,emptyLabel:t('history.empty')})
2860
+ window.DshImagePreview?.hydrate?.($('history'))
2861
+ }
2862
+ window.applyStreamPreference=()=>{if(state.current)renderHistory(false,'auto')}
2698
2863
 
2699
2864
  /* 右侧导航条: 用户发言节点 + 拖动快速定位 */
2700
2865
  let historyRailLayout=null
@@ -2749,6 +2914,7 @@ function bindRail() {
2749
2914
 
2750
2915
  /* 事件 → HTML */
2751
2916
  const INTERESTING_EVENTS = new Set([
2917
+ 'turn/start', 'turn/end',
2752
2918
  'user/message', 'assistant/message',
2753
2919
  'tool/call', 'tool/result',
2754
2920
  'agent/status',
@@ -2789,7 +2955,13 @@ function eventHtml(entry, ctx = {}) {
2789
2955
  const ev = entry.event || {}
2790
2956
  const data = ev.data || {}
2791
2957
  const type = ev.type || 'event'
2958
+ if (entry.view?.turnResult) return window.DshTurnResults.html(entry.view.turnResult)
2959
+ // Boundary markers are filtered out before they reach history.visible; this guard keeps
2960
+ // the renderer honest if one is ever re-admitted un-decorated.
2961
+ if (type === 'turn/start' || type === 'turn/end') return ''
2962
+ if (entry.view?.activityGroup) return activityGroupHtml(entry.view.activityGroup, ctx)
2792
2963
  if (!shouldShowEvent(type, ev)) return ''
2964
+ if (window.DshActivity && isToolEvent(type)) return window.DshActivity.toolEvent(entry)
2793
2965
  let inner = ''
2794
2966
 
2795
2967
  if (type === 'user/message' || type === 'assistant/message') {
@@ -2802,7 +2974,11 @@ function eventHtml(entry, ctx = {}) {
2802
2974
  } else if (type === 'user/message' && !isHumanUserMessage(ev)) {
2803
2975
  return ''
2804
2976
  } else {
2805
- inner = `<div class="msg ${esc(role)}" data-seq="${seq}"><div class="role">${esc(role === 'user' ? t('role.me') : t('role.dsh'))}</div>${blocks.map(blockHtml).join('')}</div>`
2977
+ const body = blocks.map((block,index)=>blockHtml(block,index,{...data,seq,suppressBlockTools:state.history.suppressBlockTools})).join('')
2978
+ // Inline tool blocks duplicate the separated tool events; when those events exist the
2979
+ // calls live in the activity group, so an assistant message with nothing else disappears.
2980
+ if (!body) return ''
2981
+ inner = `<div class="msg ${esc(role)}" data-seq="${seq}"><div class="role">${esc(role === 'user' ? t('role.me') : t('role.dsh'))}</div>${body}</div>`
2806
2982
  }
2807
2983
  } else if (type === 'tool/call') {
2808
2984
  const name = data.name || data.toolName || t('tool.default')
@@ -2826,13 +3002,21 @@ function eventHtml(entry, ctx = {}) {
2826
3002
  return inner
2827
3003
  }
2828
3004
 
2829
- function blockHtml(b) {
3005
+ function blockHtml(b,index=0,context={}) {
2830
3006
  if (!b || typeof b !== 'object') return `<p>${esc(String(b))}</p>`
2831
- if ((b.type === 'tool-call' || b.type === 'tool-result') && LS.get('showTools', '1') === '0') return ''
3007
+ if ((b.type === 'tool-call' || b.type === 'tool-result') && (context.suppressBlockTools || LS.get('showTools', '1') === '0')) return ''
3008
+ if (typeof window !== 'undefined' && window.DshActivity) {
3009
+ const key='block:'+context.seq+':'+index
3010
+ if (b.type==='thinking'||b.type==='reasoning') return window.DshActivity.reasoning({text:b.text??b.content??'',key:window.DshActivity.reasoningKey(context,index,key)})
3011
+ if (b.type==='tool-call'||b.type==='tool-result') return window.DshActivity.tool({key,name:b.name||b.toolName,...(b.type==='tool-call'?{args:b.arguments??b.args??b.input}:{result:b.result??b.output??b.content??b,error:!!(b.error||b.ok===false||b.isError)})})
3012
+ }
2832
3013
  switch (b.type) {
2833
- case 'text': return `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '', { fileLinks: true }) : esc(b.text ?? '')}</div>`
3014
+ case 'text': return `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '', { fileLinks: true, imageLabel: t('block.image') }) : esc(b.text ?? '')}</div>`
2834
3015
  case 'file': if (typeof window !== 'undefined' && window.DshChatFiles) return window.DshChatFiles.render(b); return `<div class="tool">📎 ${esc(b.attachment?.name || b.name || 'file')} <small>${esc(b.attachment?.bytes ?? b.bytes ?? '')} bytes</small></div>`
2835
- case 'image': return `<img alt="${t('block.image')}" src="data:${esc(b.mediaType || 'image/png')};base64,${esc(b.data || '')}">`
3016
+ case 'image': {
3017
+ const alt = b.name || b.filename || t('block.image')
3018
+ return `<button type="button" class="chat-image" data-chat-image aria-label="${esc(t('block.image'))}"><img alt="${esc(alt)}" src="data:${esc(b.mediaType || 'image/png')};base64,${esc(b.data || '')}" draggable="false"></button>`
3019
+ }
2836
3020
  case 'thinking':
2837
3021
  case 'reasoning':
2838
3022
  return `<details class="tool"><summary>${t('block.thinking')}</summary><div class="tool-text">${esc(truncate(String(b.text ?? b.content ?? safeJson(b)), 6000))}</div></details>`
@@ -2872,11 +3056,29 @@ function statsHtml(s) {
2872
3056
  }
2873
3057
 
2874
3058
  let sessionSubagentsJob = null
3059
+ function rememberSubagent(entry, parentId) {
3060
+ const childId = entry.id
3061
+ const child = state.byId.get(childId) || { sessionId: childId, cwd: state.byId.get(parentId)?.cwd || '' }
3062
+ Object.assign(child, { parentSessionId: parentId, origin: 'subagent', subagentMode: entry.mode || child.subagentMode || 'unknown' })
3063
+ if (entry.label && !child.projections?.values?.title) {
3064
+ child.projections ||= { values: {} }
3065
+ child.projections.values ||= {}
3066
+ child.projections.values.title = entry.label
3067
+ }
3068
+ state.byId.set(childId, child)
3069
+ state.subagentSessions ||= {}
3070
+ state.subagentSessions[childId] = child
3071
+ }
3072
+ async function openSubagentSession(childId, parentId, entry = {}, rootId = parentId) {
3073
+ if (!childId || childId === parentId || state.current !== rootId) return
3074
+ rememberSubagent({ ...entry, id: childId }, parentId)
3075
+ await openSession(childId)
3076
+ }
2875
3077
  async function loadSessionSubagents(sessionId) {
2876
3078
  if (sessionSubagentsJob?.sessionId === sessionId && sessionSubagentsJob.connection.valid()) return sessionSubagentsJob.promise
2877
3079
  const connection = captureConnection(), job = { sessionId, connection }
2878
3080
  job.promise = (async () => {
2879
- const value = await safeRpc('subagent.list', { parentSessionId: sessionId }, '')
3081
+ const value = await rpc('subagent.list', { parentSessionId: sessionId })
2880
3082
  return connection.valid() ? value : null
2881
3083
  })()
2882
3084
  sessionSubagentsJob = job
@@ -2937,30 +3139,15 @@ async function renderSessionCards() {
2937
3139
  }))
2938
3140
 
2939
3141
  // 子代理
2940
- const sub = await loadSessionSubagents(sessionId)
2941
3142
  if (!connection.valid() || renderGeneration !== sessionCardsRenderGeneration || state.current !== sessionId) return
2942
- if (sub?.entries?.length) {
2943
- const expanded = state.subagentExpandedSession === sessionId
2944
- const toggleLabel = expanded ? t('subagent.collapse') : t('subagent.expand')
2945
- const rows = sub.entries.map(e => {
2946
- if (e.kind === 'diagnostic') return `<div class="card-row"><span class="k">${t('subagent.diagnostic')}</span><span class="v">${esc(e.reason)}</span></div>`
2947
- const label = e.label || short(e.id)
2948
- const running = e.activity === 'running'
2949
- return `<div class="card-row"><span class="k">${running ? '▶ ' : ''}${esc(label)}</span><span class="v">${esc(e.mode)} ${running ? t('subagent.running') : ''}${e.mode === 'continuable' && running ? ` <button class="mini-btn" data-sub-interrupt="${esc(e.id)}">${t('subagent.interrupt')}</button>` : ''}</span></div>`
2950
- }).join('')
2951
- const subagentClosedIcon = 'M7 10l5 5 5-5'
2952
- const subagentOpenIcon = 'M7 14l5-5 5 5'
2953
- const subagentIcon = expanded ? subagentOpenIcon : subagentClosedIcon
2954
- box.insertAdjacentHTML('beforeend', `<div class="card subagent-card"><button type="button" class="subagent-toggle" data-subagent-toggle aria-expanded="${expanded}" aria-label="${esc(toggleLabel)}" title="${esc(toggleLabel)}"><span class="card-title">${esc(t('subagent.count', { n: sub.entries.length }))}</span><span class="subagent-toggle-icon" aria-hidden="true"><morph-icon data-morph-state="${expanded ? 'open' : 'closed'}" data-morph-closed="${subagentClosedIcon}" data-morph-open="${subagentOpenIcon}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${subagentIcon}"/></svg></morph-icon></span></button><div class="subagent-list${expanded ? '' : ' hidden'}">${rows}</div></div>`)
2955
- box.querySelector('[data-subagent-toggle]')?.addEventListener('click', () => {
2956
- const icon = box.querySelector('[data-subagent-toggle] morph-icon')
2957
- if (icon) icon.setAttribute('data-morph-state', expanded ? 'closed' : 'open')
2958
- state.subagentExpandedSession = expanded ? '' : sessionId
2959
- setTimeout(() => renderSessionCards(), 240)
2960
- })
2961
- box.querySelectorAll('[data-sub-interrupt]').forEach(btn =>
2962
- btn.addEventListener('click', () => interruptSubagent(btn.dataset.subInterrupt)))
2963
- }
3143
+ window.DshSubagents?.configure($('btn-subagents'), {
3144
+ sessionId, title: titleOf(s), activity: s.running === true ? 'running' : s.running === false ? 'inactive' : 'unknown', parentId: s.origin === 'subagent' ? s.parentSessionId : null,
3145
+ valid: () => connection.valid() && state.current === sessionId,
3146
+ read: loadSessionSubagents, remember: rememberSubagent,
3147
+ onShow: () => conversationView?.pause(), onClose: () => conversationView?.resume(),
3148
+ open: (entry, parentId) => openSubagentSession(entry.id, parentId, entry, sessionId),
3149
+ interrupt: interruptSubagent,
3150
+ })
2964
3151
  }
2965
3152
 
2966
3153
  function setGoalPhaseLocal(phase) {
@@ -2994,10 +3181,11 @@ async function goalAction(kind) {
2994
3181
  scheduleRefresh()
2995
3182
  }
2996
3183
 
2997
- async function interruptSubagent(childId) {
3184
+ async function interruptSubagent(childId, parentId = state.current) {
3185
+ const connection = captureConnection(), rootId = state.current
2998
3186
  if (!confirm(t('subagent.confirmInterrupt'))) return
2999
- const result = await safeRpc('subagent.interrupt', { parentSessionId: state.current, childSessionId: childId, mode: 'continuable' }, t('subagent.interruptFailed'))
3000
- if (result == null) return
3187
+ const result = await safeRpc('subagent.interrupt', { parentSessionId: parentId, childSessionId: childId, mode: 'continuable' }, t('subagent.interruptFailed'))
3188
+ if (result == null || !connection.valid() || state.current !== rootId) return
3001
3189
  toast(t('subagent.interruptSubmitted'), 'ok')
3002
3190
  setTimeout(renderSessionCards, 600)
3003
3191
  }
@@ -3320,6 +3508,7 @@ function bindComposerSend(button) {
3320
3508
  }
3321
3509
 
3322
3510
  async function sendSessionContent(text, images, requestedMode = 'queue') {
3511
+ if (state.byId.get(state.current)?.origin === 'subagent') { toast('子代理记录为只读 / Subagent records are read only'); return false }
3323
3512
  const clean = String(text || '').trim()
3324
3513
  if ((!clean && !images.length) || !state.current || composerSending) return false
3325
3514
  const sessionId = state.current
@@ -3752,15 +3941,15 @@ async function probeOverviewLinks(signal) {
3752
3941
  let timer
3753
3942
  const controller=new AbortController(),cancel=()=>controller.abort()
3754
3943
  signal.addEventListener('abort',cancel,{once:true});if(signal.aborted)controller.abort()
3755
- timer=setTimeout(cancel,4000)
3756
- const healthRequest=fetch(base+'/health?probe=live&t='+Date.now(),{signal:controller.signal,cache:'no-store'}).then(async response=>{
3944
+ timer=setTimeout(cancel,6500)
3945
+ const healthRequest=fetch(base+'/health?probe=fresh&t='+Date.now(),{signal:controller.signal,cache:'no-store'}).then(async response=>{
3757
3946
  if(!response.ok)throw Error('health')
3758
3947
  const health=await response.json();if(health?.ok!==true)throw Error('health')
3759
3948
  return health
3760
3949
  }).catch(()=>null).finally(()=>{clearTimeout(timer);signal.removeEventListener('abort',cancel)})
3761
3950
  const [health,host]=await Promise.all([healthRequest,refreshHostDescription()])
3762
3951
  if(!connection.valid()||signal.aborted)throw Error('stale check')
3763
- if(health){if(host)health.upstreamReachable=true;state.gatewayHealth[base]=health}
3952
+ if(health){state.gatewayHealth[base]=health}
3764
3953
  else delete state.gatewayHealth[base]
3765
3954
  return {gateway:!!health}
3766
3955
  }
@@ -4075,7 +4264,7 @@ function renderQueue() {
4075
4264
  updateCancelBtn()
4076
4265
  updateSessionStatus()
4077
4266
  // 队列数量在会话列表已显示; 详情页不重复大 UI
4078
- $('history-hint').textContent = items.length ? t('history.queueAndCount', { q: items.length, n: state.history.visible.length }) : t('history.countOnly', { n: state.history.visible.length })
4267
+ $('history-hint').textContent = items.length ? t('history.queueAndCount', { q: items.length, n: state.history.visible.filter(entry=>!['turn/start','turn/end'].includes(entry.event?.type)).length }) : t('history.countOnly', { n: state.history.visible.filter(entry=>!['turn/start','turn/end'].includes(entry.event?.type)).length })
4079
4268
  renderSessions()
4080
4269
  }
4081
4270
 
@@ -4278,6 +4467,18 @@ function fsApiUrl(sub, params = {}) {
4278
4467
  return u.href
4279
4468
  }
4280
4469
 
4470
+ /** 对话里 Markdown 图片的本地路径:相对路径按当前会话工作区解析,读取走 /fs/file。 */
4471
+ function chatImageRequest(pathValue) {
4472
+ const value = String(pathValue || '').trim()
4473
+ if (!value) return null
4474
+ let target = value
4475
+ if (!/^(?:[A-Za-z]:[\\/]|\\\\|\/|~[\\/])/.test(value)) {
4476
+ const root = state.byId.get(state.current)?.cwd || ''
4477
+ if (root) target = root.replace(/[\\/]+$/, '') + (root.includes('\\') ? '\\' : '/') + value.replace(/^\.?[\\/]+/, '')
4478
+ }
4479
+ return { url: fsApiUrl('/file', { path: target }), headers: fsHeaders() }
4480
+ }
4481
+
4281
4482
  function fsAuthError(status) {
4282
4483
  if (status === 401) authFailure()
4283
4484
  }
@@ -4933,7 +5134,7 @@ function announcementVoteKey(announcementId, pollId) {
4933
5134
  }
4934
5135
  function storeAnnouncementVote(announcementId, pollId, optionId) {
4935
5136
  const votes = readAnnouncementVotes()
4936
- votes[announcementVoteKey(announcementId, pollId)] = { optionId, votedAt: Date.now() }
5137
+ votes[announcementVoteKey(announcementId, pollId)] = { ...(optionId ? { optionId } : { submitted: true }), votedAt: Date.now() }
4937
5138
  const keys = Object.keys(votes)
4938
5139
  if (keys.length > 100) {
4939
5140
  keys.sort((a, b) => Number(votes[a]?.votedAt || 0) - Number(votes[b]?.votedAt || 0))
@@ -4945,6 +5146,9 @@ function storeAnnouncementVote(announcementId, pollId, optionId) {
4945
5146
  function announcementVote(item) {
4946
5147
  if (!item?.poll?.id) return null
4947
5148
  const saved = readAnnouncementVotes()[announcementVoteKey(item.id, item.poll.id)]
5149
+ // `submitted` is only ever written by the form path (storeAnnouncementVote with no
5150
+ // optionId), so it already implies a non-legacy poll.
5151
+ if (saved?.submitted) return { ...saved, option: { label: I18N.lang === 'en' ? 'Submitted' : '已提交' } }
4948
5152
  if (!saved?.optionId) return null
4949
5153
  const option = item.poll.options.find(entry => entry.id === saved.optionId)
4950
5154
  return option ? { ...saved, option } : null
@@ -5026,6 +5230,7 @@ function announcementVersionMatch(item) {
5026
5230
  return true
5027
5231
  }
5028
5232
  function normalizeAnnouncementPoll(value, announcementId) {
5233
+ if (window.DshAnnouncementForms) return window.DshAnnouncementForms.normalize(value, announcementId)
5029
5234
  if (!value || typeof value !== 'object') return null
5030
5235
  const id = String(value.id || announcementId || '').trim().slice(0, 120)
5031
5236
  const question = String(value.question || '').trim().slice(0, 300)
@@ -5075,7 +5280,10 @@ function renderAnnouncementPoll(item) {
5075
5280
  if (!poll) return
5076
5281
  const vote = announcementVote(item)
5077
5282
  $('announcement-poll-question').textContent = poll.question
5078
- $('announcement-poll-options').innerHTML = poll.options.map(option => `
5283
+ const forms = window.DshAnnouncementForms
5284
+ $('announcement-poll-options').innerHTML = poll.legacy === false && forms
5285
+ ? forms.render(poll, state.announcementDrafts?.[announcementVoteKey(item.id, poll.id)] || [], !!vote, I18N.lang === 'en')
5286
+ : poll.options.map(option => `
5079
5287
  <label class="announcement-poll-option">
5080
5288
  <input type="radio" name="announcement-poll-option" value="${esc(option.id)}"${vote?.optionId === option.id ? ' checked' : ''}${vote ? ' disabled' : ''}>
5081
5289
  <span><strong>${esc(option.label)}</strong>${option.description ? `<small>${esc(option.description)}</small>` : ''}</span>
@@ -5085,7 +5293,8 @@ function renderAnnouncementPoll(item) {
5085
5293
  status.classList.toggle('hidden', !vote)
5086
5294
  const submit = $('announcement-poll-submit')
5087
5295
  submit.classList.toggle('hidden', !!vote)
5088
- submit.disabled = true
5296
+ submit.disabled = !!vote || !!state.announcementSubmitting
5297
+ if (poll.legacy !== false) submit.disabled = !document.querySelector('input[name="announcement-poll-option"]:checked') || !!state.announcementSubmitting
5089
5298
  }
5090
5299
  function renderAnnouncementPagination() {
5091
5300
  const total = state.announcementItems.length
@@ -5133,19 +5342,22 @@ function showAnnouncementAt(index) {
5133
5342
  async function submitAnnouncementVote() {
5134
5343
  const item = state.announcement
5135
5344
  const poll = item?.poll
5345
+ if (!poll || state.announcementSubmitting) return
5346
+ const forms = window.DshAnnouncementForms
5136
5347
  const optionId = document.querySelector('input[name="announcement-poll-option"]:checked')?.value || ''
5137
- const option = poll?.options.find(entry => entry.id === optionId)
5138
- if (!poll || !option) return toast(t('announcement.voteChoose'), 'err')
5348
+ const option = poll.options.find(entry => entry.id === optionId)
5349
+ const answer = poll.legacy === false && forms ? forms.validate(poll, { answers: forms.read($('announcement-poll-options'), poll) }) : option ? { optionId: option.id } : { error: 'answer required' }
5350
+ if (answer.error) {
5351
+ const q = poll.questions?.find(row => row.id === answer.questionId)
5352
+ return toast((q ? q.question + ':' : '') + (I18N.lang === 'en' ? 'Check required answers and selection limits.' : '请检查必填内容、字数和选项数量。'), 'err')
5353
+ }
5354
+ const message = forms ? forms.encode(item.id, poll.id, answer) : `Poll ${poll.id}: ${option.id}`
5355
+ if (!message) return toast(I18N.lang === 'en' ? 'Answers are too long. Please shorten them.' : '回答总长度过长,请适当精简。', 'err')
5139
5356
  const button = $('announcement-poll-submit')
5140
5357
  button.disabled = true
5141
- const payload = {
5142
- type: 'poll',
5143
- message: `Poll ${poll.id}: ${option.id}`,
5144
- announcementId: item.id,
5145
- pollId: poll.id,
5146
- optionId: option.id,
5147
- appVersion: state.localVersion
5148
- }
5358
+ const connection = captureConnection(), valid = () => connection.valid() && state.announcement === item
5359
+ state.announcementSubmitting = true
5360
+ const payload = { type: 'poll', message, announcementId: item.id, pollId: poll.id, ...answer, appVersion: state.localVersion }
5149
5361
  try {
5150
5362
  const base = updateBase()
5151
5363
  let res = null
@@ -5162,8 +5374,8 @@ async function submitAnnouncementVote() {
5162
5374
  data = await res.json().catch(() => ({}))
5163
5375
  } catch {}
5164
5376
  }
5165
- // 没有网关地址、网关网络错误或令牌失效时,投票改走公网收集器。
5166
- if (!res || res.status === 401) {
5377
+ // 仅旧单选投票保留公网兜底;含填写内容的表单只提交当前网关。
5378
+ if ((!res || res.status === 401) && poll.legacy !== false && connection.valid()) {
5167
5379
  const directSignal = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(8000) : undefined
5168
5380
  res = await fetch(DIRECT_POLL_FEEDBACK_URL, {
5169
5381
  method: 'POST',
@@ -5174,22 +5386,29 @@ async function submitAnnouncementVote() {
5174
5386
  })
5175
5387
  data = await res.json().catch(() => ({}))
5176
5388
  }
5177
- if (res.ok && data.ok) {
5178
- storeAnnouncementVote(item.id, poll.id, option.id)
5389
+ if (!connection.valid()) return
5390
+ if (res?.ok && data.ok) {
5391
+ storeAnnouncementVote(item.id, poll.id, answer.optionId || '')
5179
5392
  markAnnouncementSeen(item.id)
5180
- renderAnnouncementPoll(item)
5393
+ if (valid()) renderAnnouncementPoll(item)
5181
5394
  renderAnnouncementHistory()
5182
- toast(t('announcement.voteThanks', { option: option.label }), 'ok')
5183
- } else if (res.status === 429) {
5395
+ toast(poll.legacy === false ? (I18N.lang === 'en' ? 'Submitted successfully' : '已成功提交') : t('announcement.voteThanks', { option: option.label }), 'ok')
5396
+ } else if (res?.status === 429) {
5184
5397
  toast(t('announcement.voteAgainLater'), 'err')
5185
5398
  button.disabled = false
5186
5399
  } else {
5187
- toast(t('announcement.voteFailed', { msg: data.error || res.status }), 'err')
5400
+ toast(t('announcement.voteFailed', { msg: data.error || res?.status || t('announcement.voteNetworkError') }), 'err')
5188
5401
  button.disabled = false
5189
5402
  }
5190
5403
  } catch (e) {
5191
- toast(t('announcement.voteFailed', { msg: e.message || t('announcement.voteNetworkError') }), 'err')
5404
+ if (valid()) toast(t('announcement.voteFailed', { msg: e.message || t('announcement.voteNetworkError') }), 'err')
5192
5405
  button.disabled = false
5406
+ } finally {
5407
+ state.announcementSubmitting = false
5408
+ if (connection.valid() && state.announcement?.poll) {
5409
+ const active = state.announcement
5410
+ button.disabled = !!announcementVote(active) || (active.poll.legacy !== false && !document.querySelector('input[name="announcement-poll-option"]:checked'))
5411
+ }
5193
5412
  }
5194
5413
  }
5195
5414
  function closeAnnouncement(markSeen) {
@@ -5215,11 +5434,11 @@ async function fetchAnnouncements() {
5215
5434
  state.announcements = normalized.sort((a, b) => Number(b.publishedAt || 0) - Number(a.publishedAt || 0))
5216
5435
  storeAnnouncementHistory(normalized)
5217
5436
  renderAnnouncementBoard()
5218
- if (window.DshWorkflow?.isMounted()) return false
5219
5437
  const seen = readSeenAnnouncements()
5220
5438
  const items = normalized.filter(item => !seen[item.id])
5221
5439
  .sort((a, b) => b.publishedAt - a.publishedAt)
5222
- if (!items.length || state.announcement) return false
5440
+ // 新旧界面均提示未读公告;拉取期间新出现的版本提醒仍优先展示。
5441
+ if (!items.length || state.announcement || isAppVersionWarningOpen()) return false
5223
5442
  openAnnouncementModal(items)
5224
5443
  return true
5225
5444
  } catch { return false }
@@ -5407,6 +5626,7 @@ function finishUpdateDownload() {
5407
5626
  clearInterval(updateDownloadTimer)
5408
5627
  updateDownloadTimer = null
5409
5628
  $('btn-download-update').disabled = false
5629
+ const forceButton=$('btn-force-download-update');if(forceButton)forceButton.disabled=false
5410
5630
  }
5411
5631
 
5412
5632
  async function verifyUpdateApk(info, url) {
@@ -5417,7 +5637,7 @@ async function verifyUpdateApk(info, url) {
5417
5637
  const resetTimeout = () => { clearTimeout(timer); timer = setTimeout(() => controller.abort(), 60000) }
5418
5638
  try {
5419
5639
  resetTimeout()
5420
- const res = await fetch(url, { signal: controller.signal })
5640
+ const res = await fetch(url, { signal: controller.signal, cache: 'no-store' })
5421
5641
  if (!res.ok) return { ok: false, status: res.status }
5422
5642
  total = Number(res.headers.get('content-length')) || 0
5423
5643
  const chunks = []
@@ -5448,23 +5668,36 @@ async function verifyUpdateApk(info, url) {
5448
5668
  finally { clearTimeout(timer); clearInterval(progressTimer) }
5449
5669
  }
5450
5670
 
5451
- async function downloadUpdate() {
5452
- const info = state.updateInfo
5453
- if (!info || updateDownloadBusy) return
5454
- const url = new URL(info.apkUrl || 'dsh-remote.apk', updateBase() + '/').href
5455
- const sha256 = String(info.sha256 || '').trim().toLowerCase()
5456
- if (!/^[0-9a-f]{64}$/.test(sha256)) {
5457
- // 无 SHA-256 的更新包一律不下载、不安装
5458
- updateDownloadProgress({ phase: 'error', error: t('update.hashMissing') })
5459
- return
5460
- }
5671
+ async function downloadUpdate(force = false) {
5672
+ if (updateDownloadBusy || (force !== true && !state.updateInfo)) return
5673
+ const base=updateBase()
5674
+ if(!base){toast(t('update.needServer'),'err');return}
5675
+ const connection=captureConnection()
5461
5676
  updateDownloadBusy = true
5462
5677
  updateDownloadSample = null
5463
5678
  $('btn-download-update').disabled = true
5464
- updateDownloadProgress({ phase: 'downloading', received: 0, total: 0 })
5465
- if (CAP?.isNativePlatform?.() && window.NativeUpdate?.downloadVerifiedAndInstall && window.NativeUpdate?.getDownloadStatus) {
5466
- try {
5679
+ const forceButton=$('btn-force-download-update');if(forceButton)forceButton.disabled=true
5680
+ let nativePending=false
5681
+ try {
5682
+ let info=state.updateInfo
5683
+ if(force===true){
5684
+ updateDownloadProgress({phase:'checking',received:0,total:0})
5685
+ // Same-version patches deliberately bypass only version comparison. Both
5686
+ // metadata and APK bytes are fetched afresh; hash verification still applies.
5687
+ const response=await fetch(base+'/update.json?t='+Date.now()+'&local='+encodeURIComponent(state.localVersion||''),{cache:'no-store',signal:AbortSignal.timeout(15000)})
5688
+ if(!response.ok)throw new Error('HTTP '+response.status)
5689
+ info=await response.json()
5690
+ }
5691
+ if(!connection.valid())return
5692
+ const sha256=String(info?.sha256||'').trim().toLowerCase()
5693
+ if(!/^[0-9a-f]{64}$/.test(sha256))throw new Error(t('update.hashMissing'))
5694
+ const target=new URL(info.apkUrl||'dsh-remote.apk',base+'/')
5695
+ if(force===true)target.searchParams.set('dshPatch',Date.now().toString(36)+'-'+sha256.slice(0,16))
5696
+ const url=target.href
5697
+ updateDownloadProgress({ phase: 'downloading', received: 0, total: 0 })
5698
+ if (CAP?.isNativePlatform?.() && window.NativeUpdate?.downloadVerifiedAndInstall && window.NativeUpdate?.getDownloadStatus) {
5467
5699
  if (!window.NativeUpdate.downloadVerifiedAndInstall(url, sha256)) throw new Error(t('update.busy'))
5700
+ nativePending=true
5468
5701
  const poll = () => {
5469
5702
  try {
5470
5703
  const value = JSON.parse(window.NativeUpdate.getDownloadStatus())
@@ -5474,12 +5707,11 @@ async function downloadUpdate() {
5474
5707
  }
5475
5708
  updateDownloadTimer = setInterval(poll, 500)
5476
5709
  poll()
5477
- } catch (error) { updateDownloadProgress({ phase: 'error', error: error.message }); finishUpdateDownload() }
5478
- return
5479
- }
5480
- try {
5710
+ return
5711
+ }
5481
5712
  const result = await verifyUpdateApk(info, url)
5482
- if (!result.ok) throw new Error(result.corrupted ? t('update.corrupted') : result.status ? t('update.serverFileMissing') : result.msg || t('fs.networkError'))
5713
+ if(!connection.valid())return
5714
+ if (!result.ok) throw new Error(result.corrupted ? t(force===true?'update.patchMismatch':'update.corrupted') : result.status ? t('update.serverFileMissing') : result.msg || t('fs.networkError'))
5483
5715
  {
5484
5716
  // 无校验的原生安装入口已移除: 新旧壳统一走下方"下载并本地校验"路径。
5485
5717
  const objectUrl = URL.createObjectURL(result.blob)
@@ -5492,8 +5724,8 @@ async function downloadUpdate() {
5492
5724
  setTimeout(() => URL.revokeObjectURL(objectUrl), 60000)
5493
5725
  updateDownloadProgress({ phase: 'complete', received: result.blob.size, total: result.blob.size })
5494
5726
  }
5495
- } catch (error) { updateDownloadProgress({ phase: 'error', error: error.message }) }
5496
- finally { finishUpdateDownload() }
5727
+ } catch (error) { if(connection.valid())updateDownloadProgress({ phase: 'error', error: error.message }) }
5728
+ finally { if(!nativePending)finishUpdateDownload() }
5497
5729
  }
5498
5730
 
5499
5731
 
@@ -5630,7 +5862,14 @@ function applyBgConfigFromNative() {
5630
5862
  if (opts.some(o => o.value === v)) $('bg-interval').value = v
5631
5863
  syncCustomSelect($('bg-interval'))
5632
5864
  if ($('opt-task-done')) $('opt-task-done').checked = cfg.notifyTaskDone !== false
5633
- $('bg-auth-status')?.classList.toggle('hidden', !cfg.loginExpired)
5865
+ const status = $('bg-auth-status')
5866
+ if (status) {
5867
+ status.removeAttribute('data-i18n')
5868
+ status.textContent = cfg.loginExpired ? t('settings.bgAuthFailed') : cfg.enabled && cfg.serviceRunning === false
5869
+ ? (I18N.lang === 'en' ? 'Background receiver is not running. Reopen the app or toggle to retry. ' : '后台接收未运行,返回应用或重新开关后重试。') + (cfg.serviceState || '')
5870
+ : cfg.enabled && cfg.serviceRunning === true ? (I18N.lang === 'en' ? 'Background receiver is running.' : '后台接收运行中。') + (cfg.lastSuccessAt ? ' ' + new Date(cfg.lastSuccessAt).toLocaleTimeString() : '') : ''
5871
+ status.classList.toggle('hidden', !status.textContent)
5872
+ }
5634
5873
  } catch {}
5635
5874
  }
5636
5875
  function saveBgConfig(enabled) {
@@ -5639,12 +5878,13 @@ function saveBgConfig(enabled) {
5639
5878
  const base = bgBase()
5640
5879
  const intervalMin = parseFloat($('bg-interval')?.value || '0.5') || 0.5
5641
5880
  const notifyTaskDone = $('opt-task-done')?.checked !== false
5642
- b.saveBackgroundConfig(JSON.stringify({ enabled, intervalMin, base, token: state.token || '', clientId: CLIENT_ID || '', notifyTaskDone }))
5881
+ const saved = b.saveBackgroundConfig(JSON.stringify({ enabled, intervalMin, base, token: state.token || '', clientId: CLIENT_ID || '', notifyTaskDone })) !== false
5643
5882
  if (enabled) $('bg-auth-status')?.classList.add('hidden')
5644
- return true
5883
+ return saved
5645
5884
  }
5646
5885
  function syncBgConfig() {
5647
5886
  if ($('opt-bg-poll')?.checked && state.token) saveBgConfig(true)
5887
+ void syncPeakReminders()
5648
5888
  }
5649
5889
 
5650
5890
  /* ---------------- 预设提示词 ---------------- */
@@ -5719,8 +5959,7 @@ function deletePreset(id) {
5719
5959
  toast(t('presets.deleted'), 'ok')
5720
5960
  }
5721
5961
 
5722
- /* ---------------- 峰谷计费提醒(前台服务进程内定时, 绕开 MIUI 后台限制) ---------------- */
5723
- function peakRemindOn() { return LS.get('peakRemind', '0') === '1' }
5962
+ /* ---------------- 插件规则驱动的 Android 峰谷通知 ---------------- */
5724
5963
  const LEGACY_PEAK_NOTIFICATION_IDS = [8801, 8802, 8803, 8804]
5725
5964
 
5726
5965
  async function cancelLegacyPeakNotifications() {
@@ -5736,32 +5975,55 @@ async function cancelLegacyPeakNotifications() {
5736
5975
  }
5737
5976
  }
5738
5977
 
5739
- async function schedulePeakReminders({ legacyCleaned = false } = {}) {
5740
- if (!CAP?.isNativePlatform?.()) return false
5741
- if (!legacyCleaned && !await cancelLegacyPeakNotifications()) return false
5742
- const b = bgBridge()
5743
- if (!b?.startPeakReminder) return false
5744
- try {
5745
- return b.startPeakReminder() !== false
5746
- } catch { return false }
5747
- }
5748
-
5749
5978
  async function cancelPeakReminders() {
5750
5979
  if (!CAP?.isNativePlatform?.()) return false
5980
+ const legacyCleaned = await cancelLegacyPeakNotifications()
5751
5981
  const b = bgBridge()
5982
+ if (b?.savePeakReminderConfig) return b.savePeakReminderConfig(JSON.stringify({ enabled: false })) !== false && legacyCleaned
5752
5983
  if (!b?.stopPeakReminder) return false
5753
5984
  try {
5754
5985
  const stopped = b.stopPeakReminder() !== false
5755
- const legacyCleaned = await cancelLegacyPeakNotifications()
5756
5986
  return stopped && legacyCleaned
5757
5987
  } catch { return false }
5758
5988
  }
5759
5989
 
5760
5990
  async function restorePeakReminders() {
5761
- if (!CAP?.isNativePlatform?.()) return
5762
- // 旧版使用 LocalNotifications 每日调度;无论当前开关状态都先清理,防止与前台服务重复提醒。
5763
- const legacyCleaned = await cancelLegacyPeakNotifications()
5764
- if (peakRemindOn() && legacyCleaned) await schedulePeakReminders({ legacyCleaned: true })
5991
+ await cancelLegacyPeakNotifications()
5992
+ let enabled = LS.get('peakRemind', '')
5993
+ if (!enabled) {
5994
+ try { enabled = JSON.parse(bgBridge()?.getPeakReminderConfig?.() || '{}').enabled ? '1' : '0' } catch { enabled = '0' }
5995
+ }
5996
+ $('opt-peak-remind').checked = enabled === '1'
5997
+ LS.set('peakRemind', enabled)
5998
+ if (enabled === '1') await syncPeakReminders()
5999
+ }
6000
+ let peakReminderRead = 0
6001
+ async function syncPeakReminders() {
6002
+ const b = bgBridge()
6003
+ if (!CAP?.isNativePlatform?.() || !b?.savePeakReminderConfig) return false
6004
+ const enabled = LS.get('peakRemind', '0') === '1', serial = ++peakReminderRead
6005
+ const config = { enabled, base: bgBase(), token: state.token || '', clientId: CLIENT_ID || '' }
6006
+ const status = $('peak-remind-status'), say = value => { if (status) status.textContent = value }
6007
+ const started = b.savePeakReminderConfig(JSON.stringify(config)) !== false
6008
+ if (!enabled) { say(''); return started }
6009
+ if (!started) { say(I18N.lang === 'en' ? 'Background receiver failed to start. Check system restrictions.' : '后台提醒未启动,请检查系统限制后重试。'); return false }
6010
+ if (!state.token) { say(t('settings.bgNeedToken')); return false }
6011
+ say(I18N.lang === 'en' ? 'Reading dsh-cost-meter rules…' : '正在读取 dsh-cost-meter 规则…')
6012
+ const connection = captureConnection()
6013
+ try {
6014
+ const response = await fetch(connection.server + '/remote/api/insights/peak-reminders', { headers: { authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': 'app', ...clientIdHeaders() }, signal: AbortSignal.timeout(20000) })
6015
+ const data = await response.json()
6016
+ if (!connection.valid() || serial !== peakReminderRead) return false
6017
+ if (!response.ok || data.ok !== true) throw Error('unavailable')
6018
+ b.savePeakReminderConfig(JSON.stringify({ ...config, policy: data }))
6019
+ say(data.available !== true ? (I18N.lang === 'en' ? 'No compatible cost-meter rules on this host.' : '主机未提供兼容的费用插件规则,请检查插件和网关版本。')
6020
+ : data.enabled === false ? (I18N.lang === 'en' ? 'Reminders are disabled in dsh-cost-meter.' : '费用插件已关闭峰谷提醒,请在 DSH 峰谷计价设置中开启。')
6021
+ : (I18N.lang === 'en' ? 'Rules synced. Android will deliver reminders in the background.' : '规则已同步,由 Android 在后台发送通知。'))
6022
+ return data.available === true
6023
+ } catch {
6024
+ if (connection.valid() && serial === peakReminderRead) say(I18N.lang === 'en' ? 'Rules could not refresh. The receiver will retry; only unexpired cached rules apply.' : '规则暂未刷新,后台会重试;仅使用未过期的已缓存规则。')
6025
+ return false
6026
+ }
5765
6027
  }
5766
6028
 
5767
6029
  /* ---------------- 模型设置 ---------------- */
@@ -6317,6 +6579,8 @@ async function openModelConfigDocument() {
6317
6579
  }
6318
6580
  /* ---------------- 视图切换 ---------------- */
6319
6581
  function showView(id) {
6582
+ if (id !== 'view-session') window.DshSubagents?.close()
6583
+ document.body?.classList.toggle('viewing-subagent', id === 'view-session' && state.byId.get(state.current)?.origin === 'subagent')
6320
6584
  window.DshWorkflow?.close()
6321
6585
  if (window.DshWorkflow?.isMounted() && id === 'view-activity') id = 'view-home'
6322
6586
  if (id !== 'view-session') conversationView?.pause()
@@ -6883,7 +7147,7 @@ function renderDshControlOperation(operation) {
6883
7147
  const desc = $('dsh-control-desc')
6884
7148
  const box = $('dsh-control-steps')
6885
7149
  if (!desc || !box || !operation) return
6886
- const failed = operation.stage === 'failed' || operation.done && operation.ok === false
7150
+ const failed = operation.stage !== 'unknown' && (operation.stage === 'failed' || operation.done && operation.ok === false)
6887
7151
  desc.textContent = failed ? t('settings.dshFailed', { msg: dshControlFailureText(operation) }) : dshControlStageText(operation)
6888
7152
  const steps = Array.isArray(operation.steps) && operation.steps.length
6889
7153
  ? operation.steps
@@ -6909,20 +7173,45 @@ async function readDshControlResponse(res) {
6909
7173
  try { return JSON.parse(text) } catch { return { error: `HTTP ${res.status}`, detail: text.slice(0, 500) } }
6910
7174
  }
6911
7175
 
6912
- async function pollDshControlOperation(operationId, initial) {
7176
+ let dshControlPollContext = null
7177
+ function dshControlContext() {
7178
+ const connection = captureConnection(), url = adminApiUrl('/admin/api/dsh')
7179
+ return { ...connection, url }
7180
+ }
7181
+
7182
+ async function pollDshControlOperation(operationId, initial, context = dshControlContext()) {
6913
7183
  let value = initial
6914
- while (true) {
7184
+ if (context.valid() && value?.done) { renderDshControlOperation(value); return value }
7185
+ const deadline = Math.min(Number(initial?.deadlineAt) || Date.now() + 60000, Date.now() + 320000)
7186
+ let failures = 0
7187
+ while (context.valid() && Date.now() < deadline) {
6915
7188
  renderDshControlOperation(value)
6916
7189
  if (value.done) return value
6917
- await new Promise(resolvePromise => setTimeout(resolvePromise, 700))
6918
- const res = await fetch(adminApiUrl(`/admin/api/dsh?operation=${encodeURIComponent(operationId)}`), {
6919
- headers: { authorization: 'Bearer ' + state.token }, cache: 'no-store'
6920
- })
6921
- if (res.status === 401) { authFailure(); throw Object.assign(new Error('unauthorized'), { auth: true }) }
6922
- const next = await readDshControlResponse(res)
6923
- if (!res.ok) throw Object.assign(new Error(next.error || next.message || `HTTP ${res.status}`), { dshPayload: { ...next, httpStatus: res.status } })
6924
- value = next
7190
+ await new Promise(resolvePromise => setTimeout(resolvePromise, Math.min(700 * (failures + 1), 3000)))
7191
+ if (!context.valid()) return null
7192
+ try {
7193
+ const res = await fetch(context.url + '?operation=' + encodeURIComponent(operationId), {
7194
+ headers: { authorization: 'Bearer ' + context.token }, cache: 'no-store', signal: AbortSignal.timeout(8000)
7195
+ })
7196
+ if (!context.valid()) return null
7197
+ if (res.status === 401) { authFailure(); throw Object.assign(new Error('unauthorized'), { auth: true }) }
7198
+ const next = await readDshControlResponse(res)
7199
+ if (!context.valid()) return null
7200
+ if (!res.ok) {
7201
+ if (res.status === 404 || res.status === 429 || res.status >= 500) throw new Error('gateway recovering')
7202
+ throw Object.assign(new Error(next.error || next.message || `HTTP ${res.status}`), { dshPayload: { ...next, httpStatus: res.status } })
7203
+ }
7204
+ if (next.operationId !== operationId) throw new Error('invalid operation response')
7205
+ value = next; failures = 0
7206
+ if (value.done) { renderDshControlOperation(value); return value }
7207
+ } catch (error) {
7208
+ if (!context.valid()) return null
7209
+ if (error.auth || error.dshPayload) throw error
7210
+ failures++
7211
+ value = { ...value, done: false, stage: 'recovering', message: t('settings.dshRecovering') }
7212
+ }
6925
7213
  }
7214
+ return context.valid() ? { ...value, done: true, ok: false, stage: 'unknown', code: 'RESULT_UNKNOWN', message: t('settings.dshResultUnknown') } : null
6926
7215
  }
6927
7216
 
6928
7217
  function renderDshControlStatus(value) {
@@ -6953,6 +7242,7 @@ function renderDshControlStatus(value) {
6953
7242
 
6954
7243
  async function loadDshControl() {
6955
7244
  if (!state.token || !$('dsh-control-desc')) return
7245
+ const context = dshControlContext()
6956
7246
  if (activeGatewayCapability('dshLifecycle') === false) {
6957
7247
  renderDshControlStatus({
6958
7248
  supported: false,
@@ -6961,43 +7251,62 @@ async function loadDshControl() {
6961
7251
  return
6962
7252
  }
6963
7253
  try {
6964
- const res = await fetch(adminApiUrl('/admin/api/dsh'), { headers: { authorization: 'Bearer ' + state.token }, cache: 'no-store' })
7254
+ const res = await fetch(context.url, { headers: { authorization: 'Bearer ' + context.token }, cache: 'no-store', signal: AbortSignal.timeout(8000) })
7255
+ if (!context.valid()) return
6965
7256
  if (res.status === 401) return authFailure()
6966
7257
  const value = await readDshControlResponse(res)
7258
+ if (!context.valid()) return
6967
7259
  if (!res.ok) throw Object.assign(new Error(value.error || value.message || `HTTP ${res.status}`), { dshPayload: value })
7260
+ if (dshControlPollPromise && dshControlPollContext?.valid()) return
6968
7261
  renderDshControlStatus(value)
6969
- if (value.operation?.operationId && !value.operation.done && !dshControlPollPromise) {
6970
- dshControlPollPromise = pollDshControlOperation(value.operation.operationId, value.operation)
6971
- .then(renderDshControlOperation)
7262
+ if (value.operation?.operationId && !value.operation.done) {
7263
+ dshControlPollContext = context
7264
+ const job = pollDshControlOperation(value.operation.operationId, value.operation, context)
7265
+ .then(result => { if (context.valid() && result) renderDshControlOperation(result) })
6972
7266
  .catch(error => {
6973
- if (!error?.auth) $('dsh-control-desc').textContent = t('settings.dshFailed', { msg: error?.dshPayload ? dshControlFailureText(error.dshPayload) : t('settings.dshResultUnknown') })
7267
+ if (context.valid() && !error?.auth) $('dsh-control-desc').textContent = t('settings.dshFailed', { msg: error?.dshPayload ? dshControlFailureText(error.dshPayload) : t('settings.dshResultUnknown') })
6974
7268
  })
6975
- .finally(() => { dshControlPollPromise = null; dshControlButtonsBusy(false, true) })
7269
+ .finally(() => { if (dshControlPollPromise === job) { dshControlPollPromise = null; if (context.valid()) void loadDshControl() } })
7270
+ dshControlPollPromise = job
6976
7271
  }
6977
7272
  } catch (error) {
7273
+ if (!context.valid()) return
6978
7274
  $('dsh-control-desc').textContent = t('settings.dshStatusFailed', { msg: error?.dshPayload ? dshControlFailureText(error.dshPayload) : t('conn.off') })
6979
7275
  }
6980
7276
  }
6981
7277
 
6982
7278
  async function controlDsh(action) {
6983
- if (dshControlPollPromise) return
7279
+ if (dshControlPollPromise && dshControlPollContext?.valid()) return
7280
+ const context = dshControlContext(), requestId = uuid()
7281
+ let release
7282
+ const busy = new Promise(resolve => { release = resolve })
7283
+ dshControlPollPromise = busy; dshControlPollContext = context
6984
7284
  const label = action === 'start' ? t('settings.dshStart') : t('settings.dshRestart')
6985
7285
  dshControlButtonsBusy(true, true)
6986
7286
  renderDshControlOperation({ action, service: 'dsh-web', accepted: true, done: false, stage: 'queued', elapsedMs: 0, steps: [] })
6987
7287
  try {
6988
- const res = await fetch(adminApiUrl('/admin/api/dsh'), {
7288
+ let res
7289
+ try { res = await fetch(context.url, {
6989
7290
  method: 'POST',
6990
- headers: { authorization: 'Bearer ' + state.token, 'content-type': 'application/json' },
6991
- body: JSON.stringify({ action }),
6992
- })
7291
+ headers: { authorization: 'Bearer ' + context.token, 'content-type': 'application/json' },
7292
+ body: JSON.stringify({ action, requestId }), signal: AbortSignal.timeout(8000),
7293
+ }) } catch {
7294
+ if (!context.valid()) return
7295
+ const recovered = await pollDshControlOperation(requestId, { action, done: false, deadlineAt: Date.now() + 60000 }, context)
7296
+ if (context.valid() && recovered) renderDshControlOperation(recovered)
7297
+ return
7298
+ }
7299
+ if (!context.valid()) return
6993
7300
  if (res.status === 401) return authFailure()
6994
7301
  let v = await readDshControlResponse(res)
7302
+ if (!context.valid()) return
6995
7303
  if (res.status === 409 && v.operation?.operationId) v = v.operation
6996
7304
  else if (!res.ok) throw Object.assign(new Error(v.error || v.message || `HTTP ${res.status}`), { dshPayload: { ...v, httpStatus: res.status } })
6997
7305
 
6998
7306
  if (v.accepted && v.operationId) {
6999
- dshControlPollPromise = pollDshControlOperation(v.operationId, v)
7000
- v = await dshControlPollPromise
7307
+ v = await pollDshControlOperation(v.operationId, v, context)
7308
+ if (!context.valid() || !v) return
7309
+ if (v.stage === 'unknown') { renderDshControlOperation(v); return }
7001
7310
  if (!v.ok) throw Object.assign(new Error(dshControlFailureText(v)), { dshPayload: v })
7002
7311
  renderDshControlOperation(v)
7003
7312
  toast(dshControlStageText(v), 'ok')
@@ -7009,6 +7318,7 @@ async function controlDsh(action) {
7009
7318
  renderDshControlStatus(v)
7010
7319
  toast(t('settings.dshStarted', { action: label }), 'ok')
7011
7320
  } catch (error) {
7321
+ if (!context.valid()) return
7012
7322
  if (error?.auth) return
7013
7323
  const payload = error?.dshPayload
7014
7324
  const message = payload ? dshControlFailureText(payload) : t('settings.dshResultUnknown')
@@ -7016,8 +7326,8 @@ async function controlDsh(action) {
7016
7326
  else $('dsh-control-desc').textContent = t('settings.dshFailed', { msg: message })
7017
7327
  toast(t('settings.dshFailed', { msg: message }), 'err')
7018
7328
  } finally {
7019
- dshControlPollPromise = null
7020
- dshControlButtonsBusy(false, true)
7329
+ release()
7330
+ if (dshControlPollPromise === busy) { dshControlPollPromise = null; if (context.valid()) void loadDshControl() }
7021
7331
  }
7022
7332
  }
7023
7333
 
@@ -7110,7 +7420,7 @@ function bindUi() {
7110
7420
  if (state.current) { renderSessionTitle(); renderSessionSub(); renderSessionCards(); renderHistory(true) }
7111
7421
  else renderModelMenu()
7112
7422
  loadLocalVersion()
7113
- if (state.hostInfo) $('host-desc').textContent = t('settings.hostDesc', { version: state.hostInfo.version, cwd: state.hostInfo.cwd, n: state.hostInfo.attachedSessions })
7423
+ if (state.hostInfo) $('host-desc').textContent = hostDescriptionText(state.hostInfo)
7114
7424
  $('token-desc').textContent = state.token ? t('token.savedLocal') : t('token.notSet')
7115
7425
  })
7116
7426
  $('btn-theme').addEventListener('click', openThemePanel)
@@ -7396,7 +7706,16 @@ function bindUi() {
7396
7706
  $('announcement-next').addEventListener('click', () => showAnnouncementAt(state.announcementIndex + 1))
7397
7707
  $('announcement-later').addEventListener('click', () => closeAnnouncement(false))
7398
7708
  $('announcement-confirm').addEventListener('click', () => closeAnnouncement(true))
7399
- $('announcement-poll-options').addEventListener('change', () => { $('announcement-poll-submit').disabled = false })
7709
+ const saveAnnouncementDraft = () => {
7710
+ const item = state.announcement
7711
+ if (item?.poll?.legacy === false && window.DshAnnouncementForms) {
7712
+ state.announcementDrafts ||= Object.create(null)
7713
+ state.announcementDrafts[announcementVoteKey(item.id, item.poll.id)] = window.DshAnnouncementForms.read($('announcement-poll-options'), item.poll)
7714
+ }
7715
+ $('announcement-poll-submit').disabled = !!state.announcementSubmitting
7716
+ }
7717
+ $('announcement-poll-options').addEventListener('change', saveAnnouncementDraft)
7718
+ $('announcement-poll-options').addEventListener('input', saveAnnouncementDraft)
7400
7719
  $('announcement-poll-submit').addEventListener('click', submitAnnouncementVote)
7401
7720
  $('modal-announcement').addEventListener('click', (e) => {
7402
7721
  if (e.target === $('modal-announcement') && !state.announcementItems.some(item => item.force)) closeAnnouncement(false)
@@ -7468,7 +7787,8 @@ function bindUi() {
7468
7787
  $('btn-dsh-start')?.addEventListener('click', () => controlDsh('start'))
7469
7788
  $('btn-dsh-restart')?.addEventListener('click', () => controlDsh('restart'))
7470
7789
  $('btn-check-update').addEventListener('click', () => checkUpdate(false))
7471
- $('btn-download-update').addEventListener('click', downloadUpdate)
7790
+ $('btn-download-update').addEventListener('click', () => void downloadUpdate())
7791
+ $('btn-force-download-update').addEventListener('click', () => void downloadUpdate(true))
7472
7792
  $('btn-update-expand').addEventListener('click', toggleUpdateExpand)
7473
7793
  $('app-version-later').addEventListener('click', () => closeAppVersionWarning(false))
7474
7794
  $('app-version-update').addEventListener('click', () => closeAppVersionWarning(true))
@@ -7511,35 +7831,20 @@ function bindUi() {
7511
7831
  LS.set('notify', e.target.checked ? '1' : '0')
7512
7832
  window.NativeBackground?.setPendingNotificationsEnabled?.(e.target.checked)
7513
7833
  })
7514
- $('opt-peak-remind').checked = peakRemindOn()
7515
- $('opt-peak-remind').addEventListener('change', async (e) => {
7516
- if (e.target.checked) {
7517
- if (!CAP?.isNativePlatform?.()) {
7518
- e.target.checked = false
7519
- return toast(t('peakRemind.browserOnly'), 'err')
7520
- }
7521
- const ok = await ensureNotify()
7522
- if (!ok) { e.target.checked = false; return toast(t('settings.notifyDenied')) }
7523
- const started = await schedulePeakReminders()
7524
- if (!started) {
7525
- e.target.checked = false
7526
- return toast(t('peakRemind.failed'), 'err')
7527
- }
7528
- toast(t('peakRemind.on'), 'ok')
7529
- } else {
7530
- const stopped = await cancelPeakReminders()
7531
- if (!stopped) {
7532
- e.target.checked = true
7533
- return toast(t('peakRemind.failed'), 'err')
7534
- }
7535
- toast(t('peakRemind.off'), 'ok')
7536
- }
7537
- LS.set('peakRemind', e.target.checked ? '1' : '0')
7538
- })
7539
7834
  $('btn-test-notify').addEventListener('click', sendTestNotification)
7540
7835
  $('btn-announcement-history').addEventListener('click', openAnnouncementHistory)
7541
- // 启动时先清理旧版 LocalNotifications,再按当前开关恢复前台提醒服务。
7836
+ // 启动时清理旧版 LocalNotifications 和前台提醒服务,提醒交给 dsh-cost-meter。
7542
7837
  restorePeakReminders()
7838
+ $('opt-peak-remind').addEventListener('change', async event => {
7839
+ const input = event.target
7840
+ if (input.checked) {
7841
+ if (!CAP?.isNativePlatform?.() || !bgBridge()?.savePeakReminderConfig) { input.checked = false; return toast(t('peakRemind.browserOnly'), 'err') }
7842
+ if (!state.token) { input.checked = false; return toast(t('settings.bgNeedToken'), 'err') }
7843
+ if (!await ensureNotify()) { input.checked = false; return toast(t('settings.notifyDenied'), 'err') }
7844
+ }
7845
+ LS.set('peakRemind', input.checked ? '1' : '0')
7846
+ await syncPeakReminders()
7847
+ })
7543
7848
  applyBgConfigFromNative()
7544
7849
  $('opt-bg-poll').addEventListener('change', async (e) => {
7545
7850
  if (e.target.checked) {
@@ -7553,8 +7858,9 @@ function bindUi() {
7553
7858
  }
7554
7859
  const ok = await ensureNotify()
7555
7860
  if (!ok) { e.target.checked = false; return toast(t('settings.notifyDenied')) }
7556
- saveBgConfig(true)
7557
- toast(t('settings.bgOn'), 'ok')
7861
+ const saved = saveBgConfig(true)
7862
+ applyBgConfigFromNative()
7863
+ toast(saved ? t('settings.bgOn') : (I18N.lang === 'en' ? 'Could not start background receiver. Check system restrictions.' : '后台接收启动失败,请检查系统限制后重试。'), saved ? 'ok' : 'err')
7558
7864
  } else {
7559
7865
  saveBgConfig(false)
7560
7866
  toast(t('settings.bgOff'), 'ok')
@@ -7591,6 +7897,7 @@ function bindUi() {
7591
7897
  bindFsPullRefresh()
7592
7898
 
7593
7899
  bindRail()
7900
+ window.DshImagePreview?.configure?.({ resolvePath: chatImageRequest })
7594
7901
 
7595
7902
  for (const id of ['history', 'question-body']) window.DshChatFiles?.bind($(id), () => {
7596
7903
  const c=captureConnection(),sessionId=id==='history'?state.current:state.questionModal?.sessionId
@@ -7677,6 +7984,7 @@ function mountWorkflow() {
7677
7984
  },
7678
7985
  command: runSlashCommand, refresh: refreshAll, retry: () => { startOverviewDetection(true); void refreshAll() },
7679
7986
  operations: () => { const connection=captureConnection(); return { url:apiUrl,headers:{authorization:'Bearer '+connection.token},valid:connection.valid } },
7987
+ relay: () => { const connection=captureConnection(); return { url:()=>adminApiUrl('/admin/api/relay'),headers:{authorization:'Bearer '+connection.token},valid:connection.valid,connected:!!connection.token } },
7680
7988
  discover: () => { if (confirm('登记当前绑定目录下的子目录为工作区?')) void refreshWorkbench({ discover: true }) },
7681
7989
  files: () => {
7682
7990
  const workspace = workspaceForSession(state.byId.get(state.current))
@@ -7687,7 +7995,7 @@ function mountWorkflow() {
7687
7995
  },
7688
7996
  clear: clearWorkflowData,
7689
7997
  admin: () => {
7690
- const url = new URL(apiUrl('/admin/'), location.href)
7998
+ const url = new URL(adminApiUrl('/admin/'), location.href)
7691
7999
  // Open authenticated management through its own login flow. No credential
7692
8000
  // in a newly created URL, browser history, or referrer.
7693
8001
  window.open(url.href, '_blank', 'noopener,noreferrer')
@@ -7713,6 +8021,7 @@ async function clearWorkflowData(kind) {
7713
8021
  return toast(english ? 'History cache cleared' : '历史缓存已清除', 'ok')
7714
8022
  }
7715
8023
  window.NativeBackground?.saveBackgroundConfig?.(JSON.stringify({ enabled:false, base:'', token:'', clientId:'', intervalMin:1, notifyTaskDone:false }))
8024
+ window.NativeBackground?.savePeakReminderConfig?.(JSON.stringify({ enabled:false }))
7716
8025
  window.NativeBackground?.setPendingNotificationsEnabled?.(false)
7717
8026
  if (kind === 'connection') {
7718
8027
  const current = currentServerEntry()
@@ -7736,7 +8045,20 @@ function openPluginPage(route = 'manage') {
7736
8045
  return
7737
8046
  }
7738
8047
  window.DshExtensions.mount({
7739
- connection, getSession: () => state.byId.get(state.current), getTitle: () => sessionTitleValue(state.byId.get(state.current)),
8048
+ connection,getWorkspaces: () => workspaceItems(),
8049
+ getWorkspaceId: () => workspaceById(state.workspaceFilter)?.workspaceId || workspaceForSession(state.byId.get(state.current))?.workspaceId || '',
8050
+ openTeamCaptain: async id => { if (!connection.valid()) return; await openSession(id) },
8051
+ openTeamMember: async (id, parentId) => {
8052
+ const selected = state.current
8053
+ const catalog = await loadSessionSubagents(parentId)
8054
+ if (!connection.valid() || $('view-plugins').classList.contains('hidden') || state.current !== selected) return
8055
+ const entry = catalog?.entries?.find(row => row.id === id)
8056
+ if (!entry || entry.kind === 'diagnostic') throw Error('unavailable')
8057
+ rememberSubagent(entry, parentId)
8058
+ await openSession(id)
8059
+ },
8060
+ getSession: () => state.byId.get(state.current), getTitle: () => sessionTitleValue(state.byId.get(state.current)),
8061
+ back: () => showView('view-settings'),
7740
8062
  openContext: () => void openInsights('context', true),
7741
8063
  returnToSession: () => showView('view-session'), scrollTop: () => window.scrollTo(0,0),
7742
8064
  url: path => connection.server + path,
@@ -7744,3 +8066,6 @@ function openPluginPage(route = 'manage') {
7744
8066
  valid: connection.valid,
7745
8067
  }, $('plugin-page'), route)
7746
8068
  }
8069
+
8070
+ // Operation logs stay on this device; users can copy or export them.
8071
+ globalThis.DshDiagnostics?.configure({surface:"mobile",copy:copyText,snapshot:()=>({sessionId:state.current,server:state.server,loading:!!state.history.loading,loaded:!!state.history.loaded,count:state.history.visible.length,...globalThis.DshDiagnostics.nativeSnapshot()})})