dsh-remote-plugin 0.8.0-rc.3 → 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
@@ -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,6 +522,7 @@ 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()
@@ -528,7 +534,9 @@ async function rpc(method, payload = {}, timeoutMs = 45000) {
528
534
  error.rpcRejected = true
529
535
  throw error
530
536
  }
537
+ diagnostic?.end({phase:'complete'})
531
538
  return full.result.value
539
+ } catch(error) { diagnostic?.fail(error);throw error }
532
540
  }
533
541
 
534
542
  async function respond(rpcId, value) {
@@ -561,6 +569,11 @@ let hostDescribePromise = null
561
569
  let hostDescribeConnection = null
562
570
  let hostDescribeRetryTimer = null
563
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
+ }
564
577
 
565
578
  function scheduleHostDescribeRetry() {
566
579
  if (!state.token || hostDescribeRetryTimer) return
@@ -579,16 +592,21 @@ async function refreshHostDescription({ notify = false } = {}) {
579
592
  hostDescribeConnection = connection
580
593
  const job = (async () => {
581
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
+ }
582
602
  const host = await rpc('host.describe', {}, 5000)
583
603
  if (!connection.valid()) return null
584
604
  state.hostInfo = host
585
- const health = activeGatewayHealth()
586
- if (health) health.upstreamReachable = true
587
605
  hostDescribeFailures = 0
588
606
  if (hostDescribeRetryTimer) clearTimeout(hostDescribeRetryTimer)
589
607
  hostDescribeRetryTimer = null
590
608
  const desc = $('host-desc')
591
- 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)
592
610
  renderOverview()
593
611
  return host
594
612
  } catch (error) {
@@ -769,8 +787,9 @@ function activeGatewayHealth() {
769
787
 
770
788
  function dshReachable() {
771
789
  const health = activeGatewayHealth()
790
+ if (health && typeof health.upstreamOk === 'boolean') return health.upstreamOk
772
791
  if (health && typeof health.upstreamReachable === 'boolean') return health.upstreamReachable
773
- return !!state.hostInfo
792
+ return !!state.hostInfo && state.hostInfo.metadataOnly !== true
774
793
  }
775
794
 
776
795
  async function selectFastestServer({ silent = false, reconnect = true } = {}) {
@@ -1256,12 +1275,25 @@ function openStreams() {
1256
1275
  function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1257
1276
  if (!state.token) return
1258
1277
  if (ticket === null) {
1259
- 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
1260
1281
  void getWsTicket().then((value) => {
1261
- if (connection.valid()) openStream(kind, handler, refreshOnOpen, isRestore, value)
1262
- }).catch(() => {
1282
+ if (valid()) openStream(kind, handler, refreshOnOpen, isRestore, value)
1283
+ }).catch((error) => {
1263
1284
  // 兼容旧网关/插件副本: ticket 接口不可用时临时回退旧 token 握手。
1264
- 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
+ }
1265
1297
  })
1266
1298
  return
1267
1299
  }
@@ -1294,6 +1326,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1294
1326
  ws._isRestore = !!isRestore
1295
1327
  ws.onopen = () => {
1296
1328
  if (!streamIsCurrent(kind, ws, generation)) return
1329
+ globalThis.DshDiagnostics?.record('stream.state',{channel:kind,status:'open',attempt:meta.failures})
1297
1330
  state.streamsOk[kind] = true
1298
1331
  markStreamInfo(kind, { status: 'open', lastOpenAt: Date.now(), lastCloseCode: 0, lastCloseReason: '' })
1299
1332
  meta.attempt = 0
@@ -1331,7 +1364,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1331
1364
  handler(full)
1332
1365
  } catch {}
1333
1366
  }
1334
- ws.onclose = () => {
1367
+ ws.onclose = (event) => {
1335
1368
  clearStreamTimers(ws)
1336
1369
  if (!streamIsCurrent(kind, ws, generation)) return
1337
1370
  streams[kind] = null
@@ -1339,9 +1372,10 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1339
1372
  markStreamInfo(kind, {
1340
1373
  status: 'closed',
1341
1374
  lastCloseAt: Date.now(),
1342
- lastCloseCode: Number(ws.code) || 0,
1343
- lastCloseReason: String(ws.reason || ''),
1375
+ lastCloseCode: Number(event.code) || 0,
1376
+ lastCloseReason: String(event.reason || '').slice(0, 200),
1344
1377
  })
1378
+ globalThis.DshDiagnostics?.record('stream.state',{channel:kind,status:'closed',closeCode:Number(event.code)||0,attempt:meta.failures+1})
1345
1379
  meta.failures++
1346
1380
  aggregateStreamFailures()
1347
1381
  updateConn()
@@ -1354,6 +1388,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1354
1388
  const attempt = meta.attempt++
1355
1389
  const baseDelay = Math.min(1500 * Math.pow(2, attempt), 60000)
1356
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})
1357
1392
  setReconnect(delay)
1358
1393
  clearStreamRetry(kind)
1359
1394
  meta.retryTimer = setTimeout(() => {
@@ -1366,6 +1401,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1366
1401
 
1367
1402
  /* ---------------- 轮询降级模式 ---------------- */
1368
1403
  function enterPollMode() {
1404
+ globalThis.DshDiagnostics?.record('poll.state',{status:'poll'})
1369
1405
  if (state.streamMode === 'poll') return
1370
1406
  state.streamMode = 'poll'
1371
1407
  state.pollSeq = { mux: 0, host: 0 }
@@ -1536,6 +1572,7 @@ function onMuxFrame(full) {
1536
1572
  if (f.type === 'session/jobs') { state.jobs[f.sessionId] = f.jobs || []; renderJobs(); return }
1537
1573
  if (f.type === 'session/projection') { applyProjection(f.sessionId, f.key, f.value, f.seq); return }
1538
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') }
1539
1576
  }
1540
1577
  function onHostFrame(full) {
1541
1578
  const f = full.payload
@@ -1871,7 +1908,8 @@ function sessionLabelOf(s) {
1871
1908
  }
1872
1909
  function short(id) { return '…' + String(id).slice(-8) }
1873
1910
  function isTopLevelSession(session) {
1874
- 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'
1875
1913
  }
1876
1914
  // DSH marks sessions created via "new session" but never prompted as blank and hides
1877
1915
  // them in its own UI; keep the same semantics here so they do not occupy the list,
@@ -2355,6 +2393,7 @@ async function archiveEmptySessionOnLeave(sessionId, leaving = false) {
2355
2393
  }
2356
2394
 
2357
2395
  async function openSession(id) {
2396
+ globalThis.DshDiagnostics?.record('session.open',{phase:'start',sessionId:id,server:state.server})
2358
2397
  if (state.current && state.current !== id) void archiveEmptySessionOnLeave(state.current,true)
2359
2398
  state.current = id
2360
2399
  setSessionRecovery('loading')
@@ -2372,7 +2411,13 @@ async function openSession(id) {
2372
2411
  renderSessionPending()
2373
2412
  void refreshCompactionStatus(id)
2374
2413
  getConversationView().reset()
2375
- 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
+ }
2376
2421
  if(state.current!==id||state.history!==openingHistory||!openingConnection.valid())return
2377
2422
  await loadHistory(true)
2378
2423
  renderSessionCards()
@@ -2386,19 +2431,16 @@ function sessionHasPendingActivity(sessionId, session) {
2386
2431
  || (state.queues[sessionId] || []).some(item => item?.placement !== 'context')
2387
2432
  }
2388
2433
 
2389
- async function shouldDiscardEmptySession(sessionId) {
2434
+ function shouldDiscardEmptySession(sessionId) {
2390
2435
  const session = state.byId.get(sessionId)
2391
2436
  if (!session || sessionHasPendingActivity(sessionId, session)) return false
2392
- const deadline = Date.now() + 3500
2393
- while (state.current === sessionId && state.history.loading && Date.now() < deadline) {
2394
- await new Promise(resolve => setTimeout(resolve, 25))
2395
- }
2396
- if (state.current !== sessionId || sessionHasPendingActivity(sessionId, session)) return false
2397
- 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)
2398
2440
  }
2399
2441
 
2400
2442
  async function closeSession() {
2401
- 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})
2402
2444
  const sessionId = state.current
2403
2445
  if (!sessionId) return
2404
2446
  const parentId = state.byId.get(sessionId)?.parentSessionId
@@ -2406,27 +2448,26 @@ async function closeSession() {
2406
2448
  setComposerFullscreen(false);clearComposerImages();hideComposerMenu()
2407
2449
  return openSession(parentId)
2408
2450
  }
2409
- const task = (async () => {
2410
- const discard = await shouldDiscardEmptySession(sessionId) && await archiveEmptySessionOnLeave(sessionId)
2411
- if (state.current !== sessionId) return
2412
- state.current = null
2413
- renderSessionPending()
2414
- if (discard) removeLocalSessionRecord(sessionId)
2415
- setComposerFullscreen(false)
2416
- clearComposerImages()
2417
- setSessionRecovery('idle')
2418
- $('btn-rename-session').classList.add('hidden')
2419
- $('btn-archive-session').classList.add('hidden')
2420
- state.history = emptyHistory()
2421
- document.body.classList.remove('in-session')
2422
- hideComposerMenu()
2423
- renderSessions()
2424
- renderWorkbench()
2425
- showView('view-home')
2426
- })()
2427
- closeSession.pending = task
2428
- try { await task } finally {
2429
- if (closeSession.pending === task) closeSession.pending = null
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()
2430
2471
  }
2431
2472
  }
2432
2473
 
@@ -2610,12 +2651,14 @@ function historyCacheScope() { return CACHE.history }
2610
2651
  function historySource(value) {
2611
2652
  state.history.source=value
2612
2653
  const el=$('history-source')
2613
- 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')
2614
2655
  }
2615
2656
  function getConversationView() {
2616
2657
  if(!conversationView)conversationView=new window.DshHistory.HistoryView($('history'),{
2617
2658
  html:entry=>eventHtml(entry, {toolNames:state.history.toolNames}),
2659
+ errorLabel:()=>t('history.renderFailed'),
2618
2660
  older:()=>loadHistory(false),olderLabel:()=>t('history.earlier'),loadingLabel:()=>t('history.loadingEarlier'),live:partialReasoningHtml,
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 中打开原会话。',
2619
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)},
2620
2663
  scrolled:()=>{updateRail()}
2621
2664
  })
@@ -2656,6 +2699,7 @@ function trimVisible(direction='tail') {
2656
2699
  async function loadHistory(reset = true) {
2657
2700
  const connection=captureConnection(),id=state.current,history=state.history
2658
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})
2659
2703
  const reasoningVersion=history.reasoningVersion||0,hadContent=history.visible.length>0
2660
2704
  history.loading=true
2661
2705
  if(reset){if(hadContent)historySource('syncing');else setSessionRecovery('loading')}
@@ -2667,38 +2711,58 @@ async function loadHistory(reset = true) {
2667
2711
  getConversationView().more.disabled=true
2668
2712
  getConversationView().more.textContent=getConversationView().options.loadingLabel()
2669
2713
  let v
2670
- try{v=await rpc('session.history',payload,network.readTimeout)}catch(error){
2671
- 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)
2672
2718
  history.loading=false;history.retryAfter=Date.now()+1500
2673
2719
  if(error.message==='AUTH'){authFailure();return}
2674
- 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')
2675
2722
  setSessionRecovery('error',error.message)
2723
+ getConversationView().reset?.()
2676
2724
  $('history').innerHTML='<div class="history-empty">'+esc(error.message)+'</div>'
2677
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)
2678
2730
  return
2679
2731
  }
2680
2732
  if(!connection.valid()||state.current!==id||state.history!==history)return
2681
- const liveReasoning=(history.reasoningVersion||0)!==reasoningVersion?new Map(history.partialReasoning):null
2682
- hydrateSessionProjections(id,v.projections);history.loaded=true
2683
- const incoming=v.events||[],prepared=[]
2684
- for (const entry of incoming) {
2685
- const ev=entry?.event
2686
- applyReasoningStreamEvent(ev)
2687
- if(ev?.type==='turn/start'||ev?.type==='turn/end')noteSessionTurnTime(id,ev)
2688
- if(ev?.seq==null||!shouldShowEvent(ev.type,ev))continue
2689
- prepared.push({seq:ev.seq,event:ev,view:entry.view})
2690
- }
2691
- const rawSeqs=incoming.map(entry=>entry?.event?.seq).filter(Number.isFinite),floor=rawSeqs.length?Math.min(...rawSeqs):Infinity
2692
- 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}
2693
- else{history.visible=window.DshHistory.reconcile(history.visible,prepared,floor,true,payload.beforeSeq);history.minSeq=Math.min(history.minSeq,floor)}
2694
- history.seqs=new Set(history.visible.map(entry=>entry.seq));history.headEvicted=false;trimVisible(reset?'tail':'older')
2695
- if(liveReasoning)history.partialReasoning=liveReasoning;else applyReasoningBaseline(v.partialReasoning)
2696
- history.hasMore=(!!v.hasMore||(reset&&history.headEvicted)) && rawSeqs.length>0 && (reset || floor<payload.beforeSeq)
2697
- history.loading=false;history.cached=false;historySource('synced');setSessionRecovery('ready')
2698
- renderSessionTitle();renderSessionSub();renderSessionCards()
2699
- renderHistory(!hadContent,reset?'fixed':'keep')
2700
- $('history-hint').textContent=t('history.count',{n:history.visible.length})
2701
- 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) }
2702
2766
  }
