dsh-remote-plugin 0.8.0 → 0.8.2

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
@@ -11,7 +11,7 @@ const DIRECT_POLL_FEEDBACK_URL = 'https://vm-0-2-ubuntu.tail1f6fc4.ts.net/submit
11
11
  /* ---------------- 状态 ---------------- */
12
12
  const LS = {
13
13
  get(k, d) { try { return localStorage.getItem(k) ?? d } catch { return d } },
14
- set(k, v) { try { localStorage.setItem(k, v) } catch {} },
14
+ set(k, v) { try { localStorage.setItem(k, v); return true } catch(error) { try { globalThis.DshDiagnostics?.storageFailure(k,error) } catch {} return false } },
15
15
  del(k) { try { localStorage.removeItem(k) } catch {} }
16
16
  }
17
17
  const CLIENT_ID = (() => {
@@ -137,6 +137,8 @@ for (const key of ['server', 'token']) {
137
137
  window.DshInsights?.close()
138
138
  window.DshExtensions?.close()
139
139
  window.DshExtensions?.invalidateCapabilities()
140
+ window.DshFileInbox?.reset()
141
+ window.DshSessionDeck?.reset()
140
142
  if (typeof document !== 'undefined') document.getElementById('btn-insights')?.classList.add('hidden')
141
143
  if(typeof document!=='undefined') {
142
144
  const identityGeneration=connectionGeneration
@@ -328,6 +330,7 @@ async function copyText(text) {
328
330
  } catch { return false }
329
331
  }
330
332
  function openFeedbackSheet() {
333
+ window.DshExtensions?.closeShortcuts()
331
334
  $('feedback-backdrop').classList.remove('hidden')
332
335
  $('feedback-sheet').classList.remove('hidden')
333
336
  $('btn-feedback').setAttribute('aria-expanded', 'true')
@@ -404,14 +407,16 @@ function closeFeedbackSuccess() {
404
407
  $('btn-feedback')?.focus()
405
408
  }
406
409
  async function loadCrashPreview() {
410
+ const generation=loadCrashPreview.generation=(loadCrashPreview.generation||0)+1
407
411
  const connection=captureConnection(),preview=$('fb-crash-preview')
408
412
  preview.textContent=t('feedback.crashLoading')
409
- try {
410
- const response=await fetch(updateBase()+'/crash-logs',{headers:{authorization:'Bearer '+connection.token},signal:AbortSignal.timeout(5000),cache:'no-store'})
411
- if(!response.ok)throw new Error('unavailable')
412
- const data=await response.json()
413
- if(connection.valid())preview.textContent=JSON.stringify(data.upload,null,2)
414
- }catch{if(connection.valid())preview.textContent=t('feedback.crashUnavailable')}
413
+ const selected=$('fb-include-diagnostics').checked,crashes=$('fb-include-crashes').checked
414
+ if(!selected&&!crashes){preview.textContent=I18N.lang==='en'?'Select a log option above to preview the attachment.':'勾选上方日志选项后,可在这里预览拟上传的附件。';return}
415
+ const read=async route=>{try{const response=await fetch(updateBase()+route,{headers:{authorization:'Bearer '+connection.token},signal:AbortSignal.timeout(5000),cache:'no-store'});if(!response.ok)throw Error();return await response.json()}catch{return {unavailable:true}}}
416
+ const evidence={}
417
+ if(selected){evidence.client=globalThis.DshDiagnostics?.report();evidence.gateway=await read('/diagnostics')}
418
+ if(crashes){const data=await read('/crash-logs');evidence.crashes=data.upload||data}
419
+ if(connection.valid()&&generation===loadCrashPreview.generation)preview.textContent=JSON.stringify(evidence,null,2)
415
420
  }
416
421
  async function submitFeedback() {
417
422
  const type = state.feedbackType || 'bug'
@@ -419,6 +424,7 @@ async function submitFeedback() {
419
424
  const contact = $('fb-contact').value.trim()
420
425
  const includeDiagnostics = $('fb-include-diagnostics').checked
421
426
  const includeCrashLogs = $('fb-include-crashes').checked
427
+ const clientDiagnostics=includeDiagnostics?globalThis.DshDiagnostics?.report():null
422
428
  if (!message) { toast(t('feedback.empty'), 'err'); return }
423
429
  if (message.length > 2000) { toast(t('feedback.tooLong'), 'err'); return }
424
430
  const btn = $('fb-submit')
@@ -430,12 +436,16 @@ async function submitFeedback() {
430
436
  const res = await fetch(base + '/feedback', {
431
437
  method: 'POST',
432
438
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token },
433
- body: JSON.stringify({ type, message, contact, appVersion: state.localVersion, includeDiagnostics, includeCrashLogs })
439
+ body: JSON.stringify({ type, message, contact, appVersion: state.localVersion, includeDiagnostics, includeCrashLogs,...(clientDiagnostics?{clientDiagnostics}:{}) })
434
440
  })
435
441
  diagnostic?.end({phase:res.ok?'complete':'failed',httpStatus:res.status})
436
442
  let json = {}
437
443
  try { json = await res.json() } catch {}
438
- if (res.ok && json.ok) { closeFeedbackModal(); openFeedbackSuccess() }
444
+ if (res.ok && json.ok) { closeFeedbackModal(); openFeedbackSuccess()
445
+ const status=$('feedback-diagnostics-status'),saved=json.diagnostics?.saved===true&&json.diagnostics.reportId===clientDiagnostics?.reportId
446
+ status.textContent=clientDiagnostics?(saved?(I18N.lang==='en'?'Diagnostic report saved. ID: ':'诊断日志已保存,编号:')+clientDiagnostics.reportId:(I18N.lang==='en'?'Feedback received, but the server did not confirm the complete diagnostic report. Copy or export the local log to supplement it.':'反馈已收到,但服务器未确认完整诊断日志已保存。请复制或导出本地日志补充。')):''
447
+ status.classList.toggle('hidden',!clientDiagnostics)
448
+ }
439
449
  else if (res.status === 429) { toast(json.retryAfter ? t('feedback.rateLimitedAt', { n: json.retryAfter }) : t('feedback.rateLimited'), 'err') }
440
450
  else { toast(t('feedback.submitFailed', { msg: json.error || res.status }), 'err') }
441
451
  } catch(error) {
@@ -1530,6 +1540,16 @@ async function pollKind(kind, cancellation) {
1530
1540
  if (state.current) void resyncCurrentSession()
1531
1541
  }
1532
1542
  if (data.epoch) cursors[kind + 'Epoch'] = data.epoch
1543
+ // The fallback poll may contain a request and its resolution together. Seed
1544
+ // native tombstones first, including before the pending baseline is replayed.
1545
+ if (kind === 'mux' && typeof window !== 'undefined' && window.NativeBackground?.handlePendingEvent) {
1546
+ for (const item of data.events) {
1547
+ const payload = item.event?.payload
1548
+ if (item.seq > (reset ? 0 : since) && ['approval/resolved', 'question/resolved'].includes(payload?.type)) {
1549
+ window.NativeBackground.handlePendingEvent(bgBase(), state.token || '', JSON.stringify(item.event), false)
1550
+ }
1551
+ }
1552
+ }
1533
1553
  for (const frame of data.baseline || []) { if (kind === 'mux') onMuxFrame(frame); else onHostFrame(frame) }
1534
1554
  for (const item of data.events) {
1535
1555
  if (item.seq > (state.pollSeq[kind] || 0)) {
@@ -1651,6 +1671,7 @@ function onMuxFrame(full) {
1651
1671
  function onHostFrame(full) {
1652
1672
  const f = full.payload
1653
1673
  if (!f) return
1674
+ if (['host/session-status', 'host/agent-error'].includes(f.type) && typeof window !== 'undefined' && window.NativeBackground?.handleTaskEvent) window.NativeBackground.handleTaskEvent(bgBase(), state.token || '', JSON.stringify(full), f.replay === true)
1654
1675
  if (['host/session-added', 'host/session-removed', 'host/workspace-changed', 'host/workspace-removed', 'host/workspace-order-changed', 'host/archived-sessions-changed'].includes(f.type)) return scheduleRefresh()
1655
1676
  if (f.type === 'host/session-activity') {
1656
1677
  const session = state.byId.get(f.sessionId)
@@ -1796,6 +1817,7 @@ function observeCompactionEvent(sessionId, event, meta = {}) {
1796
1817
 
1797
1818
  function onSessionEvent(sessionId, event, meta = {}) {
1798
1819
  if (!event) return
1820
+ if (['agent/status', 'agent/error', 'turn/start', 'turn/end', 'goal/completed'].includes(event.type) && typeof window !== 'undefined' && window.NativeBackground?.handleTaskEvent) window.NativeBackground.handleTaskEvent(bgBase(), state.token || '', JSON.stringify({ payload: { sessionId, event } }), meta.replay === true)
1799
1821
  const s = state.byId.get(sessionId)
1800
1822
  observeCompactionEvent(sessionId, event, meta)
1801
1823
  if (event.type === 'turn/start' || event.type === 'turn/end') {
@@ -2595,6 +2617,8 @@ function bindNativeBack() {
2595
2617
  if (customSelectCurrent) { closeCustomSelect(); return }
2596
2618
  if (groupDrawerOpen()) { closeGroupDrawer(); return }
2597
2619
  if (typeof window !== 'undefined' && window.DshImagePreview?.isOpen?.()) { window.DshImagePreview.close(); return }
2620
+ if (typeof window !== 'undefined' && window.DshExtensions?.closeShortcuts(true)) return
2621
+ if (typeof window !== 'undefined' && window.DshFileInbox?.close()) return
2598
2622
  const dialog = document.querySelector('dialog[open]')
2599
2623
  if (dialog) { dialog.close(); return }
2600
2624
  const openModal = [...document.querySelectorAll('.modal')].find(m => !m.classList.contains('hidden'))
@@ -3153,7 +3177,7 @@ function blockHtml(b,index=0,context={}) {
3153
3177
  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)})})
3154
3178
  }
3155
3179
  switch (b.type) {
3156
- case 'text': return `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '', { fileLinks: true, imageLabel: t('block.image') }) : esc(b.text ?? '')}</div>`
3180
+ case 'text': return window.DshActivity.hasVisibleText(b.text) ? `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '', { fileLinks: true, imageLabel: t('block.image') }) : esc(b.text ?? '')}</div>` : ''
3157
3181
  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>`
3158
3182
  case 'image': {
3159
3183
  if (b.attachment && window.DshImagePreview) return window.DshImagePreview.attachmentHtml(b.attachment, t('block.image'), state.current)
@@ -3246,27 +3270,25 @@ async function renderSessionCards() {
3246
3270
 
3247
3271
  if (goal && !isGoalTerminal(goal)) {
3248
3272
  const collapsed = isGoalCollapsed(sessionId, goal)
3249
- html += `<div class="goal-disclosure${collapsed ? ' is-collapsed' : ''}">
3273
+ html += `<div data-deck-kind="goal" class="goal-disclosure${collapsed ? ' is-collapsed' : ''}">
3250
3274
  <div id="goal-panel-mobile" class="card goal-card${collapsed ? ' hidden' : ''}">
3251
- <div class="goal-card-head"><div class="card-title">${t('goal.title')}</div>
3275
+ <div class="goal-card-head"><div class="card-title">${esc(window.DshSessionDeck?.goalState(goal.phase) || goal.phase || t('goal.title'))}</div>
3252
3276
  <button type="button" class="goal-collapse-btn" data-goal-collapse="1" aria-expanded="true" aria-controls="goal-panel-mobile" title="${esc(t('goal.collapse'))}"><span aria-hidden="true">›</span>${t('goal.collapseShort')}</button>
3253
3277
  </div>
3254
3278
  <div class="goal-obj">${esc(goal.objective || '')}</div>
3255
- <div class="goal-phase">phase: ${esc(goal.phase || '?')} · revision ${goal.revision ?? '?'}</div>
3256
3279
  <div class="goal-actions">
3257
3280
  ${goal.phase === 'active' ? '<button class="mini-btn" data-goal="pause">' + t('goal.pause') + '</button>' : '<button class="mini-btn" data-goal="resume">' + t('goal.resume') + '</button>'}
3258
3281
  <button class="mini-btn" data-goal="complete">${t('goal.complete')}</button>
3259
- <button class="mini-btn" data-goal="edit">${t('goal.edit')}</button>
3260
- <button class="mini-btn" data-goal="clear">${t('goal.clear')}</button>
3282
+ <details class="deck-more" data-deck-details="goal-${esc(goal.id || '')}"><summary>${I18N.lang === 'en' ? 'More' : '更多'}</summary><div class="deck-full-content">${esc(goal.objective || '')}<p>revision ${esc(goal.revision ?? '?')}</p></div><div class="goal-actions"><button class="mini-btn" data-goal="edit">${t('goal.edit')}</button><button class="mini-btn" data-goal="clear">${t('goal.clear')}</button></div></details>
3261
3283
  </div>
3262
3284
  </div>
3263
3285
  <button type="button" class="goal-side-tab${collapsed ? '' : ' hidden'}" data-goal-collapse="0" aria-expanded="false" aria-controls="goal-panel-mobile" aria-label="${esc(t('goal.expand'))}" title="${esc(t('goal.expand'))}"><span aria-hidden="true">‹</span><span>${t('goal.title')}</span><small>${t('goal.collapsedHint')}</small></button>
3264
3286
  </div>`
3265
3287
  }
3266
3288
  if (todos?.items?.length) {
3267
- html += `<div class="card"><div class="card-title">${t('todos.title')}</div>${todos.items.map(t =>
3289
+ html += `<div data-deck-kind="todos" class="card">${window.DshSessionDeck?.taskHtml(todos.items) || `<div class="card-title">${t('todos.title')}</div>${todos.items.map(t =>
3268
3290
  `<div><span class="pill ${t.status === 'completed' ? 'done' : t.status === 'in_progress' ? 'active' : ''}">${esc(t.status || 'pending')}</span>${esc(t.content || '')}</div>`
3269
- ).join('')}</div>`
3291
+ ).join('')}`}</div>`
3270
3292
  }
3271
3293
  box.innerHTML = html
3272
3294
  box.querySelectorAll('[data-goal]').forEach(btn =>
@@ -4358,13 +4380,14 @@ function renderPending() {
4358
4380
 
4359
4381
  function approvalDetail(a) {
4360
4382
  const lines = []
4361
- if (a?.reason) lines.push(String(a.reason))
4383
+ if (a?.reason) lines.push(window.DshApprovalRecords?.displayReason(a.reason) || String(a.reason))
4362
4384
  if (a?.arguments !== undefined) lines.push(safeJson(a.arguments))
4363
4385
  if (a?.callId) lines.push(`callId: ${a.callId}`)
4364
4386
  return lines.join('\n') || t('pending.noReason')
4365
4387
  }
4366
4388
 
4367
4389
  function renderSessionPending() {
4390
+ window.DshFileInbox?.render()
4368
4391
  const box = $('session-pending')
4369
4392
  if (!box) return
4370
4393
  const sessionId = state.current
@@ -4375,11 +4398,11 @@ function renderSessionPending() {
4375
4398
  box.classList.toggle('hidden', !sessionId || !items.length)
4376
4399
  if (!sessionId || !items.length) { box.innerHTML = ''; return }
4377
4400
  box.innerHTML = `<div class="session-pending-head"><span>${esc(t('overview.attention'))}</span><span>${esc(t('pending.count', { n: items.length }))}</span></div><div class="session-pending-list">${items.map(({ kind, item }) => {
4378
- if (kind === 'approval') return `<article class="pending-card approval" data-session-approval="${esc(item.approvalId)}">
4401
+ if (kind === 'approval') return `<article class="pending-card approval" data-session-approval="${esc(item.approvalId)}">${window.DshSessionDeck?.approvalHtml(item, approvalDetail(item)) || `
4379
4402
  <div class="pc-title">${esc(item.toolName || t('tool.default'))}</div>
4380
4403
  <div class="pc-desc">${esc(approvalDetail(item))}</div>
4381
4404
  <div class="goal-actions"><button type="button" class="mini-btn" data-session-approve="1">${t('pending.allow')}</button><button type="button" class="mini-btn" data-session-approve="0">${t('pending.reject')}</button></div>
4382
- </article>`
4405
+ `}</article>`
4383
4406
  return `<button type="button" class="pending-card question" data-session-question="${esc(item.rpcId)}" aria-haspopup="dialog">
4384
4407
  <span class="question-card-head"><span class="pc-title">❓ ${esc(item.questions?.[0]?.header || t('notify.questionTitle'))}</span><span class="mini-btn">${t('pending.answer')}</span></span>
4385
4408
  <span class="question-summary">${esc(questionSummary(item))}</span>
@@ -5404,9 +5427,61 @@ const ANNOUNCEMENTS_POLL_MS = 30 * 1000
5404
5427
  let announcementCheckPromise = null
5405
5428
  let announcementPollTimer = null
5406
5429
  let announcementPollingStarted = false
5430
+ // LS.set silently tolerates quota/security errors. Keep failed writes available to
5431
+ // the UI, and use sessionStorage so a page reload can retain the acknowledgement.
5432
+ const announcementStorageFallback = new Map()
5433
+ function clearAnnouncementFallback(key) {
5434
+ announcementStorageFallback.delete(key)
5435
+ try { sessionStorage.removeItem(key) } catch {}
5436
+ }
5437
+ function readAnnouncementStorage(key, fallback) {
5438
+ const saved = LS.get(key, null)
5439
+ let pending = announcementStorageFallback.get(key)
5440
+ if (!pending) {
5441
+ try { pending = JSON.parse(sessionStorage.getItem(key) || 'null') } catch {}
5442
+ if (!pending || typeof pending.value !== 'string' || !(pending.previous === null || typeof pending.previous === 'string')) pending = null
5443
+ }
5444
+ if (pending) {
5445
+ // Honor a newer persistent value written by another page, including recovery
5446
+ // of our own failed write. A blocked read may still return null.
5447
+ if (saved !== null && saved !== pending.previous) {
5448
+ clearAnnouncementFallback(key)
5449
+ return saved
5450
+ }
5451
+ announcementStorageFallback.set(key, pending)
5452
+ return pending.value
5453
+ }
5454
+ return saved ?? fallback
5455
+ }
5456
+ function writeAnnouncementStorage(key, value) {
5457
+ try { LS.set(key, value) } catch {}
5458
+ const saved = LS.get(key, null)
5459
+ if (saved === value) {
5460
+ clearAnnouncementFallback(key)
5461
+ return
5462
+ }
5463
+ const pending = { previous: saved, value }
5464
+ const alreadyFailed = announcementStorageFallback.has(key)
5465
+ announcementStorageFallback.set(key, pending)
5466
+ let backend = 'memory'
5467
+ try {
5468
+ sessionStorage.setItem(key, JSON.stringify(pending))
5469
+ backend = 'session'
5470
+ } catch {}
5471
+ if (!alreadyFailed) globalThis.DshDiagnostics?.record('announcement.storage', {
5472
+ phase: 'failed', storageBackend: backend,
5473
+ storageKey: key === ANNOUNCEMENTS_KEY ? 'seen' : key === ANNOUNCEMENT_HISTORY_KEY ? 'history' : 'votes'
5474
+ })
5475
+ }
5476
+ function resetAnnouncementStorage() {
5477
+ for (const key of [ANNOUNCEMENTS_KEY, ANNOUNCEMENT_HISTORY_KEY, ANNOUNCEMENT_VOTES_KEY]) {
5478
+ LS.del(key)
5479
+ clearAnnouncementFallback(key)
5480
+ }
5481
+ }
5407
5482
  function readSeenAnnouncements() {
5408
5483
  try {
5409
- const value = JSON.parse(LS.get(ANNOUNCEMENTS_KEY, '{}'))
5484
+ const value = JSON.parse(readAnnouncementStorage(ANNOUNCEMENTS_KEY, '{}'))
5410
5485
  return value && typeof value === 'object' && !Array.isArray(value) ? value : {}
5411
5486
  } catch { return {} }
5412
5487
  }
@@ -5421,13 +5496,13 @@ function markAnnouncementsSeen(items) {
5421
5496
  keys.sort((a, b) => Number(seen[a]) - Number(seen[b]))
5422
5497
  for (const key of keys.slice(0, keys.length - 100)) delete seen[key]
5423
5498
  }
5424
- LS.set(ANNOUNCEMENTS_KEY, JSON.stringify(seen))
5499
+ writeAnnouncementStorage(ANNOUNCEMENTS_KEY, JSON.stringify(seen))
5425
5500
  renderAnnouncementBoard()
5426
5501
  }
5427
5502
  function markAnnouncementSeen(id) { markAnnouncementsSeen([id]) }
5428
5503
  function readAnnouncementVotes() {
5429
5504
  try {
5430
- const value = JSON.parse(LS.get(ANNOUNCEMENT_VOTES_KEY, '{}'))
5505
+ const value = JSON.parse(readAnnouncementStorage(ANNOUNCEMENT_VOTES_KEY, '{}'))
5431
5506
  return value && typeof value === 'object' && !Array.isArray(value) ? value : {}
5432
5507
  } catch { return {} }
5433
5508
  }
@@ -5442,7 +5517,7 @@ function storeAnnouncementVote(announcementId, pollId, optionId) {
5442
5517
  keys.sort((a, b) => Number(votes[a]?.votedAt || 0) - Number(votes[b]?.votedAt || 0))
5443
5518
  for (const key of keys.slice(0, keys.length - 100)) delete votes[key]
5444
5519
  }
5445
- LS.set(ANNOUNCEMENT_VOTES_KEY, JSON.stringify(votes))
5520
+ writeAnnouncementStorage(ANNOUNCEMENT_VOTES_KEY, JSON.stringify(votes))
5446
5521
  renderAnnouncementBoard()
5447
5522
  }
5448
5523
  function announcementVote(item) {
@@ -5457,7 +5532,7 @@ function announcementVote(item) {
5457
5532
  }
5458
5533
  function readAnnouncementHistory() {
5459
5534
  try {
5460
- const value = JSON.parse(LS.get(ANNOUNCEMENT_HISTORY_KEY, '[]'))
5535
+ const value = JSON.parse(readAnnouncementStorage(ANNOUNCEMENT_HISTORY_KEY, '[]'))
5461
5536
  return Array.isArray(value) ? value.filter(item => item && typeof item.id === 'string') : []
5462
5537
  } catch { return [] }
5463
5538
  }
@@ -5465,7 +5540,7 @@ function storeAnnouncementHistory(items) {
5465
5540
  const merged = new Map(readAnnouncementHistory().map(item => [item.id, item]))
5466
5541
  for (const item of items) if (item?.id) merged.set(item.id, item)
5467
5542
  const list = [...merged.values()].sort((a, b) => Number(b.publishedAt || 0) - Number(a.publishedAt || 0)).slice(0, 50)
5468
- LS.set(ANNOUNCEMENT_HISTORY_KEY, JSON.stringify(list))
5543
+ writeAnnouncementStorage(ANNOUNCEMENT_HISTORY_KEY, JSON.stringify(list))
5469
5544
  return list
5470
5545
  }
5471
5546
  function announcementBoardItems() {
@@ -5493,7 +5568,7 @@ function renderAnnouncementBoard() {
5493
5568
  return `<button class="overview-announcement-card ${poll ? 'poll' : 'notice'}" type="button" data-home-announcement="${esc(item.id)}">
5494
5569
  <span class="overview-announcement-meta"><span class="overview-announcement-badge">${esc(t(poll ? 'overview.communityPoll' : 'overview.communityNotice'))}</span><span class="overview-announcement-new">${esc(t('overview.communityNew'))}</span><span class="overview-announcement-date">${esc(date)}</span></span>
5495
5570
  <span class="overview-announcement-title">${esc(item.title)}</span>
5496
- <span class="overview-announcement-copy">${esc(item.content)}</span>
5571
+ <span class="overview-announcement-copy">${esc(item.summary || item.content)}</span>
5497
5572
  <span class="overview-announcement-footer"><span>${esc(action)}</span><span aria-hidden="true">›</span></span>
5498
5573
  </button>`
5499
5574
  }).join('')
@@ -5513,7 +5588,7 @@ function renderAnnouncementHistory() {
5513
5588
  const pollAction = item.poll ? (vote
5514
5589
  ? `<div class="announcement-poll-status">${esc(t('announcement.voteThanks', { option: vote.option.label }))}</div>`
5515
5590
  : `<button class="mini-btn" type="button" data-announcement-poll="${esc(item.id)}">${esc(t('announcement.voteFromHistory'))}</button>`) : ''
5516
- return `<details class="announcement-history-item"><summary><span>${esc(item.title)}</span><small>${esc(date)}</small></summary><div class="announcement-history-content">${esc(item.content).replace(/\r?\n/g, '<br>')}${action}${pollAction}</div></details>`
5591
+ return `<details class="announcement-history-item"><summary><span>${esc(item.title)}</span><small>${esc(date)}</small></summary><div class="announcement-history-content">${announcementBodyHtml(item)}${action}${pollAction}</div></details>`
5517
5592
  }).join('')
5518
5593
  }
5519
5594
  function openAnnouncementHistory() {
@@ -5531,6 +5606,30 @@ function announcementVersionMatch(item) {
5531
5606
  if (max && cmpVersion(state.localVersion, max) > 0) return false
5532
5607
  return true
5533
5608
  }
5609
+ function normalizeAnnouncementPresentation(item) {
5610
+ if (typeof item?.summary !== 'string' || !Array.isArray(item.sections) || !item.sections.length || item.sections.length > 8) return {}
5611
+ const summary = item.summary.trim()
5612
+ if (!summary || summary.length > 2000) return {}
5613
+ let length = summary.length
5614
+ const sections = []
5615
+ for (const row of item.sections) {
5616
+ if (!row || typeof row.title !== 'string' || typeof row.content !== 'string') return {}
5617
+ const title = row.title.trim(), content = row.content.trim()
5618
+ if (!title || title.length > 160 || !content || content.length > 10000) return {}
5619
+ length += title.length + content.length
5620
+ if (length > 20000) return {}
5621
+ sections.push({ title, content, expanded: row.expanded === true })
5622
+ }
5623
+ return { summary, sections }
5624
+ }
5625
+ function announcementBodyHtml(item) {
5626
+ const text = value => esc(String(value ?? '').replace(/\r\n?/g, '\n')).replace(/\n/g, '<br>')
5627
+ const presentation = normalizeAnnouncementPresentation(item)
5628
+ if (!presentation.sections) return text(item?.content)
5629
+ return `<div class="announcement-summary">${text(presentation.summary)}</div><div class="announcement-sections">` + presentation.sections.map(section =>
5630
+ `<details class="announcement-section"${section.expanded ? ' open' : ''}><summary><span class="announcement-section-title">${esc(section.title)}</span><span class="announcement-section-expand">${esc(t('announcement.expand'))}</span><span class="announcement-section-collapse">${esc(t('announcement.collapse'))}</span></summary><div class="announcement-section-body">${text(section.content)}</div></details>`
5631
+ ).join('') + '</div>'
5632
+ }
5534
5633
  function normalizeAnnouncementPoll(value, announcementId) {
5535
5634
  if (window.DshAnnouncementForms) return window.DshAnnouncementForms.normalize(value, announcementId)
5536
5635
  if (!value || typeof value !== 'object') return null
@@ -5569,6 +5668,7 @@ function normalizeAnnouncement(item, base) {
5569
5668
  }
5570
5669
  return {
5571
5670
  id, title, content, actionUrl,
5671
+ ...normalizeAnnouncementPresentation(item),
5572
5672
  actionText: String(item.actionText || '').trim().slice(0, 80),
5573
5673
  publishedAt: Number.isFinite(startsAt) ? startsAt : 0,
5574
5674
  force: item.force === true,
@@ -5612,7 +5712,7 @@ function renderAnnouncementModal() {
5612
5712
  if (!item) return
5613
5713
  state.announcement = item
5614
5714
  $('announcement-title').textContent = item.title
5615
- $('announcement-content').innerHTML = esc(item.content).replace(/\r?\n/g, '<br>')
5715
+ $('announcement-content').innerHTML = announcementBodyHtml(item)
5616
5716
  renderAnnouncementPoll(item)
5617
5717
  const action = $('announcement-action')
5618
5718
  if (item.actionUrl) {
@@ -5635,6 +5735,7 @@ function openAnnouncementModal(items, index = 0) {
5635
5735
  state.announcementIndex = Math.max(0, Math.min(Number(index) || 0, list.length - 1))
5636
5736
  renderAnnouncementModal()
5637
5737
  $('modal-announcement').classList.remove('hidden')
5738
+ globalThis.DshDiagnostics?.record('announcement.show',{phase:'shown',announcementId:state.announcement?.id,count:list.length})
5638
5739
  }
5639
5740
  function showAnnouncementAt(index) {
5640
5741
  if (!state.announcementItems.length) return
@@ -5656,6 +5757,7 @@ async function submitAnnouncementVote() {
5656
5757
  const message = forms ? forms.encode(item.id, poll.id, answer) : `Poll ${poll.id}: ${option.id}`
5657
5758
  if (!message) return toast(I18N.lang === 'en' ? 'Answers are too long. Please shorten them.' : '回答总长度过长,请适当精简。', 'err')
5658
5759
  const button = $('announcement-poll-submit')
5760
+ const diagnostic=globalThis.DshDiagnostics?.start('announcement.vote',{announcementId:item.id,count:poll.questions?.length||1})
5659
5761
  button.disabled = true
5660
5762
  const connection = captureConnection(), valid = () => connection.valid() && state.announcement === item
5661
5763
  state.announcementSubmitting = true
@@ -5688,21 +5790,25 @@ async function submitAnnouncementVote() {
5688
5790
  })
5689
5791
  data = await res.json().catch(() => ({}))
5690
5792
  }
5691
- if (!connection.valid()) return
5793
+ if (!connection.valid()) { diagnostic?.end({phase:'skipped',reason:'unavailable'}); return }
5692
5794
  if (res?.ok && data.ok) {
5693
5795
  storeAnnouncementVote(item.id, poll.id, answer.optionId || '')
5694
5796
  markAnnouncementSeen(item.id)
5797
+ diagnostic?.end({phase:'complete',httpStatus:res.status})
5695
5798
  if (valid()) renderAnnouncementPoll(item)
5696
5799
  renderAnnouncementHistory()
5697
5800
  toast(poll.legacy === false ? (I18N.lang === 'en' ? 'Submitted successfully' : '已成功提交') : t('announcement.voteThanks', { option: option.label }), 'ok')
5698
5801
  } else if (res?.status === 429) {
5802
+ diagnostic?.end({phase:'failed',httpStatus:res.status})
5699
5803
  toast(t('announcement.voteAgainLater'), 'err')
5700
5804
  button.disabled = false
5701
5805
  } else {
5806
+ diagnostic?.end({phase:'failed',httpStatus:res?.status||0})
5702
5807
  toast(t('announcement.voteFailed', { msg: data.error || res?.status || t('announcement.voteNetworkError') }), 'err')
5703
5808
  button.disabled = false
5704
5809
  }
5705
5810
  } catch (e) {
5811
+ diagnostic?.fail(e)
5706
5812
  if (valid()) toast(t('announcement.voteFailed', { msg: e.message || t('announcement.voteNetworkError') }), 'err')
5707
5813
  button.disabled = false
5708
5814
  } finally {
@@ -5715,6 +5821,7 @@ async function submitAnnouncementVote() {
5715
5821
  }
5716
5822
  function closeAnnouncement(markSeen) {
5717
5823
  if (markSeen) markAnnouncementsSeen(state.announcementItems)
5824
+ globalThis.DshDiagnostics?.record('announcement.close',{phase:markSeen?'acknowledged':'dismissed',announcementId:state.announcement?.id,count:state.announcementItems.length})
5718
5825
  state.announcement = null
5719
5826
  state.announcementItems = []
5720
5827
  state.announcementIndex = 0
@@ -5723,13 +5830,14 @@ function closeAnnouncement(markSeen) {
5723
5830
  async function fetchAnnouncements() {
5724
5831
  const base = updateBase()
5725
5832
  if (!base || !state.localVersion || isAppVersionWarningOpen()) return false
5833
+ const diagnostic=globalThis.DshDiagnostics?.start('announcement.fetch')
5726
5834
  try {
5727
5835
  const signal = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(8000) : undefined
5728
5836
  const url = base + '/announcements.json?t=' + Date.now()
5729
5837
  const res = signal ? await fetch(url, { cache: 'no-store', signal }) : await fetch(url, { cache: 'no-store' })
5730
- if (!res.ok) return false
5838
+ if (!res.ok) { diagnostic?.end({phase:'failed',httpStatus:res.status,reason:'http'}); return false }
5731
5839
  const raw = await res.text()
5732
- if (raw.length > 512 * 1024) return false
5840
+ if (raw.length > 512 * 1024) { diagnostic?.end({phase:'failed',reason:'too-large'}); return false }
5733
5841
  const data = JSON.parse(raw)
5734
5842
  const source = Array.isArray(data) ? data : (Array.isArray(data?.items) ? data.items : [data])
5735
5843
  const normalized = source.map(item => normalizeAnnouncement(item, base)).filter(Boolean)
@@ -5740,10 +5848,11 @@ async function fetchAnnouncements() {
5740
5848
  const items = normalized.filter(item => !seen[item.id])
5741
5849
  .sort((a, b) => b.publishedAt - a.publishedAt)
5742
5850
  // 新旧界面均提示未读公告;拉取期间新出现的版本提醒仍优先展示。
5743
- if (!items.length || state.announcement || isAppVersionWarningOpen()) return false
5851
+ if (!items.length || state.announcement || isAppVersionWarningOpen()) { diagnostic?.end({phase:'skipped',count:items.length,reason:state.announcement?'already-open':isAppVersionWarningOpen()?'version-warning':'already-read'}); return false }
5744
5852
  openAnnouncementModal(items)
5853
+ diagnostic?.end({phase:'received',count:items.length,httpStatus:res.status})
5745
5854
  return true
5746
- } catch { return false }
5855
+ } catch(error) { diagnostic?.fail(error); return false }
5747
5856
  }
5748
5857
 
5749
5858
  function checkAnnouncements() {
@@ -6124,6 +6233,14 @@ function notify(title, body) {
6124
6233
  }
6125
6234
 
6126
6235
  async function sendTestNotification() {
6236
+ if (window.NativeBackground?.testNotification) {
6237
+ if (!await ensureNotify()) return toast(t('settings.notifyDenied'), 'err')
6238
+ const kind = $('test-notify-kind')?.value || 'approval'
6239
+ const sent = window.NativeBackground.testNotification(kind)
6240
+ applyBgConfigFromNative()
6241
+ toast(sent ? (I18N.lang === 'en' ? 'Test notification submitted. Check the selected system channel.' : '测试通知已提交,请检查所选系统通知渠道。') : t('settings.notifyDenied'), sent ? 'ok' : 'err')
6242
+ return
6243
+ }
6127
6244
  if (!CAP?.isNativePlatform?.()) {
6128
6245
  toast(t('settings.testNotifyUnavailable'), 'err')
6129
6246
  return
@@ -6170,6 +6287,11 @@ function applyBgConfigFromNative() {
6170
6287
  status.textContent = cfg.loginExpired ? t('settings.bgAuthFailed') : cfg.enabled && cfg.serviceRunning === false
6171
6288
  ? (I18N.lang === 'en' ? 'Background receiver is not running. Reopen the app or toggle to retry. ' : '后台接收未运行,返回应用或重新开关后重试。') + (cfg.serviceState || '')
6172
6289
  : cfg.enabled && cfg.serviceRunning === true ? (I18N.lang === 'en' ? 'Background receiver is running.' : '后台接收运行中。') + (cfg.lastSuccessAt ? ' ' + new Date(cfg.lastSuccessAt).toLocaleTimeString() : '') : ''
6290
+ const blocked = []
6291
+ if (cfg.notificationsEnabled === false) blocked.push(I18N.lang === 'en' ? 'System notifications disabled' : '系统通知已关闭')
6292
+ if (cfg.attentionChannelEnabled === false) blocked.push(I18N.lang === 'en' ? 'Approval channel disabled' : '审批提醒渠道已关闭')
6293
+ if (cfg.taskChannelEnabled === false) blocked.push(I18N.lang === 'en' ? 'Task result channel disabled' : '任务结果渠道已关闭')
6294
+ if (blocked.length) status.textContent = [status.textContent, ...blocked].filter(Boolean).join(' · ')
6173
6295
  status.classList.toggle('hidden', !status.textContent)
6174
6296
  }
6175
6297
  } catch {}
@@ -6185,7 +6307,7 @@ function saveBgConfig(enabled) {
6185
6307
  return saved
6186
6308
  }
6187
6309
  function syncBgConfig() {
6188
- if ($('opt-bg-poll')?.checked && state.token) saveBgConfig(true)
6310
+ if (state.token && bgBridge()?.saveBackgroundConfig) saveBgConfig(!!$('opt-bg-poll')?.checked)
6189
6311
  void syncPeakReminders()
6190
6312
  }
6191
6313
 
@@ -6880,7 +7002,8 @@ async function openModelConfigDocument() {
6880
7002
  if (value?.opened) toast(t('settings.modelOpenedConfig'), 'ok')
6881
7003
  }
6882
7004
  /* ---------------- 视图切换 ---------------- */
6883
- function showView(id) {
7005
+ function showView(id, pluginRoute = 'manage') {
7006
+ window.DshExtensions?.closeShortcuts()
6884
7007
  if (id !== 'view-session') window.DshSubagents?.close()
6885
7008
  document.body?.classList.toggle('viewing-subagent', id === 'view-session' && state.byId.get(state.current)?.origin === 'subagent')
6886
7009
  window.DshWorkflow?.close()
@@ -6890,19 +7013,19 @@ function showView(id) {
6890
7013
  for (const v of ['view-home', 'view-files', 'view-session', 'view-activity', 'view-plugins', 'view-settings']) $(v).classList.toggle('hidden', v !== id)
6891
7014
  // 离开会话页必须清掉 in-session, 否则其他页面顶栏被 body 样式隐藏
6892
7015
  document.body.classList.toggle('in-session', id === 'view-session')
7016
+ window.DshFileInbox?.render()
7017
+ window.DshSessionDeck?.refresh()
6893
7018
  if (id === 'view-session') conversationView?.resume()
6894
7019
  $('session-actions')?.close()
6895
7020
  $('session-info')?.close()
6896
7021
  document.querySelectorAll('.nav-btn').forEach(b => b.classList.toggle('active', b.dataset.view === id))
6897
- // 主页已有上下文明确的刷新按钮,避免顶栏出现第二个同义入口。
6898
- $('btn-refresh')?.classList.toggle('hidden', id === 'view-activity')
6899
7022
  window.DshMotion?.view($(id))
6900
7023
  window.scrollTo(0, 0)
6901
7024
  if (id === 'view-files' && !state.fs.loaded) {
6902
7025
  const workspace = workspaceById(state.fs.workspaceId)
6903
7026
  loadFs(workspace?.path || null, { silent: true, resetRoot: true })
6904
7027
  }
6905
- if (id === 'view-plugins') openPluginPage()
7028
+ if (id === 'view-plugins') openPluginPage(pluginRoute)
6906
7029
  else window.DshExtensions?.close()
6907
7030
  if (id === 'view-settings') showSettingsHome()
6908
7031
  if(id==='view-activity')startOverviewDetection(true);else {overviewDetector?.pause();overviewPulse?.pause()}
@@ -6935,7 +7058,7 @@ function updateConn() {
6935
7058
  const ms = cur ? state.serverLatency[serverKey(cur)] : undefined
6936
7059
  const curGroup = cur ? cur.group : state.activeGroup
6937
7060
  const curLabel = cur ? (cur.note || cur.url) : (state.server || t('speed.origin'))
6938
- const titleBase = t('conn.titleGroup', { group: curGroup, url: curLabel, ms: Number.isFinite(ms) ? ms + 'ms' : '—' })
7061
+ const titleBase = t('conn.titleGroup', { group: curGroup, url: curLabel, ms: Number.isFinite(ms) ? ms + 'ms' : '—' }) + ' · ' + t('conn.refresh')
6939
7062
  if (!navigator.onLine) {
6940
7063
  el.textContent = t('conn.offline')
6941
7064
  el.className = 'topbar-btn conn-badge off'
@@ -7815,7 +7938,11 @@ function bindUi() {
7815
7938
  $('btn-stats').addEventListener('click', () => { renderSessionCards(); $('modal-stats').classList.remove('hidden') })
7816
7939
  $('btn-insights').addEventListener('click', () => openInsights())
7817
7940
  $('stats-close').addEventListener('click', () => $('modal-stats').classList.add('hidden'))
7818
- $('btn-refresh').addEventListener('click', () => { toast(t('common.refreshing')); openStreams(); refreshAll() })
7941
+ $('conn-badge').addEventListener('click', () => { toast(t('common.refreshing')); openStreams(); void refreshAll() })
7942
+ window.DshExtensions?.bindShortcuts({ trigger: $('btn-plugin-shortcuts'), menu: $('plugin-shortcuts-menu'),
7943
+ config: () => optionalPluginConfig(), connected: () => !!state.token, hasSession: () => !!state.current,
7944
+ beforeOpen: () => { closeFeedbackSheet(); closeGroupDrawer({ restoreFocus: false }) },
7945
+ open: route => { if (route === 'context') void openInsights('context', true); else showView('view-plugins', route) } })
7819
7946
  $('overview-refresh').addEventListener('click', () => {
7820
7947
  toast(t('common.refreshing'))
7821
7948
  startOverviewDetection(true)
@@ -7837,6 +7964,8 @@ function bindUi() {
7837
7964
  $('home-doctor').addEventListener('click', openDoctor)
7838
7965
  $('fb-cancel').addEventListener('click', closeFeedbackModal)
7839
7966
  $('fb-submit').addEventListener('click', submitFeedback)
7967
+ $('fb-include-diagnostics').addEventListener('change',()=>{void loadCrashPreview()})
7968
+ $('fb-include-crashes').addEventListener('change',()=>{void loadCrashPreview()})
7840
7969
  $('feedback-success-confirm').addEventListener('click', closeFeedbackSuccess)
7841
7970
  $('modal-feedback-success').addEventListener('click', (e) => {
7842
7971
  if (e.target === $('modal-feedback-success')) closeFeedbackSuccess()
@@ -8041,6 +8170,14 @@ function bindUi() {
8041
8170
  })
8042
8171
  $('btn-server-speed').addEventListener('click', () => selectFastestServer({ silent: false }))
8043
8172
  $('btn-server-add').addEventListener('click', addServer)
8173
+ window.DshLanDiscovery?.mount($('btn-lan-discover'), result => {
8174
+ const url = new URL('dshremote://pair')
8175
+ url.searchParams.set('server', result.server); url.searchParams.set('token', result.token)
8176
+ if (!applyPairUrl(url.href)) return toast(t('send.failed'), 'err')
8177
+ const server = state.servers.find(entry => entry.url === result.server && entry.token === result.token)
8178
+ if (server) { server.note = String(result.name || '').slice(0, 40); saveServers(); renderServers() }
8179
+ openStreams(); toast(t('scan.paired'), 'ok')
8180
+ })
8044
8181
  $('btn-group-add').addEventListener('click', addGroup)
8045
8182
  $('group-select-btn').addEventListener('click', (e) => { e.stopPropagation(); toggleGroupMenu() })
8046
8183
  $('group-drawer-trigger').addEventListener('click', () => { groupDrawerOpen() ? closeGroupDrawer() : openGroupDrawer() })
@@ -8083,7 +8220,7 @@ function bindUi() {
8083
8220
  if (!confirm(t('settings.confirmReset'))) return
8084
8221
  clearTimeout(scheduleHistoryCacheSave._t)
8085
8222
  await window.DshHistory.cacheClear()
8086
- LS.del('token'); LS.del('notify'); LS.del('server'); LS.del('mobileEnterAction'); LS.del('steerSendingEnabled'); LS.del('busySendMode'); LS.del(ANNOUNCEMENTS_KEY); LS.del(ANNOUNCEMENT_HISTORY_KEY); LS.del(ANNOUNCEMENT_VOTES_KEY)
8223
+ LS.del('token'); LS.del('notify'); LS.del('server'); LS.del('mobileEnterAction'); LS.del('steerSendingEnabled'); LS.del('busySendMode'); resetAnnouncementStorage()
8087
8224
  if (bgBridge()?.saveBackgroundConfig) saveBgConfig(false)
8088
8225
  location.reload()
8089
8226
  })
@@ -8153,7 +8290,8 @@ function bindUi() {
8153
8290
  $('bg-interval').addEventListener('change', () => {
8154
8291
  if ($('opt-bg-poll')?.checked) saveBgConfig(true)
8155
8292
  })
8156
- $('opt-task-done')?.addEventListener('change', () => {
8293
+ $('opt-task-done')?.addEventListener('change', async event => {
8294
+ if (event.target.checked && !await ensureNotify()) { event.target.checked = false; toast(t('settings.notifyDenied'), 'err') }
8157
8295
  if (bgBridge()?.saveBackgroundConfig) saveBgConfig($('opt-bg-poll')?.checked)
8158
8296
  })
8159
8297
  renderPresets()
@@ -8211,6 +8349,7 @@ window.addEventListener('dsh-native-insets', applyNativeInsets)
8211
8349
  async function boot() {
8212
8350
  initToken()
8213
8351
  bindUi()
8352
+ syncBgConfig()
8214
8353
  renderAnnouncementBoard()
8215
8354
  renderLangBtn()
8216
8355
  bindNativeBack()
@@ -8351,6 +8490,7 @@ async function clearWorkflowData(kind) {
8351
8490
  await cancelPeakReminders()
8352
8491
  clearTimeout(scheduleHistoryCacheSave._t)
8353
8492
  await window.DshHistory.cacheClear()
8493
+ resetAnnouncementStorage()
8354
8494
  window.DshWorkflow.clearStorage()
8355
8495
  location.reload()
8356
8496
  }
@@ -8391,3 +8531,9 @@ function openPluginPage(route = 'manage') {
8391
8531
 
8392
8532
  // Operation logs stay on this device; users can copy or export them.
8393
8533
  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()})})
8534
+ globalThis.DshFileInbox?.mount({ capture: captureConnection, url: apiUrl,
8535
+ context: () => ({ sessionId: state.current, inChat: !$('view-session').classList.contains('hidden') }),
8536
+ sessionTitle: id => sessionTitleValue(state.byId.get(id)), openFiles: () => showView('view-files'),
8537
+ headers: connection => ({ authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }),
8538
+ native: () => CAP?.isNativePlatform?.() ? window.NativeFile : null })
8539
+ globalThis.DshSessionDeck?.mount({ context: () => ({ sessionId: state.current, inChat: !$('view-session').classList.contains('hidden') }) })