dsh-remote-plugin 0.8.1 → 0.8.3

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.
Files changed (111) hide show
  1. package/README.md +1 -1
  2. package/apk/dsh-remote.apk +0 -0
  3. package/cordis.patch.yml +2 -1
  4. package/gateway.cjs +323 -64
  5. package/index.mjs +2 -2
  6. package/insights.mjs +5 -3
  7. package/market.mjs +4 -1
  8. package/package.json +1 -1
  9. package/plugin-center.mjs +120 -7
  10. package/plugin-transaction.mjs +10 -3
  11. package/public/admin.html +19 -14
  12. package/public/admin.js +71 -23
  13. package/public/announcements.json +192 -0
  14. package/public/app.js +192 -60
  15. package/public/build.json +2 -2
  16. package/public/chat-copy.js +46 -0
  17. package/public/desktop/desktop.css +10 -0
  18. package/public/desktop/desktop.html +28 -15
  19. package/public/desktop/desktop.js +74 -22
  20. package/public/diagnostics.js +115 -21
  21. package/public/history.js +45 -9
  22. package/public/image-cache.js +141 -0
  23. package/public/image-preview.js +48 -5
  24. package/public/index.html +39 -34
  25. package/public/lan-discovery.js +94 -0
  26. package/public/md.js +8 -2
  27. package/public/plugin-center.js +1 -1
  28. package/public/plugin.html +8 -2
  29. package/public/relay-settings.js +7 -6
  30. package/public/skins/blue-fish/DESIGN.md +24 -0
  31. package/public/skins/blue-fish/preview.html +11 -289
  32. package/public/skins/blue-fish/skin.css +95 -585
  33. package/public/skins/blue-fish/sparkles.svg +18 -0
  34. package/public/skins/bocchi/DESIGN.md +99 -0
  35. package/public/skins/bocchi/face.png +0 -0
  36. package/public/skins/bocchi/grain.png +0 -0
  37. package/public/skins/bocchi/icon-blush.png +0 -0
  38. package/public/skins/bocchi/icon-sleep.png +0 -0
  39. package/public/skins/bocchi/icon-smile.png +0 -0
  40. package/public/skins/bocchi/icon-star.png +0 -0
  41. package/public/skins/bocchi/icon-wink.png +0 -0
  42. package/public/skins/bocchi/icon.png +0 -0
  43. package/public/skins/bocchi/pattern-soft.png +0 -0
  44. package/public/skins/bocchi/pattern.png +0 -0
  45. package/public/skins/bocchi/preview.html +54 -0
  46. package/public/skins/bocchi/skin.css +233 -0
  47. package/public/skins/bocchi/stage-bg.png +0 -0
  48. package/public/skins/bocchi/stage-soft.png +0 -0
  49. package/public/skins/bocchi/stand.png +0 -0
  50. package/public/skins/bocchi/sticker-guitar.png +0 -0
  51. package/public/skins/kessoku/DESIGN.md +38 -0
  52. package/public/skins/kessoku/grain.png +0 -0
  53. package/public/skins/kessoku/skin.css +212 -0
  54. package/public/skins/kita/SOURCES.json +51 -0
  55. package/public/skins/kita/face.png +0 -0
  56. package/public/skins/kita/icon-live.png +0 -0
  57. package/public/skins/kita/icon-reddress.png +0 -0
  58. package/public/skins/kita/icon-seifuku.png +0 -0
  59. package/public/skins/kita/pattern.png +0 -0
  60. package/public/skins/kita/preview.html +55 -0
  61. package/public/skins/kita/skin.css +26 -0
  62. package/public/skins/kita/stand.png +0 -0
  63. package/public/skins/kita/sticker-live.png +0 -0
  64. package/public/skins/nijika/SOURCES.json +51 -0
  65. package/public/skins/nijika/face.png +0 -0
  66. package/public/skins/nijika/icon-live.png +0 -0
  67. package/public/skins/nijika/icon-reddress.png +0 -0
  68. package/public/skins/nijika/icon-seifuku.png +0 -0
  69. package/public/skins/nijika/pattern.png +0 -0
  70. package/public/skins/nijika/preview.html +55 -0
  71. package/public/skins/nijika/skin.css +25 -0
  72. package/public/skins/nijika/stand.png +0 -0
  73. package/public/skins/nijika/sticker-live.png +0 -0
  74. package/public/skins/penguin/DESIGN.md +33 -0
  75. package/public/skins/penguin/SOURCES.json +22 -0
  76. package/public/skins/penguin/aic-blueprint.svg +24 -0
  77. package/public/skins/penguin/endfield-triangles.svg +4 -0
  78. package/public/skins/penguin/face.png +0 -0
  79. package/public/skins/penguin/icon-blush.png +0 -0
  80. package/public/skins/penguin/icon-dizzy.png +0 -0
  81. package/public/skins/penguin/icon-laugh.png +0 -0
  82. package/public/skins/penguin/icon-sleep.png +0 -0
  83. package/public/skins/penguin/icon-smile.png +0 -0
  84. package/public/skins/penguin/icon-star.png +0 -0
  85. package/public/skins/penguin/icon-wink.png +0 -0
  86. package/public/skins/penguin/icon.png +0 -0
  87. package/public/skins/penguin/mascot.png +0 -0
  88. package/public/skins/penguin/pattern-night.png +0 -0
  89. package/public/skins/penguin/pattern.png +0 -0
  90. package/public/skins/penguin/preview.html +11 -0
  91. package/public/skins/penguin/skin.css +212 -0
  92. package/public/skins/ryo/SOURCES.json +51 -0
  93. package/public/skins/ryo/face.png +0 -0
  94. package/public/skins/ryo/icon-live.png +0 -0
  95. package/public/skins/ryo/icon-reddress.png +0 -0
  96. package/public/skins/ryo/icon-seifuku.png +0 -0
  97. package/public/skins/ryo/pattern.png +0 -0
  98. package/public/skins/ryo/preview.html +55 -0
  99. package/public/skins/ryo/skin.css +25 -0
  100. package/public/skins/ryo/stand.png +0 -0
  101. package/public/skins/ryo/sticker-live.png +0 -0
  102. package/public/sponsor-entry.js +22 -0
  103. package/public/styles.css +13 -0
  104. package/public/theme-picker.css +58 -0
  105. package/public/theme-vars.css +532 -5
  106. package/public/theme.js +111 -3
  107. package/public/update.json +12 -12
  108. package/public/version.json +1 -1
  109. package/public/workflow.css +2 -1
  110. package/public/workflow.js +24 -1
  111. package/skills/dsh-remote-doctor/references/wiki/notifications.md +4 -0
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 = (() => {
@@ -33,9 +33,9 @@ const CACHE = {
33
33
  get sessions() { return connectionCacheKey('sessions') },
34
34
  get history() { return connectionCacheKey('history') }
35
35
  }
36
- function connectionCacheKey(kind) {
36
+ function connectionCacheKey(kind, server=state.server, token=state.token) {
37
37
  const hash = new SHA256()
38
- hash.update(new TextEncoder().encode(JSON.stringify([state.server || location.origin, state.token])))
38
+ hash.update(new TextEncoder().encode(JSON.stringify([server || location.origin, token])))
39
39
  return kind + 'CacheV2:' + hash.hex()
40
40
  }
41
41
  function cacheRead(key, d = null) {
@@ -120,6 +120,7 @@ for (const key of ['server', 'token']) {
120
120
  if (next === value) return
121
121
  cancelHistoryLoad()
122
122
  value = next; connectionGeneration++
123
+ window.DshImagePreview?.reset?.()
123
124
  clearTimeout(state.refreshTimer); state.refreshTimer = null
124
125
  state.sessions = []; state.byId.clear(); state.pendingProjections.clear(); state.runtimeErrors = new Map()
125
126
  state.hostInfo = null
@@ -393,6 +394,7 @@ function openFeedbackModal(options = {}) {
393
394
  $('fb-include-crashes').checked = false
394
395
  $('fb-crash-details').open = false
395
396
  }
397
+ updateFeedbackLength()
396
398
  void loadCrashPreview()
397
399
  $('modal-feedback').classList.remove('hidden')
398
400
  setTimeout(() => $('fb-msg').focus(), 50)
@@ -407,14 +409,22 @@ function closeFeedbackSuccess() {
407
409
  $('btn-feedback')?.focus()
408
410
  }
409
411
  async function loadCrashPreview() {
412
+ const generation=loadCrashPreview.generation=(loadCrashPreview.generation||0)+1
410
413
  const connection=captureConnection(),preview=$('fb-crash-preview')
411
414
  preview.textContent=t('feedback.crashLoading')
412
- try {
413
- const response=await fetch(updateBase()+'/crash-logs',{headers:{authorization:'Bearer '+connection.token},signal:AbortSignal.timeout(5000),cache:'no-store'})
414
- if(!response.ok)throw new Error('unavailable')
415
- const data=await response.json()
416
- if(connection.valid())preview.textContent=JSON.stringify(data.upload,null,2)
417
- }catch{if(connection.valid())preview.textContent=t('feedback.crashUnavailable')}
415
+ const selected=$('fb-include-diagnostics').checked,crashes=$('fb-include-crashes').checked
416
+ if(!selected&&!crashes){preview.textContent=I18N.lang==='en'?'Select a log option above to preview the attachment.':'勾选上方日志选项后,可在这里预览拟上传的附件。';return}
417
+ 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}}}
418
+ const evidence={}
419
+ if(selected){evidence.client=globalThis.DshDiagnostics?.report();evidence.gateway=await read('/diagnostics')}
420
+ if(crashes){const data=await read('/crash-logs');evidence.crashes=data.upload||data}
421
+ if(connection.valid()&&generation===loadCrashPreview.generation)preview.textContent=JSON.stringify(evidence,null,2)
422
+ }
423
+ function updateFeedbackLength() {
424
+ const length = $('fb-msg').value.trim().length, over = length > 20000
425
+ $('fb-length').textContent = I18N.lang === 'en' ? length + ' / 20000 characters' + (over ? ' — shorten before submitting; your text is preserved.' : '') : length + ' / 20000 字符' + (over ? ',请精简后提交;全文已保留。' : '')
426
+ $('fb-msg').setAttribute('aria-invalid', String(over))
427
+ $('fb-copy-draft').textContent = I18N.lang === 'en' ? 'Copy text' : '复制全文'
418
428
  }
419
429
  async function submitFeedback() {
420
430
  const type = state.feedbackType || 'bug'
@@ -422,8 +432,9 @@ async function submitFeedback() {
422
432
  const contact = $('fb-contact').value.trim()
423
433
  const includeDiagnostics = $('fb-include-diagnostics').checked
424
434
  const includeCrashLogs = $('fb-include-crashes').checked
435
+ const clientDiagnostics=includeDiagnostics?globalThis.DshDiagnostics?.report():null
425
436
  if (!message) { toast(t('feedback.empty'), 'err'); return }
426
- if (message.length > 2000) { toast(t('feedback.tooLong'), 'err'); return }
437
+ if (message.length > 20000) { toast(t('feedback.tooLong'), 'err'); return }
427
438
  const btn = $('fb-submit')
428
439
  btn.disabled = true
429
440
  const diagnostic=globalThis.DshDiagnostics?.start('feedback.submit')
@@ -433,17 +444,26 @@ async function submitFeedback() {
433
444
  const res = await fetch(base + '/feedback', {
434
445
  method: 'POST',
435
446
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token },
436
- body: JSON.stringify({ type, message, contact, appVersion: state.localVersion, includeDiagnostics, includeCrashLogs })
447
+ body: JSON.stringify({ type, message, contact, appVersion: state.localVersion, includeDiagnostics, includeCrashLogs,...(clientDiagnostics?{clientDiagnostics}:{}) })
437
448
  })
438
449
  diagnostic?.end({phase:res.ok?'complete':'failed',httpStatus:res.status})
439
450
  let json = {}
440
451
  try { json = await res.json() } catch {}
441
- if (res.ok && json.ok) { closeFeedbackModal(); openFeedbackSuccess() }
452
+ if (res.ok && json.ok) { closeFeedbackModal(); openFeedbackSuccess()
453
+ const status=$('feedback-diagnostics-status'),saved=json.diagnostics?.saved===true&&json.diagnostics.reportId===clientDiagnostics?.reportId
454
+ 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.':'反馈已收到,但服务器未确认完整诊断日志已保存。请复制或导出本地日志补充。')):''
455
+ status.classList.toggle('hidden',!clientDiagnostics)
456
+ }
442
457
  else if (res.status === 429) { toast(json.retryAfter ? t('feedback.rateLimitedAt', { n: json.retryAfter }) : t('feedback.rateLimited'), 'err') }
458
+ else if (json.error === 'message too long' && Number.isSafeInteger(json.max)) { toast(I18N.lang === 'en' ? 'This gateway limits feedback to ' + json.max + ' characters. Your full text is preserved; update the host gateway.' : '当前网关正文上限为 ' + json.max + ' 字符,全文已保留;请更新主机网关。', 'err') }
459
+ else if (json.error === 'collector-message-limit') { toast(I18N.lang === 'en' ? 'The collector still limits feedback to ' + json.max + ' characters. Your full text is preserved; copy it before updating the collector.' : '收集器仍只支持 ' + json.max + ' 字符,全文已保留;可先复制全文,待收集器升级后再提交。', 'err') }
460
+ else if (json.error === 'collector-body-limit') { toast(I18N.lang === 'en' ? 'The collector rejected the request size. Your full text is preserved; copy it before updating the collector.' : '收集器请求体超限,全文已保留;请先复制,待收集器升级后再提交。', 'err') }
461
+ else if (json.error === 'feedback_service_unavailable') { toast(I18N.lang === 'en' ? 'Delivery is unconfirmed; it may have been received. Your text is preserved. Check before resubmitting.' : '发送结果未确认,可能已收到。全文已保留,请先核对,勿重复提交。', 'err') }
462
+ else if (json.error === 'feedback-content-unconfirmed') { toast(I18N.lang === 'en' ? 'The content receipt did not match. It may have been received; check before resubmitting. Your text is preserved.' : '正文保存回执不一致,可能已收到;请先核对,勿重复提交。全文已保留。', 'err') }
443
463
  else { toast(t('feedback.submitFailed', { msg: json.error || res.status }), 'err') }
444
464
  } catch(error) {
445
465
  diagnostic?.fail(error)
446
- toast(t('feedback.submitFailed', { msg: t('feedback.networkError') }), 'err')
466
+ toast(I18N.lang === 'en' ? 'Delivery is unconfirmed; it may have been received. Your text is preserved. Check before resubmitting.' : '发送结果未确认,可能已收到。全文已保留,请先核对,勿重复提交。', 'err')
447
467
  } finally {
448
468
  btn.disabled = false
449
469
  }
@@ -1177,6 +1197,8 @@ function editServer(id) {
1177
1197
  function removeServer(id) {
1178
1198
  const s = state.servers.find(x => x.id === id)
1179
1199
  if (!s) return
1200
+ void window.DshImageCache?.clear(historyCacheScope(s.url,serverToken(s)))
1201
+ void window.DshHistory.cacheClear(historyCacheScope(s.url,serverToken(s)))
1180
1202
  state.servers = state.servers.filter(x => x.id !== id)
1181
1203
  const wasActive = state.server === s.url && state.token === serverToken(s)
1182
1204
  // 清理该组手动指定
@@ -1533,6 +1555,16 @@ async function pollKind(kind, cancellation) {
1533
1555
  if (state.current) void resyncCurrentSession()
1534
1556
  }
1535
1557
  if (data.epoch) cursors[kind + 'Epoch'] = data.epoch
1558
+ // The fallback poll may contain a request and its resolution together. Seed
1559
+ // native tombstones first, including before the pending baseline is replayed.
1560
+ if (kind === 'mux' && typeof window !== 'undefined' && window.NativeBackground?.handlePendingEvent) {
1561
+ for (const item of data.events) {
1562
+ const payload = item.event?.payload
1563
+ if (item.seq > (reset ? 0 : since) && ['approval/resolved', 'question/resolved'].includes(payload?.type)) {
1564
+ window.NativeBackground.handlePendingEvent(bgBase(), state.token || '', JSON.stringify(item.event), false)
1565
+ }
1566
+ }
1567
+ }
1536
1568
  for (const frame of data.baseline || []) { if (kind === 'mux') onMuxFrame(frame); else onHostFrame(frame) }
1537
1569
  for (const item of data.events) {
1538
1570
  if (item.seq > (state.pollSeq[kind] || 0)) {
@@ -1654,6 +1686,7 @@ function onMuxFrame(full) {
1654
1686
  function onHostFrame(full) {
1655
1687
  const f = full.payload
1656
1688
  if (!f) return
1689
+ 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)
1657
1690
  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()
1658
1691
  if (f.type === 'host/session-activity') {
1659
1692
  const session = state.byId.get(f.sessionId)
@@ -1799,6 +1832,7 @@ function observeCompactionEvent(sessionId, event, meta = {}) {
1799
1832
 
1800
1833
  function onSessionEvent(sessionId, event, meta = {}) {
1801
1834
  if (!event) return
1835
+ 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)
1802
1836
  const s = state.byId.get(sessionId)
1803
1837
  observeCompactionEvent(sessionId, event, meta)
1804
1838
  if (event.type === 'turn/start' || event.type === 'turn/end') {
@@ -2766,7 +2800,11 @@ function restoreCachedSessionList() {
2766
2800
  }
2767
2801
 
2768
2802
  let conversationView = null
2769
- function historyCacheScope() { return CACHE.history }
2803
+ function historyCacheScope(server=state.server,token=state.token) { return connectionCacheKey('history',server,token) }
2804
+ function captureChatImage() {
2805
+ const connection=captureConnection(),sessionId=state.current
2806
+ return {scope:historyCacheScope(),valid:()=>connection.valid()&&state.current===sessionId}
2807
+ }
2770
2808
  function historySource(value) {
2771
2809
  state.history.source=value
2772
2810
  const el=$('history-source')
@@ -2946,6 +2984,10 @@ function canForkTurnResult() {
2946
2984
  return !!session && session.origin !== 'subagent' && session.formatStatus !== 'migration-required' && activeGatewayCapability('operations') === true
2947
2985
  }
2948
2986
  function bindTurnResultActions() {
2987
+ window.DshChatCopy?.bind($('history'), {
2988
+ capture: () => { const connection = captureConnection(), sessionId = state.current, history = state.history; return { history, valid: () => connection.valid() && state.current === sessionId && state.history === history } },
2989
+ copy: copyText, notice: toast,
2990
+ })
2949
2991
  window.DshTurnResults.bind($('history'), {
2950
2992
  capture: () => {
2951
2993
  const connection = captureConnection(), sessionId = state.current, history = state.history
@@ -3121,7 +3163,7 @@ function eventHtml(entry, ctx = {}) {
3121
3163
  // Inline tool blocks duplicate the separated tool events; when those events exist the
3122
3164
  // calls live in the activity group, so an assistant message with nothing else disappears.
3123
3165
  if (!body) return ''
3124
- inner = `<div class="msg ${esc(role)}" data-seq="${seq}"><div class="role">${esc(role === 'user' ? t('role.me') : t('role.dsh'))}</div>${body}</div>`
3166
+ inner = `<div class="msg ${esc(role)}" data-seq="${seq}"><div class="role">${esc(role === 'user' ? t('role.me') : t('role.dsh'))}${blocks.some(block => block?.type === 'text' && String(block.text ?? '').trim()) ? window.DshChatCopy?.button(seq, state.history) || '' : ''}</div>${body}</div>`
3125
3167
  }
3126
3168
  } else if (type === 'tool/call') {
3127
3169
  const name = data.name || data.toolName || t('tool.default')
@@ -3158,7 +3200,7 @@ function blockHtml(b,index=0,context={}) {
3158
3200
  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)})})
3159
3201
  }
3160
3202
  switch (b.type) {
3161
- 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>` : ''
3203
+ case 'text': return window.DshActivity.hasVisibleText(b.text) ? `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '', { fileLinks: true, imageLabel: t('block.image'), copyCode: true, copyCodeLabel: window.I18N?.lang === 'en' ? 'Copy code' : '复制代码' }) : esc(b.text ?? '')}</div>` : ''
3162
3204
  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>`
3163
3205
  case 'image': {
3164
3206
  if (b.attachment && window.DshImagePreview) return window.DshImagePreview.attachmentHtml(b.attachment, t('block.image'), state.current)
@@ -3168,7 +3210,7 @@ function blockHtml(b,index=0,context={}) {
3168
3210
  case 'thinking':
3169
3211
  case 'reasoning':
3170
3212
  return `<details class="tool"><summary>${t('block.thinking')}</summary><div class="tool-text">${esc(truncate(String(b.text ?? b.content ?? safeJson(b)), 6000))}</div></details>`
3171
- case 'code': return `<pre>${esc(b.content ?? b.code ?? '')}</pre>`
3213
+ case 'code': return window.DshChatCopy?.code(b.content ?? b.code ?? '') || `<pre>${esc(b.content ?? b.code ?? '')}</pre>`
3172
3214
  case 'tool-call':
3173
3215
  return `<details class="tool"><summary>🔧 ${esc(b.name || b.toolName || t('block.toolCall'))}</summary><pre>${esc(truncate(safeJson(b.arguments ?? b), 4000))}</pre></details>`
3174
3216
  case 'tool-result':
@@ -5408,9 +5450,61 @@ const ANNOUNCEMENTS_POLL_MS = 30 * 1000
5408
5450
  let announcementCheckPromise = null
5409
5451
  let announcementPollTimer = null
5410
5452
  let announcementPollingStarted = false
5453
+ // LS.set silently tolerates quota/security errors. Keep failed writes available to
5454
+ // the UI, and use sessionStorage so a page reload can retain the acknowledgement.
5455
+ const announcementStorageFallback = new Map()
5456
+ function clearAnnouncementFallback(key) {
5457
+ announcementStorageFallback.delete(key)
5458
+ try { sessionStorage.removeItem(key) } catch {}
5459
+ }
5460
+ function readAnnouncementStorage(key, fallback) {
5461
+ const saved = LS.get(key, null)
5462
+ let pending = announcementStorageFallback.get(key)
5463
+ if (!pending) {
5464
+ try { pending = JSON.parse(sessionStorage.getItem(key) || 'null') } catch {}
5465
+ if (!pending || typeof pending.value !== 'string' || !(pending.previous === null || typeof pending.previous === 'string')) pending = null
5466
+ }
5467
+ if (pending) {
5468
+ // Honor a newer persistent value written by another page, including recovery
5469
+ // of our own failed write. A blocked read may still return null.
5470
+ if (saved !== null && saved !== pending.previous) {
5471
+ clearAnnouncementFallback(key)
5472
+ return saved
5473
+ }
5474
+ announcementStorageFallback.set(key, pending)
5475
+ return pending.value
5476
+ }
5477
+ return saved ?? fallback
5478
+ }
5479
+ function writeAnnouncementStorage(key, value) {
5480
+ try { LS.set(key, value) } catch {}
5481
+ const saved = LS.get(key, null)
5482
+ if (saved === value) {
5483
+ clearAnnouncementFallback(key)
5484
+ return
5485
+ }
5486
+ const pending = { previous: saved, value }
5487
+ const alreadyFailed = announcementStorageFallback.has(key)
5488
+ announcementStorageFallback.set(key, pending)
5489
+ let backend = 'memory'
5490
+ try {
5491
+ sessionStorage.setItem(key, JSON.stringify(pending))
5492
+ backend = 'session'
5493
+ } catch {}
5494
+ if (!alreadyFailed) globalThis.DshDiagnostics?.record('announcement.storage', {
5495
+ phase: 'failed', storageBackend: backend,
5496
+ storageKey: key === ANNOUNCEMENTS_KEY ? 'seen' : key === ANNOUNCEMENT_HISTORY_KEY ? 'history' : 'votes'
5497
+ })
5498
+ }
5499
+ function resetAnnouncementStorage() {
5500
+ for (const key of [ANNOUNCEMENTS_KEY, ANNOUNCEMENT_HISTORY_KEY, ANNOUNCEMENT_VOTES_KEY]) {
5501
+ LS.del(key)
5502
+ clearAnnouncementFallback(key)
5503
+ }
5504
+ }
5411
5505
  function readSeenAnnouncements() {
5412
5506
  try {
5413
- const value = JSON.parse(LS.get(ANNOUNCEMENTS_KEY, '{}'))
5507
+ const value = JSON.parse(readAnnouncementStorage(ANNOUNCEMENTS_KEY, '{}'))
5414
5508
  return value && typeof value === 'object' && !Array.isArray(value) ? value : {}
5415
5509
  } catch { return {} }
5416
5510
  }
@@ -5425,13 +5519,13 @@ function markAnnouncementsSeen(items) {
5425
5519
  keys.sort((a, b) => Number(seen[a]) - Number(seen[b]))
5426
5520
  for (const key of keys.slice(0, keys.length - 100)) delete seen[key]
5427
5521
  }
5428
- LS.set(ANNOUNCEMENTS_KEY, JSON.stringify(seen))
5522
+ writeAnnouncementStorage(ANNOUNCEMENTS_KEY, JSON.stringify(seen))
5429
5523
  renderAnnouncementBoard()
5430
5524
  }
5431
5525
  function markAnnouncementSeen(id) { markAnnouncementsSeen([id]) }
5432
5526
  function readAnnouncementVotes() {
5433
5527
  try {
5434
- const value = JSON.parse(LS.get(ANNOUNCEMENT_VOTES_KEY, '{}'))
5528
+ const value = JSON.parse(readAnnouncementStorage(ANNOUNCEMENT_VOTES_KEY, '{}'))
5435
5529
  return value && typeof value === 'object' && !Array.isArray(value) ? value : {}
5436
5530
  } catch { return {} }
5437
5531
  }
@@ -5446,7 +5540,7 @@ function storeAnnouncementVote(announcementId, pollId, optionId) {
5446
5540
  keys.sort((a, b) => Number(votes[a]?.votedAt || 0) - Number(votes[b]?.votedAt || 0))
5447
5541
  for (const key of keys.slice(0, keys.length - 100)) delete votes[key]
5448
5542
  }
5449
- LS.set(ANNOUNCEMENT_VOTES_KEY, JSON.stringify(votes))
5543
+ writeAnnouncementStorage(ANNOUNCEMENT_VOTES_KEY, JSON.stringify(votes))
5450
5544
  renderAnnouncementBoard()
5451
5545
  }
5452
5546
  function announcementVote(item) {
@@ -5461,7 +5555,7 @@ function announcementVote(item) {
5461
5555
  }
5462
5556
  function readAnnouncementHistory() {
5463
5557
  try {
5464
- const value = JSON.parse(LS.get(ANNOUNCEMENT_HISTORY_KEY, '[]'))
5558
+ const value = JSON.parse(readAnnouncementStorage(ANNOUNCEMENT_HISTORY_KEY, '[]'))
5465
5559
  return Array.isArray(value) ? value.filter(item => item && typeof item.id === 'string') : []
5466
5560
  } catch { return [] }
5467
5561
  }
@@ -5469,7 +5563,7 @@ function storeAnnouncementHistory(items) {
5469
5563
  const merged = new Map(readAnnouncementHistory().map(item => [item.id, item]))
5470
5564
  for (const item of items) if (item?.id) merged.set(item.id, item)
5471
5565
  const list = [...merged.values()].sort((a, b) => Number(b.publishedAt || 0) - Number(a.publishedAt || 0)).slice(0, 50)
5472
- LS.set(ANNOUNCEMENT_HISTORY_KEY, JSON.stringify(list))
5566
+ writeAnnouncementStorage(ANNOUNCEMENT_HISTORY_KEY, JSON.stringify(list))
5473
5567
  return list
5474
5568
  }
5475
5569
  function announcementBoardItems() {
@@ -5664,6 +5758,7 @@ function openAnnouncementModal(items, index = 0) {
5664
5758
  state.announcementIndex = Math.max(0, Math.min(Number(index) || 0, list.length - 1))
5665
5759
  renderAnnouncementModal()
5666
5760
  $('modal-announcement').classList.remove('hidden')
5761
+ globalThis.DshDiagnostics?.record('announcement.show',{phase:'shown',announcementId:state.announcement?.id,count:list.length})
5667
5762
  }
5668
5763
  function showAnnouncementAt(index) {
5669
5764
  if (!state.announcementItems.length) return
@@ -5685,6 +5780,7 @@ async function submitAnnouncementVote() {
5685
5780
  const message = forms ? forms.encode(item.id, poll.id, answer) : `Poll ${poll.id}: ${option.id}`
5686
5781
  if (!message) return toast(I18N.lang === 'en' ? 'Answers are too long. Please shorten them.' : '回答总长度过长,请适当精简。', 'err')
5687
5782
  const button = $('announcement-poll-submit')
5783
+ const diagnostic=globalThis.DshDiagnostics?.start('announcement.vote',{announcementId:item.id,count:poll.questions?.length||1})
5688
5784
  button.disabled = true
5689
5785
  const connection = captureConnection(), valid = () => connection.valid() && state.announcement === item
5690
5786
  state.announcementSubmitting = true
@@ -5717,21 +5813,25 @@ async function submitAnnouncementVote() {
5717
5813
  })
5718
5814
  data = await res.json().catch(() => ({}))
5719
5815
  }
5720
- if (!connection.valid()) return
5816
+ if (!connection.valid()) { diagnostic?.end({phase:'skipped',reason:'unavailable'}); return }
5721
5817
  if (res?.ok && data.ok) {
5722
5818
  storeAnnouncementVote(item.id, poll.id, answer.optionId || '')
5723
5819
  markAnnouncementSeen(item.id)
5820
+ diagnostic?.end({phase:'complete',httpStatus:res.status})
5724
5821
  if (valid()) renderAnnouncementPoll(item)
5725
5822
  renderAnnouncementHistory()
5726
5823
  toast(poll.legacy === false ? (I18N.lang === 'en' ? 'Submitted successfully' : '已成功提交') : t('announcement.voteThanks', { option: option.label }), 'ok')
5727
5824
  } else if (res?.status === 429) {
5825
+ diagnostic?.end({phase:'failed',httpStatus:res.status})
5728
5826
  toast(t('announcement.voteAgainLater'), 'err')
5729
5827
  button.disabled = false
5730
5828
  } else {
5829
+ diagnostic?.end({phase:'failed',httpStatus:res?.status||0})
5731
5830
  toast(t('announcement.voteFailed', { msg: data.error || res?.status || t('announcement.voteNetworkError') }), 'err')
5732
5831
  button.disabled = false
5733
5832
  }
5734
5833
  } catch (e) {
5834
+ diagnostic?.fail(e)
5735
5835
  if (valid()) toast(t('announcement.voteFailed', { msg: e.message || t('announcement.voteNetworkError') }), 'err')
5736
5836
  button.disabled = false
5737
5837
  } finally {
@@ -5744,6 +5844,7 @@ async function submitAnnouncementVote() {
5744
5844
  }
5745
5845
  function closeAnnouncement(markSeen) {
5746
5846
  if (markSeen) markAnnouncementsSeen(state.announcementItems)
5847
+ globalThis.DshDiagnostics?.record('announcement.close',{phase:markSeen?'acknowledged':'dismissed',announcementId:state.announcement?.id,count:state.announcementItems.length})
5747
5848
  state.announcement = null
5748
5849
  state.announcementItems = []
5749
5850
  state.announcementIndex = 0
@@ -5752,13 +5853,14 @@ function closeAnnouncement(markSeen) {
5752
5853
  async function fetchAnnouncements() {
5753
5854
  const base = updateBase()
5754
5855
  if (!base || !state.localVersion || isAppVersionWarningOpen()) return false
5856
+ const diagnostic=globalThis.DshDiagnostics?.start('announcement.fetch')
5755
5857
  try {
5756
5858
  const signal = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(8000) : undefined
5757
5859
  const url = base + '/announcements.json?t=' + Date.now()
5758
5860
  const res = signal ? await fetch(url, { cache: 'no-store', signal }) : await fetch(url, { cache: 'no-store' })
5759
- if (!res.ok) return false
5861
+ if (!res.ok) { diagnostic?.end({phase:'failed',httpStatus:res.status,reason:'http'}); return false }
5760
5862
  const raw = await res.text()
5761
- if (raw.length > 512 * 1024) return false
5863
+ if (raw.length > 512 * 1024) { diagnostic?.end({phase:'failed',reason:'too-large'}); return false }
5762
5864
  const data = JSON.parse(raw)
5763
5865
  const source = Array.isArray(data) ? data : (Array.isArray(data?.items) ? data.items : [data])
5764
5866
  const normalized = source.map(item => normalizeAnnouncement(item, base)).filter(Boolean)
@@ -5769,10 +5871,11 @@ async function fetchAnnouncements() {
5769
5871
  const items = normalized.filter(item => !seen[item.id])
5770
5872
  .sort((a, b) => b.publishedAt - a.publishedAt)
5771
5873
  // 新旧界面均提示未读公告;拉取期间新出现的版本提醒仍优先展示。
5772
- if (!items.length || state.announcement || isAppVersionWarningOpen()) return false
5874
+ 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 }
5773
5875
  openAnnouncementModal(items)
5876
+ diagnostic?.end({phase:'received',count:items.length,httpStatus:res.status})
5774
5877
  return true
5775
- } catch { return false }
5878
+ } catch(error) { diagnostic?.fail(error); return false }
5776
5879
  }
5777
5880
 
5778
5881
  function checkAnnouncements() {
@@ -6153,6 +6256,14 @@ function notify(title, body) {
6153
6256
  }
6154
6257
 
6155
6258
  async function sendTestNotification() {
6259
+ if (window.NativeBackground?.testNotification) {
6260
+ if (!await ensureNotify()) return toast(t('settings.notifyDenied'), 'err')
6261
+ const kind = $('test-notify-kind')?.value || 'approval'
6262
+ const sent = window.NativeBackground.testNotification(kind)
6263
+ applyBgConfigFromNative()
6264
+ toast(sent ? (I18N.lang === 'en' ? 'Test notification submitted. Check the selected system channel.' : '测试通知已提交,请检查所选系统通知渠道。') : t('settings.notifyDenied'), sent ? 'ok' : 'err')
6265
+ return
6266
+ }
6156
6267
  if (!CAP?.isNativePlatform?.()) {
6157
6268
  toast(t('settings.testNotifyUnavailable'), 'err')
6158
6269
  return
@@ -6199,6 +6310,11 @@ function applyBgConfigFromNative() {
6199
6310
  status.textContent = cfg.loginExpired ? t('settings.bgAuthFailed') : cfg.enabled && cfg.serviceRunning === false
6200
6311
  ? (I18N.lang === 'en' ? 'Background receiver is not running. Reopen the app or toggle to retry. ' : '后台接收未运行,返回应用或重新开关后重试。') + (cfg.serviceState || '')
6201
6312
  : cfg.enabled && cfg.serviceRunning === true ? (I18N.lang === 'en' ? 'Background receiver is running.' : '后台接收运行中。') + (cfg.lastSuccessAt ? ' ' + new Date(cfg.lastSuccessAt).toLocaleTimeString() : '') : ''
6313
+ const blocked = []
6314
+ if (cfg.notificationsEnabled === false) blocked.push(I18N.lang === 'en' ? 'System notifications disabled' : '系统通知已关闭')
6315
+ if (cfg.attentionChannelEnabled === false) blocked.push(I18N.lang === 'en' ? 'Approval channel disabled' : '审批提醒渠道已关闭')
6316
+ if (cfg.taskChannelEnabled === false) blocked.push(I18N.lang === 'en' ? 'Task result channel disabled' : '任务结果渠道已关闭')
6317
+ if (blocked.length) status.textContent = [status.textContent, ...blocked].filter(Boolean).join(' · ')
6202
6318
  status.classList.toggle('hidden', !status.textContent)
6203
6319
  }
6204
6320
  } catch {}
@@ -6214,7 +6330,7 @@ function saveBgConfig(enabled) {
6214
6330
  return saved
6215
6331
  }
6216
6332
  function syncBgConfig() {
6217
- if ($('opt-bg-poll')?.checked && state.token) saveBgConfig(true)
6333
+ if (state.token && bgBridge()?.saveBackgroundConfig) saveBgConfig(!!$('opt-bg-poll')?.checked)
6218
6334
  void syncPeakReminders()
6219
6335
  }
6220
6336
 
@@ -7675,7 +7791,13 @@ const THEME_META = [
7675
7791
  { id: 'light', sw: ['#F5F7F8', '#FFFFFF', '#176B87'] },
7676
7792
  { id: 'neutral', sw: ['#EEF1E8', '#FAFBF6', '#47643C'] },
7677
7793
  { id: 'mono', sw: ['#050505', '#333333', '#F5F5F5'] },
7678
- { id: 'fish', sw: ['#EAF6FF', '#FFFFFF', '#2F52D0'] }
7794
+ { id: 'fish', sw: ['#EAF6FF', '#FFFFFF', '#2F52D0'] },
7795
+ { id: 'penguin', sw: ['#EDF3FA', '#FFFFFF', '#2B6CB0'] },
7796
+ { id: 'penguin-night', sw: ['#10151B', '#1A222C', '#F2C230'] },
7797
+ { id: 'bocchi', sw: ['#FFD9E8', '#FFFFFF', '#D0105A'] },
7798
+ { id: 'nijika', sw: ['#FFF3D5', '#FFFFFF', '#94600C'] },
7799
+ { id: 'ryo', sw: ['#E9F1FA', '#FFFFFF', '#315D91'] },
7800
+ { id: 'kita', sw: ['#FFE9E5', '#FFFFFF', '#B6373C'] }
7679
7801
  ]
7680
7802
 
7681
7803
  function renderThemeBtn() {
@@ -7683,28 +7805,11 @@ function renderThemeBtn() {
7683
7805
  if (btn) btn.textContent = t('theme.' + window.DSHTheme.get())
7684
7806
  }
7685
7807
 
7686
- function renderThemeOptions() {
7687
- const box = $('theme-options')
7688
- if (!box) return
7689
- const cur = window.DSHTheme.get()
7690
- box.innerHTML = THEME_META.map(m => `
7691
- <button type="button" class="theme-option ${m.id === cur ? 'current' : ''}" data-theme="${m.id}" aria-pressed="${m.id === cur}" title="${t('theme.' + m.id)}">
7692
- <span class="theme-swatches">${m.sw.map(c => `<i style="background:${c}"></i>`).join('')}</span>
7693
- <span class="theme-name">${t('theme.' + m.id)}</span>
7694
- <span class="theme-check">${m.id === cur ? '✓' : ''}</span>
7695
- </button>`).join('')
7696
- box.querySelectorAll('.theme-option').forEach(btn =>
7697
- btn.addEventListener('click', () => {
7698
- window.DSHTheme.set(btn.dataset.theme)
7699
- renderThemeBtn()
7700
- renderThemeOptions()
7701
- $('modal-theme').classList.add('hidden')
7702
- }))
7703
- }
7704
-
7705
7808
  function openThemePanel() {
7706
- renderThemeOptions()
7707
- $('modal-theme').classList.remove('hidden')
7809
+ window.DSHTheme.openPicker({
7810
+ themes: THEME_META, label: id => t('theme.' + id), lang: I18N.lang,
7811
+ onSelect: id => { window.DSHTheme.set(id); renderThemeBtn() }
7812
+ })
7708
7813
  }
7709
7814
 
7710
7815
  function openDonateModal() {
@@ -7758,7 +7863,6 @@ function bindUi() {
7758
7863
  $('token-desc').textContent = state.token ? t('token.savedLocal') : t('token.notSet')
7759
7864
  })
7760
7865
  $('btn-theme').addEventListener('click', openThemePanel)
7761
- $('theme-close').addEventListener('click', () => $('modal-theme').classList.add('hidden'))
7762
7866
  $('btn-donate').addEventListener('click', openDonateModal)
7763
7867
  $('donate-close').addEventListener('click', () => $('modal-donate').classList.add('hidden'))
7764
7868
  document.addEventListener('click', (e) => {
@@ -7871,6 +7975,10 @@ function bindUi() {
7871
7975
  $('home-doctor').addEventListener('click', openDoctor)
7872
7976
  $('fb-cancel').addEventListener('click', closeFeedbackModal)
7873
7977
  $('fb-submit').addEventListener('click', submitFeedback)
7978
+ $('fb-msg').addEventListener('input', updateFeedbackLength)
7979
+ $('fb-copy-draft').addEventListener('click', async () => { const ok = await copyText($('fb-msg').value); toast(I18N.lang === 'en' ? (ok ? 'Copied' : 'Copy failed') : (ok ? '已复制全文' : '复制失败,请重试'), ok ? 'ok' : 'err') })
7980
+ $('fb-include-diagnostics').addEventListener('change',()=>{void loadCrashPreview()})
7981
+ $('fb-include-crashes').addEventListener('change',()=>{void loadCrashPreview()})
7874
7982
  $('feedback-success-confirm').addEventListener('click', closeFeedbackSuccess)
7875
7983
  $('modal-feedback-success').addEventListener('click', (e) => {
7876
7984
  if (e.target === $('modal-feedback-success')) closeFeedbackSuccess()
@@ -8075,6 +8183,14 @@ function bindUi() {
8075
8183
  })
8076
8184
  $('btn-server-speed').addEventListener('click', () => selectFastestServer({ silent: false }))
8077
8185
  $('btn-server-add').addEventListener('click', addServer)
8186
+ window.DshLanDiscovery?.mount($('btn-lan-discover'), result => {
8187
+ const url = new URL('dshremote://pair')
8188
+ url.searchParams.set('server', result.server); url.searchParams.set('token', result.token)
8189
+ if (!applyPairUrl(url.href)) return toast(t('send.failed'), 'err')
8190
+ const server = state.servers.find(entry => entry.url === result.server && entry.token === result.token)
8191
+ if (server) { server.note = String(result.name || '').slice(0, 40); saveServers(); renderServers() }
8192
+ openStreams(); toast(t('scan.paired'), 'ok')
8193
+ })
8078
8194
  $('btn-group-add').addEventListener('click', addGroup)
8079
8195
  $('group-select-btn').addEventListener('click', (e) => { e.stopPropagation(); toggleGroupMenu() })
8080
8196
  $('group-drawer-trigger').addEventListener('click', () => { groupDrawerOpen() ? closeGroupDrawer() : openGroupDrawer() })
@@ -8117,7 +8233,8 @@ function bindUi() {
8117
8233
  if (!confirm(t('settings.confirmReset'))) return
8118
8234
  clearTimeout(scheduleHistoryCacheSave._t)
8119
8235
  await window.DshHistory.cacheClear()
8120
- 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)
8236
+ await window.DshImageCache?.clear()
8237
+ LS.del('token'); LS.del('notify'); LS.del('server'); LS.del('mobileEnterAction'); LS.del('steerSendingEnabled'); LS.del('busySendMode'); resetAnnouncementStorage()
8121
8238
  if (bgBridge()?.saveBackgroundConfig) saveBgConfig(false)
8122
8239
  location.reload()
8123
8240
  })
@@ -8187,7 +8304,8 @@ function bindUi() {
8187
8304
  $('bg-interval').addEventListener('change', () => {
8188
8305
  if ($('opt-bg-poll')?.checked) saveBgConfig(true)
8189
8306
  })
8190
- $('opt-task-done')?.addEventListener('change', () => {
8307
+ $('opt-task-done')?.addEventListener('change', async event => {
8308
+ if (event.target.checked && !await ensureNotify()) { event.target.checked = false; toast(t('settings.notifyDenied'), 'err') }
8191
8309
  if (bgBridge()?.saveBackgroundConfig) saveBgConfig($('opt-bg-poll')?.checked)
8192
8310
  })
8193
8311
  renderPresets()
@@ -8215,7 +8333,7 @@ function bindUi() {
8215
8333
  bindFsPullRefresh()
8216
8334
 
8217
8335
  bindRail()
8218
- window.DshImagePreview?.configure?.({ resolvePath: chatImageRequest, resolveAttachment: chatImageAttachment })
8336
+ window.DshImagePreview?.configure?.({ resolvePath: chatImageRequest, resolveAttachment: chatImageAttachment, capture: captureChatImage })
8219
8337
 
8220
8338
  for (const id of ['history', 'question-body']) window.DshChatFiles?.bind($(id), () => {
8221
8339
  const c=captureConnection(),sessionId=id==='history'?state.current:state.questionModal?.sessionId
@@ -8245,6 +8363,7 @@ window.addEventListener('dsh-native-insets', applyNativeInsets)
8245
8363
  async function boot() {
8246
8364
  initToken()
8247
8365
  bindUi()
8366
+ syncBgConfig()
8248
8367
  renderAnnouncementBoard()
8249
8368
  renderLangBtn()
8250
8369
  bindNativeBack()
@@ -8362,19 +8481,29 @@ function mountOnboarding() {
8362
8481
  async function clearWorkflowData(kind) {
8363
8482
  const english = window.I18N?.lang === 'en'
8364
8483
  const messages = { history: english ? 'Clear cached conversation history on this device?' : '清除这台设备的会话历史缓存?主机记录保留。',
8365
- connection: english ? 'Remove the current address and its saved credential? Other addresses remain.' : '移除当前地址和保存的凭证?其他连接条目保留。',
8484
+ images: english ? 'Clear cached images on this device? Images will download again when viewed.' : '清除本机图片缓存?再次查看时会重新下载。',
8485
+ caches: english ? 'Clear history and image caches? Connections and preferences will be kept.' : '清除本机历史和图片缓存?保留连接、凭证与偏好设置。',
8486
+ connection: english ? 'Remove this connection, credential and its caches? Other connections will be kept.' : '移除当前地址、保存的凭证及其缓存?其他连接条目保留。',
8366
8487
  all: english ? 'Clear all Remote settings and credentials on this device and stop background reminders?' : '清除本机全部 Remote 配置与凭证,并停止后台轮询和提醒?主机数据保留。' }
8367
8488
  if (!confirm(messages[kind])) return
8368
- if (kind === 'history') {
8489
+ if (['history','images','caches'].includes(kind)) {
8369
8490
  clearTimeout(scheduleHistoryCacheSave._t)
8370
- await window.DshHistory.cacheClear()
8371
- for (let i=localStorage.length-1;i>=0;i--) { const key=localStorage.key(i); if (/^dsh-remote-(?:sessions|history)/.test(key)) localStorage.removeItem(key) }
8372
- return toast(english ? 'History cache cleared' : '历史缓存已清除', 'ok')
8491
+ if(kind!=='images')cancelHistoryLoad()
8492
+ const results=[]
8493
+ if(kind!=='images')results.push(await window.DshHistory.cacheClear())
8494
+ if(kind!=='history')results.push(await window.DshImageCache.clear())
8495
+ if(results.includes(false))return toast(english?'Some caches could not be cleared. Retry shortly.':'部分缓存未能清除,请稍后重试。','err')
8496
+ return toast(english ? 'Cache cleared' : '缓存已清除', 'ok')
8373
8497
  }
8374
8498
  window.NativeBackground?.saveBackgroundConfig?.(JSON.stringify({ enabled:false, base:'', token:'', clientId:'', intervalMin:1, notifyTaskDone:false }))
8375
8499
  window.NativeBackground?.savePeakReminderConfig?.(JSON.stringify({ enabled:false }))
8376
8500
  window.NativeBackground?.setPendingNotificationsEnabled?.(false)
8377
8501
  if (kind === 'connection') {
8502
+ const connection=captureConnection(),scope=historyCacheScope()
8503
+ cancelHistoryLoad()
8504
+ await window.DshImageCache.clear(scope)
8505
+ await window.DshHistory.cacheClear(scope)
8506
+ if(!connection.valid())return
8378
8507
  const current = currentServerEntry()
8379
8508
  if (current) state.servers = state.servers.filter(server => server.id !== current.id)
8380
8509
  state.groupActive[state.activeGroup] = ''
@@ -8383,8 +8512,11 @@ async function clearWorkflowData(kind) {
8383
8512
  return
8384
8513
  }
8385
8514
  await cancelPeakReminders()
8515
+ cancelHistoryLoad()
8386
8516
  clearTimeout(scheduleHistoryCacheSave._t)
8387
8517
  await window.DshHistory.cacheClear()
8518
+ await window.DshImageCache.clear()
8519
+ resetAnnouncementStorage()
8388
8520
  window.DshWorkflow.clearStorage()
8389
8521
  location.reload()
8390
8522
  }
package/public/build.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "schema": 1,
3
- "version": "0.8.1",
4
- "buildId": "a5766dea744290d7a52eb2a05017ffce3f038a1d3cbf0cc6bfbe684539961216"
3
+ "version": "0.8.3",
4
+ "buildId": "3fded6fb0396b7b688f815ad40b1c440c512b3aac9ca322bcfb187fe4be6ef65"
5
5
  }
@@ -0,0 +1,46 @@
1
+ /* Explicit clipboard actions over the loaded history; no duplicate source cache. */
2
+ ;(function(root) {
3
+ 'use strict'
4
+ const scopes = new WeakMap(); let nextScope = 0
5
+ const label = (zh, en) => root.I18N?.lang === 'en' ? en : zh
6
+ const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))
7
+ function scope(history) { if (!scopes.has(history)) scopes.set(history, String(++nextScope)); return scopes.get(history) }
8
+ function messageText(entries, seq) {
9
+ const entry = entries.find(row => String(row.seq) === String(seq))
10
+ if (!['user/message', 'assistant/message'].includes(entry?.event?.type)) return ''
11
+ const data = entry.event.data || {}, blocks = data.message?.content || data.content || []
12
+ return Array.isArray(blocks) ? blocks.filter(block => block?.type === 'text').map(block => String(block.text ?? '')).join('\n\n') : ''
13
+ }
14
+ function button(seq, history) {
15
+ return `<button type="button" class="chat-copy-button" data-chat-copy-markdown="${esc(seq)}" data-chat-copy-scope="${scope(history)}">${esc(label('复制 Markdown', 'Copy Markdown'))}</button>`
16
+ }
17
+ function code(source) {
18
+ return `<div class="chat-code"><button type="button" class="chat-copy-button" data-chat-copy-code>${esc(label('复制代码', 'Copy code'))}</button><pre><code>${esc(source)}</code></pre></div>`
19
+ }
20
+ function bind(box, host) {
21
+ if (!box || box.dataset.chatCopyBound) return
22
+ box.dataset.chatCopyBound = '1'
23
+ box.addEventListener('click', async event => {
24
+ const button = event.target.closest?.('[data-chat-copy-markdown],[data-chat-copy-code]')
25
+ if (!button || !box.contains(button) || button.disabled) return
26
+ const context = host.capture()
27
+ if (!context.valid()) return
28
+ let source
29
+ if (button.hasAttribute('data-chat-copy-markdown')) {
30
+ if (button.dataset.chatCopyScope !== scope(context.history)) return
31
+ source = messageText(context.history.visible, button.dataset.chatCopyMarkdown)
32
+ } else source = button.closest('.chat-code')?.querySelector('pre code')?.textContent
33
+ if (source == null || source === '') return
34
+ event.preventDefault(); event.stopPropagation()
35
+ button.disabled = true
36
+ try {
37
+ const ok = await host.copy(source)
38
+ if (context.valid()) host.notice(label(ok ? '已复制' : '复制失败,请重试', ok ? 'Copied' : 'Copy failed. Please retry.'), ok ? 'ok' : 'err')
39
+ } catch { if (context.valid()) host.notice(label('复制失败,请重试', 'Copy failed. Please retry.'), 'err') }
40
+ finally { button.disabled = false }
41
+ })
42
+ }
43
+ const api = { scope, messageText, button, code, bind }
44
+ if (typeof module !== 'undefined' && module.exports) module.exports = api
45
+ else root.DshChatCopy = api
46
+ })(typeof window === 'undefined' ? globalThis : window)