2703
2767
 
2704
2768
  function insertLiveEvent(event) {
@@ -2742,11 +2806,39 @@ function filteredEntries() {
2742
2806
  return f
2743
2807
  }
2744
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
+
2745
2837
  function renderHistory(reset=false,mode='auto') {
2746
2838
  const filtered=filteredEntries(),toolNames=new Map()
2747
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)}
2748
2840
  state.history.toolNames=toolNames
2749
- $('history-hint').textContent=t('history.count',{n:state.history.visible.length})
2841
+ $('history-hint').textContent=t('history.count',{n:state.history.visible.filter(entry=>!['turn/start','turn/end'].includes(entry.event?.type)).length})
2750
2842
  let prepared=window.DshActivity?.prepare(filtered)||filtered
2751
2843
  // 弱网精简:尚未返回的调用在完成前不展示,只留已完成的消息与工具结果。
2752
2844
  if(weakStreamTrim())prepared=prepared.filter(entry=>entry.event?.type!=='tool/call'||entry.view?.toolActivity)
@@ -2760,6 +2852,10 @@ function renderHistory(reset=false,mode='auto') {
2760
2852
  const groups = prepared.filter(entry => entry.view?.activityGroup)
2761
2853
  const activeGroup = groups.at(-1)
2762
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
+ }
2763
2859
  getConversationView().set(prepared,{reset,follow:mode==='bottom',live:partialReasoningHtml(),hasMore:state.history.hasMore,loading:state.history.loading,emptyLabel:t('history.empty')})
2764
2860
  window.DshImagePreview?.hydrate?.($('history'))
2765
2861
  }
@@ -2818,6 +2914,7 @@ function bindRail() {
2818
2914
 
2819
2915
  /* 事件 → HTML */
2820
2916
  const INTERESTING_EVENTS = new Set([
2917
+ 'turn/start', 'turn/end',
2821
2918
  'user/message', 'assistant/message',
2822
2919
  'tool/call', 'tool/result',
2823
2920
  'agent/status',
@@ -2858,6 +2955,10 @@ function eventHtml(entry, ctx = {}) {
2858
2955
  const ev = entry.event || {}
2859
2956
  const data = ev.data || {}
2860
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 ''
2861
2962
  if (entry.view?.activityGroup) return activityGroupHtml(entry.view.activityGroup, ctx)
2862
2963
  if (!shouldShowEvent(type, ev)) return ''
2863
2964
  if (window.DshActivity && isToolEvent(type)) return window.DshActivity.toolEvent(entry)
@@ -3840,15 +3941,15 @@ async function probeOverviewLinks(signal) {
3840
3941
  let timer
3841
3942
  const controller=new AbortController(),cancel=()=>controller.abort()
3842
3943
  signal.addEventListener('abort',cancel,{once:true});if(signal.aborted)controller.abort()
3843
- timer=setTimeout(cancel,4000)
3844
- 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=>{
3845
3946
  if(!response.ok)throw Error('health')
3846
3947
  const health=await response.json();if(health?.ok!==true)throw Error('health')
3847
3948
  return health
3848
3949
  }).catch(()=>null).finally(()=>{clearTimeout(timer);signal.removeEventListener('abort',cancel)})
3849
3950
  const [health,host]=await Promise.all([healthRequest,refreshHostDescription()])
3850
3951
  if(!connection.valid()||signal.aborted)throw Error('stale check')
3851
- if(health){if(host)health.upstreamReachable=true;state.gatewayHealth[base]=health}
3952
+ if(health){state.gatewayHealth[base]=health}
3852
3953
  else delete state.gatewayHealth[base]
3853
3954
  return {gateway:!!health}
3854
3955
  }
@@ -4163,7 +4264,7 @@ function renderQueue() {
4163
4264
  updateCancelBtn()
4164
4265
  updateSessionStatus()
4165
4266
  // 队列数量在会话列表已显示; 详情页不重复大 UI
4166
- $('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 })
4167
4268
  renderSessions()
4168
4269
  }
4169
4270
 
@@ -5033,7 +5134,7 @@ function announcementVoteKey(announcementId, pollId) {
5033
5134
  }
5034
5135
  function storeAnnouncementVote(announcementId, pollId, optionId) {
5035
5136
  const votes = readAnnouncementVotes()
5036
- votes[announcementVoteKey(announcementId, pollId)] = { optionId, votedAt: Date.now() }
5137
+ votes[announcementVoteKey(announcementId, pollId)] = { ...(optionId ? { optionId } : { submitted: true }), votedAt: Date.now() }
5037
5138
  const keys = Object.keys(votes)
5038
5139
  if (keys.length > 100) {
5039
5140
  keys.sort((a, b) => Number(votes[a]?.votedAt || 0) - Number(votes[b]?.votedAt || 0))
@@ -5045,6 +5146,9 @@ function storeAnnouncementVote(announcementId, pollId, optionId) {
5045
5146
  function announcementVote(item) {
5046
5147
  if (!item?.poll?.id) return null
5047
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' : '已提交' } }
5048
5152
  if (!saved?.optionId) return null
5049
5153
  const option = item.poll.options.find(entry => entry.id === saved.optionId)
5050
5154
  return option ? { ...saved, option } : null
@@ -5126,6 +5230,7 @@ function announcementVersionMatch(item) {
5126
5230
  return true
5127
5231
  }
5128
5232
  function normalizeAnnouncementPoll(value, announcementId) {
5233
+ if (window.DshAnnouncementForms) return window.DshAnnouncementForms.normalize(value, announcementId)
5129
5234
  if (!value || typeof value !== 'object') return null
5130
5235
  const id = String(value.id || announcementId || '').trim().slice(0, 120)
5131
5236
  const question = String(value.question || '').trim().slice(0, 300)
@@ -5175,7 +5280,10 @@ function renderAnnouncementPoll(item) {
5175
5280
  if (!poll) return
5176
5281
  const vote = announcementVote(item)
5177
5282
  $('announcement-poll-question').textContent = poll.question
5178
- $('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 => `
5179
5287
  <label class="announcement-poll-option">
5180
5288
  <input type="radio" name="announcement-poll-option" value="${esc(option.id)}"${vote?.optionId === option.id ? ' checked' : ''}${vote ? ' disabled' : ''}>
5181
5289
  <span><strong>${esc(option.label)}</strong>${option.description ? `<small>${esc(option.description)}</small>` : ''}</span>
@@ -5185,7 +5293,8 @@ function renderAnnouncementPoll(item) {
5185
5293
  status.classList.toggle('hidden', !vote)
5186
5294
  const submit = $('announcement-poll-submit')
5187
5295
  submit.classList.toggle('hidden', !!vote)
5188
- 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
5189
5298
  }
5190
5299
  function renderAnnouncementPagination() {
5191
5300
  const total = state.announcementItems.length
@@ -5233,19 +5342,22 @@ function showAnnouncementAt(index) {
5233
5342
  async function submitAnnouncementVote() {
5234
5343
  const item = state.announcement
5235
5344
  const poll = item?.poll
5345
+ if (!poll || state.announcementSubmitting) return
5346
+ const forms = window.DshAnnouncementForms
5236
5347
  const optionId = document.querySelector('input[name="announcement-poll-option"]:checked')?.value || ''
5237
- const option = poll?.options.find(entry => entry.id === optionId)
5238
- 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')
5239
5356
  const button = $('announcement-poll-submit')
5240
5357
  button.disabled = true
5241
- const payload = {
5242
- type: 'poll',
5243
- message: `Poll ${poll.id}: ${option.id}`,
5244
- announcementId: item.id,
5245
- pollId: poll.id,
5246
- optionId: option.id,
5247
- appVersion: state.localVersion
5248
- }
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 }
5249
5361
  try {
5250
5362
  const base = updateBase()
5251
5363
  let res = null
@@ -5262,8 +5374,8 @@ async function submitAnnouncementVote() {
5262
5374
  data = await res.json().catch(() => ({}))
5263
5375
  } catch {}
5264
5376
  }
5265
- // 没有网关地址、网关网络错误或令牌失效时,投票改走公网收集器。
5266
- if (!res || res.status === 401) {
5377
+ // 仅旧单选投票保留公网兜底;含填写内容的表单只提交当前网关。
5378
+ if ((!res || res.status === 401) && poll.legacy !== false && connection.valid()) {
5267
5379
  const directSignal = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(8000) : undefined
5268
5380
  res = await fetch(DIRECT_POLL_FEEDBACK_URL, {
5269
5381
  method: 'POST',
@@ -5274,22 +5386,29 @@ async function submitAnnouncementVote() {
5274
5386
  })
5275
5387
  data = await res.json().catch(() => ({}))
5276
5388
  }
5277
- if (res.ok && data.ok) {
5278
- 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 || '')
5279
5392
  markAnnouncementSeen(item.id)
5280
- renderAnnouncementPoll(item)
5393
+ if (valid()) renderAnnouncementPoll(item)
5281
5394
  renderAnnouncementHistory()
5282
- toast(t('announcement.voteThanks', { option: option.label }), 'ok')
5283
- } 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) {
5284
5397
  toast(t('announcement.voteAgainLater'), 'err')
5285
5398
  button.disabled = false
5286
5399
  } else {
5287
- toast(t('announcement.voteFailed', { msg: data.error || res.status }), 'err')
5400
+ toast(t('announcement.voteFailed', { msg: data.error || res?.status || t('announcement.voteNetworkError') }), 'err')
5288
5401
  button.disabled = false
5289
5402
  }
5290
5403
  } catch (e) {
5291
- 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')
5292
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
+ }
5293
5412
  }
5294
5413
  }
5295
5414
  function closeAnnouncement(markSeen) {
@@ -5743,7 +5862,14 @@ function applyBgConfigFromNative() {
5743
5862
  if (opts.some(o => o.value === v)) $('bg-interval').value = v
5744
5863
  syncCustomSelect($('bg-interval'))
5745
5864
  if ($('opt-task-done')) $('opt-task-done').checked = cfg.notifyTaskDone !== false
5746
- $('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
+ }
5747
5873
  } catch {}
5748
5874
  }
5749
5875
  function saveBgConfig(enabled) {
@@ -5752,12 +5878,13 @@ function saveBgConfig(enabled) {
5752
5878
  const base = bgBase()
5753
5879
  const intervalMin = parseFloat($('bg-interval')?.value || '0.5') || 0.5
5754
5880
  const notifyTaskDone = $('opt-task-done')?.checked !== false
5755
- 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
5756
5882
  if (enabled) $('bg-auth-status')?.classList.add('hidden')
5757
- return true
5883
+ return saved
5758
5884
  }
5759
5885
  function syncBgConfig() {
5760
5886
  if ($('opt-bg-poll')?.checked && state.token) saveBgConfig(true)
5887
+ void syncPeakReminders()
5761
5888
  }
5762
5889
 
5763
5890
  /* ---------------- 预设提示词 ---------------- */
@@ -5832,7 +5959,7 @@ function deletePreset(id) {
5832
5959
  toast(t('presets.deleted'), 'ok')
5833
5960
  }
5834
5961
 
5835
- /* ---------------- 旧峰谷提醒清理(现由 dsh-cost-meter 管理) ---------------- */
5962
+ /* ---------------- 插件规则驱动的 Android 峰谷通知 ---------------- */
5836
5963
  const LEGACY_PEAK_NOTIFICATION_IDS = [8801, 8802, 8803, 8804]
5837
5964
 
5838
5965
  async function cancelLegacyPeakNotifications() {
@@ -5852,6 +5979,7 @@ async function cancelPeakReminders() {
5852
5979
  if (!CAP?.isNativePlatform?.()) return false
5853
5980
  const legacyCleaned = await cancelLegacyPeakNotifications()
5854
5981
  const b = bgBridge()
5982
+ if (b?.savePeakReminderConfig) return b.savePeakReminderConfig(JSON.stringify({ enabled: false })) !== false && legacyCleaned
5855
5983
  if (!b?.stopPeakReminder) return false
5856
5984
  try {
5857
5985
  const stopped = b.stopPeakReminder() !== false
@@ -5860,9 +5988,42 @@ async function cancelPeakReminders() {
5860
5988
  }
5861
5989
 
5862
5990
  async function restorePeakReminders() {
5863
- // dsh-cost-meter owns reminders. Retire both legacy scheduling mechanisms.
5864
- LS.del('peakRemind')
5865
- await cancelPeakReminders()
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
+ }
5866
6027
  }
5867
6028
 
5868
6029
  /* ---------------- 模型设置 ---------------- */
@@ -6986,7 +7147,7 @@ function renderDshControlOperation(operation) {
6986
7147
  const desc = $('dsh-control-desc')
6987
7148
  const box = $('dsh-control-steps')
6988
7149
  if (!desc || !box || !operation) return
6989
- const failed = operation.stage === 'failed' || operation.done && operation.ok === false
7150
+ const failed = operation.stage !== 'unknown' && (operation.stage === 'failed' || operation.done && operation.ok === false)
6990
7151
  desc.textContent = failed ? t('settings.dshFailed', { msg: dshControlFailureText(operation) }) : dshControlStageText(operation)
6991
7152
  const steps = Array.isArray(operation.steps) && operation.steps.length
6992
7153
  ? operation.steps
@@ -7012,20 +7173,45 @@ async function readDshControlResponse(res) {
7012
7173
  try { return JSON.parse(text) } catch { return { error: `HTTP ${res.status}`, detail: text.slice(0, 500) } }
7013
7174
  }
7014
7175
 
7015
- 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()) {
7016
7183
  let value = initial
7017
- 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) {
7018
7188
  renderDshControlOperation(value)
7019
7189
  if (value.done) return value
7020
- await new Promise(resolvePromise => setTimeout(resolvePromise, 700))
7021
- const res = await fetch(adminApiUrl(`/admin/api/dsh?operation=${encodeURIComponent(operationId)}`), {
7022
- headers: { authorization: 'Bearer ' + state.token }, cache: 'no-store'
7023
- })
7024
- if (res.status === 401) { authFailure(); throw Object.assign(new Error('unauthorized'), { auth: true }) }
7025
- const next = await readDshControlResponse(res)
7026
- if (!res.ok) throw Object.assign(new Error(next.error || next.message || `HTTP ${res.status}`), { dshPayload: { ...next, httpStatus: res.status } })
7027
- 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
+ }
7028
7213
  }
7214
+ return context.valid() ? { ...value, done: true, ok: false, stage: 'unknown', code: 'RESULT_UNKNOWN', message: t('settings.dshResultUnknown') } : null
7029
7215
  }
7030
7216
 
7031
7217
  function renderDshControlStatus(value) {
@@ -7056,6 +7242,7 @@ function renderDshControlStatus(value) {
7056
7242
 
7057
7243
  async function loadDshControl() {
7058
7244
  if (!state.token || !$('dsh-control-desc')) return
7245
+ const context = dshControlContext()
7059
7246
  if (activeGatewayCapability('dshLifecycle') === false) {
7060
7247
  renderDshControlStatus({
7061
7248
  supported: false,
@@ -7064,43 +7251,62 @@ async function loadDshControl() {
7064
7251
  return
7065
7252
  }
7066
7253
  try {
7067
- 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
7068
7256
  if (res.status === 401) return authFailure()
7069
7257
  const value = await readDshControlResponse(res)
7258
+ if (!context.valid()) return
7070
7259
  if (!res.ok) throw Object.assign(new Error(value.error || value.message || `HTTP ${res.status}`), { dshPayload: value })
7260
+ if (dshControlPollPromise && dshControlPollContext?.valid()) return
7071
7261
  renderDshControlStatus(value)
7072
- if (value.operation?.operationId && !value.operation.done && !dshControlPollPromise) {
7073
- dshControlPollPromise = pollDshControlOperation(value.operation.operationId, value.operation)
7074
- .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) })
7075
7266
  .catch(error => {
7076
- 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') })
7077
7268
  })
7078
- .finally(() => { dshControlPollPromise = null; dshControlButtonsBusy(false, true) })
7269
+ .finally(() => { if (dshControlPollPromise === job) { dshControlPollPromise = null; if (context.valid()) void loadDshControl() } })
7270
+ dshControlPollPromise = job
7079
7271
  }
7080
7272
  } catch (error) {
7273
+ if (!context.valid()) return
7081
7274
  $('dsh-control-desc').textContent = t('settings.dshStatusFailed', { msg: error?.dshPayload ? dshControlFailureText(error.dshPayload) : t('conn.off') })
7082
7275
  }
7083
7276
  }
7084
7277
 
7085
7278
  async function controlDsh(action) {
7086
- 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
7087
7284
  const label = action === 'start' ? t('settings.dshStart') : t('settings.dshRestart')
7088
7285
  dshControlButtonsBusy(true, true)
7089
7286
  renderDshControlOperation({ action, service: 'dsh-web', accepted: true, done: false, stage: 'queued', elapsedMs: 0, steps: [] })
7090
7287
  try {
7091
- const res = await fetch(adminApiUrl('/admin/api/dsh'), {
7288
+ let res
7289
+ try { res = await fetch(context.url, {
7092
7290
  method: 'POST',
7093
- headers: { authorization: 'Bearer ' + state.token, 'content-type': 'application/json' },
7094
- body: JSON.stringify({ action }),
7095
- })
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
7096
7300
  if (res.status === 401) return authFailure()
7097
7301
  let v = await readDshControlResponse(res)
7302
+ if (!context.valid()) return
7098
7303
  if (res.status === 409 && v.operation?.operationId) v = v.operation
7099
7304
  else if (!res.ok) throw Object.assign(new Error(v.error || v.message || `HTTP ${res.status}`), { dshPayload: { ...v, httpStatus: res.status } })
7100
7305
 
7101
7306
  if (v.accepted && v.operationId) {
7102
- dshControlPollPromise = pollDshControlOperation(v.operationId, v)
7103
- 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 }
7104
7310
  if (!v.ok) throw Object.assign(new Error(dshControlFailureText(v)), { dshPayload: v })
7105
7311
  renderDshControlOperation(v)
7106
7312
  toast(dshControlStageText(v), 'ok')
@@ -7112,6 +7318,7 @@ async function controlDsh(action) {
7112
7318
  renderDshControlStatus(v)
7113
7319
  toast(t('settings.dshStarted', { action: label }), 'ok')
7114
7320
  } catch (error) {
7321
+ if (!context.valid()) return
7115
7322
  if (error?.auth) return
7116
7323
  const payload = error?.dshPayload
7117
7324
  const message = payload ? dshControlFailureText(payload) : t('settings.dshResultUnknown')
@@ -7119,8 +7326,8 @@ async function controlDsh(action) {
7119
7326
  else $('dsh-control-desc').textContent = t('settings.dshFailed', { msg: message })
7120
7327
  toast(t('settings.dshFailed', { msg: message }), 'err')
7121
7328
  } finally {
7122
- dshControlPollPromise = null
7123
- dshControlButtonsBusy(false, true)
7329
+ release()
7330
+ if (dshControlPollPromise === busy) { dshControlPollPromise = null; if (context.valid()) void loadDshControl() }
7124
7331
  }
7125
7332
  }
7126
7333
 
@@ -7213,7 +7420,7 @@ function bindUi() {
7213
7420
  if (state.current) { renderSessionTitle(); renderSessionSub(); renderSessionCards(); renderHistory(true) }
7214
7421
  else renderModelMenu()
7215
7422
  loadLocalVersion()
7216
- 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)
7217
7424
  $('token-desc').textContent = state.token ? t('token.savedLocal') : t('token.notSet')
7218
7425
  })
7219
7426
  $('btn-theme').addEventListener('click', openThemePanel)
@@ -7499,7 +7706,16 @@ function bindUi() {
7499
7706
  $('announcement-next').addEventListener('click', () => showAnnouncementAt(state.announcementIndex + 1))
7500
7707
  $('announcement-later').addEventListener('click', () => closeAnnouncement(false))
7501
7708
  $('announcement-confirm').addEventListener('click', () => closeAnnouncement(true))
7502
- $('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)
7503
7719
  $('announcement-poll-submit').addEventListener('click', submitAnnouncementVote)
7504
7720
  $('modal-announcement').addEventListener('click', (e) => {
7505
7721
  if (e.target === $('modal-announcement') && !state.announcementItems.some(item => item.force)) closeAnnouncement(false)
@@ -7619,6 +7835,16 @@ function bindUi() {
7619
7835
  $('btn-announcement-history').addEventListener('click', openAnnouncementHistory)
7620
7836
  // 启动时清理旧版 LocalNotifications 和前台提醒服务,提醒交给 dsh-cost-meter。
7621
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
+ })
7622
7848
  applyBgConfigFromNative()
7623
7849
  $('opt-bg-poll').addEventListener('change', async (e) => {
7624
7850
  if (e.target.checked) {
@@ -7632,8 +7858,9 @@ function bindUi() {
7632
7858
  }
7633
7859
  const ok = await ensureNotify()
7634
7860
  if (!ok) { e.target.checked = false; return toast(t('settings.notifyDenied')) }
7635
- saveBgConfig(true)
7636
- 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')
7637
7864
  } else {
7638
7865
  saveBgConfig(false)
7639
7866
  toast(t('settings.bgOff'), 'ok')
@@ -7794,6 +8021,7 @@ async function clearWorkflowData(kind) {
7794
8021
  return toast(english ? 'History cache cleared' : '历史缓存已清除', 'ok')
7795
8022
  }
7796
8023
  window.NativeBackground?.saveBackgroundConfig?.(JSON.stringify({ enabled:false, base:'', token:'', clientId:'', intervalMin:1, notifyTaskDone:false }))
8024
+ window.NativeBackground?.savePeakReminderConfig?.(JSON.stringify({ enabled:false }))
7797
8025
  window.NativeBackground?.setPendingNotificationsEnabled?.(false)
7798
8026
  if (kind === 'connection') {
7799
8027
  const current = currentServerEntry()
@@ -7817,7 +8045,19 @@ function openPluginPage(route = 'manage') {
7817
8045
  return
7818
8046
  }
7819
8047
  window.DshExtensions.mount({
7820
- 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)),
7821
8061
  back: () => showView('view-settings'),
7822
8062
  openContext: () => void openInsights('context', true),
7823
8063
  returnToSession: () => showView('view-session'), scrollTop: () => window.scrollTo(0,0),
@@ -7826,3 +8066,6 @@ function openPluginPage(route = 'manage') {
7826
8066
  valid: connection.valid,
7827
8067
  }, $('plugin-page'), route)
7828
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()})})