dsh-remote-plugin 0.8.3 → 0.8.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.
Files changed (48) hide show
  1. package/apk/dsh-remote.apk +0 -0
  2. package/approval-summary.mjs +115 -0
  3. package/gateway.cjs +642 -16
  4. package/index.mjs +12 -0
  5. package/insights.mjs +1 -1
  6. package/package.json +2 -1
  7. package/plugin-center.mjs +88 -17
  8. package/plugin-transaction.mjs +19 -3
  9. package/public/admin.html +30 -28
  10. package/public/admin.js +1 -1
  11. package/public/announcements.json +31 -0
  12. package/public/app.js +40 -47
  13. package/public/approval-summary.js +78 -0
  14. package/public/build.json +2 -2
  15. package/public/cache-upgrade.js +51 -0
  16. package/public/chat-copy.js +34 -21
  17. package/public/desktop/desktop.css +18 -39
  18. package/public/desktop/desktop.html +70 -96
  19. package/public/desktop/desktop.js +15 -42
  20. package/public/e2ee-transport.js +147 -0
  21. package/public/extensions.js +6 -6
  22. package/public/history.js +48 -1
  23. package/public/index.html +74 -93
  24. package/public/md.js +36 -18
  25. package/public/motion.js +1 -1
  26. package/public/plugin-center.css +1 -0
  27. package/public/plugin-center.js +92 -11
  28. package/public/plugin.html +25 -24
  29. package/public/relay-devices.js +74 -0
  30. package/public/relay-settings.css +7 -0
  31. package/public/relay-settings.js +11 -4
  32. package/public/session-deck.css +7 -1
  33. package/public/session-deck.js +1 -1
  34. package/public/skins/blue-fish/preview.html +3 -2
  35. package/public/skins/bocchi/preview.html +5 -4
  36. package/public/skins/kita/preview.html +6 -5
  37. package/public/skins/nijika/preview.html +6 -5
  38. package/public/skins/penguin/preview.html +3 -2
  39. package/public/skins/ryo/preview.html +6 -5
  40. package/public/sponsor-entry.js +20 -21
  41. package/public/styles.css +24 -24
  42. package/public/teams.js +2 -2
  43. package/public/update.json +8 -8
  44. package/public/version.json +1 -1
  45. package/public/workflow.js +3 -4
  46. package/skills/dsh-remote-doctor/references/wiki/plugins.md +1 -1
  47. package/task-board.mjs +2 -2
  48. package/teams.mjs +7 -2
package/public/app.js CHANGED
@@ -140,6 +140,7 @@ for (const key of ['server', 'token']) {
140
140
  window.DshExtensions?.invalidateCapabilities()
141
141
  window.DshFileInbox?.reset()
142
142
  window.DshSessionDeck?.reset()
143
+ window.DshApprovalSummary?.reset()
143
144
  if (typeof document !== 'undefined') document.getElementById('btn-insights')?.classList.add('hidden')
144
145
  if(typeof document!=='undefined') {
145
146
  const identityGeneration=connectionGeneration
@@ -236,7 +237,6 @@ function customSelectOptionCopy(option) {
236
237
  function openCustomSelect(select) {
237
238
  const trigger = select?._customSelectTrigger
238
239
  if (!select || !trigger || select.disabled) return
239
- closeFeedbackSheet()
240
240
  syncCustomSelect(select)
241
241
  customSelectCurrent = { select, trigger }
242
242
  const titleKey = CUSTOM_SELECT_TITLES[select.id]
@@ -314,12 +314,6 @@ function initCustomSelects() {
314
314
  }
315
315
 
316
316
  /* ---------------- 反馈 ---------------- */
317
- const FEEDBACK_LINKS = {
318
- githubIssues: 'https://github.com/Blank-not-black/dsh-Remote/issues',
319
- giteeIssues: 'https://gitee.com/Blankneverfails/dsh-Remote/issues',
320
- bili: 'https://space.bilibili.com/419009275/dynamic',
321
- repo: 'https://github.com/Blank-not-black/dsh-Remote'
322
- }
323
317
  async function copyText(text) {
324
318
  try { await navigator.clipboard.writeText(text); return true } catch {}
325
319
  try {
@@ -330,22 +324,6 @@ async function copyText(text) {
330
324
  ta.remove(); return ok
331
325
  } catch { return false }
332
326
  }
333
- function openFeedbackSheet() {
334
- window.DshExtensions?.closeShortcuts()
335
- $('feedback-backdrop').classList.remove('hidden')
336
- $('feedback-sheet').classList.remove('hidden')
337
- $('btn-feedback').setAttribute('aria-expanded', 'true')
338
- const first = $('feedback-sheet').querySelector('[role="menuitem"]')
339
- if (first) first.focus()
340
- }
341
- function closeFeedbackSheet() {
342
- $('feedback-backdrop').classList.add('hidden')
343
- $('feedback-sheet').classList.add('hidden')
344
- $('btn-feedback').setAttribute('aria-expanded', 'false')
345
- }
346
- function toggleFeedbackSheet() {
347
- $('feedback-sheet').classList.contains('hidden') ? openFeedbackSheet() : closeFeedbackSheet()
348
- }
349
327
  function doctorEnvironment() {
350
328
  let report = {}
351
329
  try { report = globalThis.DshDiagnostics?.report?.() || {} } catch {}
@@ -363,7 +341,6 @@ function doctorEnvironment() {
363
341
  }
364
342
  }
365
343
  function openDoctor() {
366
- closeFeedbackSheet()
367
344
  if (!window.DshDoctor) {
368
345
  toast(t('feedback.submitFailed', { msg: 'doctor unavailable' }), 'err')
369
346
  return
@@ -406,7 +383,7 @@ function openFeedbackSuccess() {
406
383
  }
407
384
  function closeFeedbackSuccess() {
408
385
  $('modal-feedback-success').classList.add('hidden')
409
- $('btn-feedback')?.focus()
386
+ $('btn-feedback-open')?.focus()
410
387
  }
411
388
  async function loadCrashPreview() {
412
389
  const generation=loadCrashPreview.generation=(loadCrashPreview.generation||0)+1
@@ -3163,7 +3140,7 @@ function eventHtml(entry, ctx = {}) {
3163
3140
  // Inline tool blocks duplicate the separated tool events; when those events exist the
3164
3141
  // calls live in the activity group, so an assistant message with nothing else disappears.
3165
3142
  if (!body) return ''
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>`
3143
+ inner = `<div class="msg ${esc(role)}" data-seq="${seq}"><div class="role">${esc(role === 'user' ? t('role.me') : t('role.dsh'))}</div>${body}</div>`
3167
3144
  }
3168
3145
  } else if (type === 'tool/call') {
3169
3146
  const name = data.name || data.toolName || t('tool.default')
@@ -3200,7 +3177,7 @@ function blockHtml(b,index=0,context={}) {
3200
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)})})
3201
3178
  }
3202
3179
  switch (b.type) {
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>` : ''
3180
+ 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, copyScope: window.DshChatCopy?.scope(state.history), copyCodeLabel: window.I18N?.lang === 'en' ? 'Copy code' : '复制代码' }) : esc(b.text ?? '')}</div>` : ''
3204
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>`
3205
3182
  case 'image': {
3206
3183
  if (b.attachment && window.DshImagePreview) return window.DshImagePreview.attachmentHtml(b.attachment, t('block.image'), state.current)
@@ -3210,7 +3187,7 @@ function blockHtml(b,index=0,context={}) {
3210
3187
  case 'thinking':
3211
3188
  case 'reasoning':
3212
3189
  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>`
3213
- case 'code': return window.DshChatCopy?.code(b.content ?? b.code ?? '') || `<pre>${esc(b.content ?? b.code ?? '')}</pre>`
3190
+ case 'code': return window.DshChatCopy?.code(b.content ?? b.code ?? '', b.language || b.lang || '', { scope: window.DshChatCopy?.scope(state.history) }) || `<pre>${esc(b.content ?? b.code ?? '')}</pre>`
3214
3191
  case 'tool-call':
3215
3192
  return `<details class="tool"><summary>🔧 ${esc(b.name || b.toolName || t('block.toolCall'))}</summary><pre>${esc(truncate(safeJson(b.arguments ?? b), 4000))}</pre></details>`
3216
3193
  case 'tool-result':
@@ -5447,6 +5424,8 @@ const ANNOUNCEMENTS_KEY = 'seenAnnouncementsV1'
5447
5424
  const ANNOUNCEMENT_HISTORY_KEY = 'announcementHistoryV1'
5448
5425
  const ANNOUNCEMENT_VOTES_KEY = 'announcementVotesV1'
5449
5426
  const ANNOUNCEMENTS_POLL_MS = 30 * 1000
5427
+ const announcementDeferred = new Set()
5428
+ const announcementDeferralKey = item => updateBase() + ':' + item.id
5450
5429
  let announcementCheckPromise = null
5451
5430
  let announcementPollTimer = null
5452
5431
  let announcementPollingStarted = false
@@ -5497,6 +5476,7 @@ function writeAnnouncementStorage(key, value) {
5497
5476
  })
5498
5477
  }
5499
5478
  function resetAnnouncementStorage() {
5479
+ announcementDeferred.clear()
5500
5480
  for (const key of [ANNOUNCEMENTS_KEY, ANNOUNCEMENT_HISTORY_KEY, ANNOUNCEMENT_VOTES_KEY]) {
5501
5481
  LS.del(key)
5502
5482
  clearAnnouncementFallback(key)
@@ -5844,6 +5824,11 @@ async function submitAnnouncementVote() {
5844
5824
  }
5845
5825
  function closeAnnouncement(markSeen) {
5846
5826
  if (markSeen) markAnnouncementsSeen(state.announcementItems)
5827
+ else {
5828
+ for (const item of state.announcementItems) if (!item.force) announcementDeferred.add(announcementDeferralKey(item))
5829
+ // Deferral is session-only and bounded; unread/history state is unchanged.
5830
+ while (announcementDeferred.size > 200) announcementDeferred.delete(announcementDeferred.values().next().value)
5831
+ }
5847
5832
  globalThis.DshDiagnostics?.record('announcement.close',{phase:markSeen?'acknowledged':'dismissed',announcementId:state.announcement?.id,count:state.announcementItems.length})
5848
5833
  state.announcement = null
5849
5834
  state.announcementItems = []
@@ -5869,6 +5854,7 @@ async function fetchAnnouncements() {
5869
5854
  renderAnnouncementBoard()
5870
5855
  const seen = readSeenAnnouncements()
5871
5856
  const items = normalized.filter(item => !seen[item.id])
5857
+ .filter(item => item.force || !announcementDeferred.has(announcementDeferralKey(item)))
5872
5858
  .sort((a, b) => b.publishedAt - a.publishedAt)
5873
5859
  // 新旧界面均提示未读公告;拉取期间新出现的版本提醒仍优先展示。
5874
5860
  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 }
@@ -7863,7 +7849,6 @@ function bindUi() {
7863
7849
  $('token-desc').textContent = state.token ? t('token.savedLocal') : t('token.notSet')
7864
7850
  })
7865
7851
  $('btn-theme').addEventListener('click', openThemePanel)
7866
- $('btn-donate').addEventListener('click', openDonateModal)
7867
7852
  $('donate-close').addEventListener('click', () => $('modal-donate').classList.add('hidden'))
7868
7853
  document.addEventListener('click', (e) => {
7869
7854
  if (e.target.closest('[data-donate-open]')) openDonateModal()
@@ -7952,7 +7937,7 @@ function bindUi() {
7952
7937
  $('conn-badge').addEventListener('click', () => { toast(t('common.refreshing')); openStreams(); void refreshAll() })
7953
7938
  window.DshExtensions?.bindShortcuts({ trigger: $('btn-plugin-shortcuts'), menu: $('plugin-shortcuts-menu'),
7954
7939
  config: () => optionalPluginConfig(), connected: () => !!state.token, hasSession: () => !!state.current,
7955
- beforeOpen: () => { closeFeedbackSheet(); closeGroupDrawer({ restoreFocus: false }) },
7940
+ beforeOpen: () => { closeGroupDrawer({ restoreFocus: false }) },
7956
7941
  open: route => { if (route === 'context') void openInsights('context', true); else showView('view-plugins', route) } })
7957
7942
  $('overview-refresh').addEventListener('click', () => {
7958
7943
  toast(t('common.refreshing'))
@@ -7960,18 +7945,6 @@ function bindUi() {
7960
7945
  void Promise.all([refreshAll(), checkAnnouncements()])
7961
7946
  })
7962
7947
  // 反馈
7963
- $('btn-feedback').addEventListener('click', (e) => { e.stopPropagation(); toggleFeedbackSheet() })
7964
- $('feedback-backdrop').addEventListener('click', closeFeedbackSheet)
7965
- $('feedback-sheet').addEventListener('click', (e) => {
7966
- if (e.target.closest('a[role="menuitem"]')) closeFeedbackSheet()
7967
- })
7968
- $('btn-copy-link').addEventListener('click', async () => {
7969
- const ok = await copyText(FEEDBACK_LINKS.repo)
7970
- toast(t(ok ? 'feedback.copied' : 'feedback.copyFailed'), ok ? 'ok' : 'err')
7971
- closeFeedbackSheet()
7972
- })
7973
- $('btn-write-feedback').addEventListener('click', () => { closeFeedbackSheet(); openFeedbackModal() })
7974
- $('btn-doctor').addEventListener('click', openDoctor)
7975
7948
  $('home-doctor').addEventListener('click', openDoctor)
7976
7949
  $('fb-cancel').addEventListener('click', closeFeedbackModal)
7977
7950
  $('fb-submit').addEventListener('click', submitFeedback)
@@ -7988,12 +7961,8 @@ function bindUi() {
7988
7961
  state.feedbackType = btn.dataset.fbType
7989
7962
  document.querySelectorAll('#fb-chips .fb-chip').forEach(b => b.classList.toggle('current', b === btn))
7990
7963
  }))
7991
- document.addEventListener('click', (e) => {
7992
- if (!e.target.closest('#feedback-sheet') && !e.target.closest('#btn-feedback')) closeFeedbackSheet()
7993
- })
7994
7964
  document.addEventListener('keydown', (e) => {
7995
- if (e.key === 'Escape' && !$('feedback-sheet').classList.contains('hidden')) { closeFeedbackSheet(); $('btn-feedback').focus() }
7996
- else if (e.key === 'Escape' && !$('modal-feedback-success').classList.contains('hidden')) closeFeedbackSuccess()
7965
+ if (e.key === 'Escape' && !$('modal-feedback-success').classList.contains('hidden')) closeFeedbackSuccess()
7997
7966
  else if (e.key === 'Escape' && isAppVersionWarningOpen()) closeAppVersionWarning(false)
7998
7967
  })
7999
7968
  $('btn-new-session').addEventListener('click', newSession)
@@ -8408,6 +8377,7 @@ function mountWorkflow() {
8408
8377
  settings: name => { showView('view-settings'); showSettingsPage(name) },
8409
8378
  plugins: () => showView('view-plugins'), models: loadSessionModels, send: sendMessage,
8410
8379
  feedback: openFeedbackModal,
8380
+ doctor: openDoctor,
8411
8381
  browse: () => { closeNewSessionModal(); showView('view-files') },
8412
8382
  register: async () => {
8413
8383
  const connection=captureConnection(), path=state.fs.path
@@ -8422,6 +8392,17 @@ function mountWorkflow() {
8422
8392
  command: runSlashCommand, refresh: refreshAll, retry: () => { startOverviewDetection(true); void refreshAll() },
8423
8393
  operations: () => { const connection=captureConnection(); return { url:apiUrl,headers:{authorization:'Bearer '+connection.token},valid:connection.valid } },
8424
8394
  relay: () => { const connection=captureConnection(); return { url:()=>adminApiUrl('/admin/api/relay'),headers:{authorization:'Bearer '+connection.token},valid:connection.valid,connected:!!connection.token } },
8395
+ e2eeConnect: (origin, connection) => {
8396
+ if (!connection.valid()) return
8397
+ const token = connection.headers.authorization.slice(7)
8398
+ closeStream('mux'); closeStream('host'); stopPolling(); state.wsTicket = null
8399
+ if (applyPairUrl('dshremote://pair?' + new URLSearchParams({ server: origin, token }).toString())) { void refreshAll(); openStreams() }
8400
+ },
8401
+ e2eeModeChange: (origin, connection) => {
8402
+ if (!connection.valid() || new URL(apiUrl('/relay'),location.href).origin !== origin) return
8403
+ closeStream('mux'); closeStream('host'); stopPolling(); state.wsTicket = null
8404
+ syncBgConfig(); void refreshAll(); openStreams()
8405
+ },
8425
8406
  discover: () => { if (confirm('登记当前绑定目录下的子目录为工作区?')) void refreshWorkbench({ discover: true }) },
8426
8407
  files: () => {
8427
8408
  const workspace = workspaceForSession(state.byId.get(state.current))
@@ -8505,6 +8486,8 @@ async function clearWorkflowData(kind) {
8505
8486
  await window.DshHistory.cacheClear(scope)
8506
8487
  if(!connection.valid())return
8507
8488
  const current = currentServerEntry()
8489
+ const remaining = current ? state.servers.filter(server => server.id !== current.id) : state.servers
8490
+ if (!remaining.some(server => server.url === state.server) && window.NativeE2ee?.remove?.(state.server) === false) return toast(english ? 'Unable to remove encrypted pairing.' : '加密配对未能清理,请重试。','err')
8508
8491
  if (current) state.servers = state.servers.filter(server => server.id !== current.id)
8509
8492
  state.groupActive[state.activeGroup] = ''
8510
8493
  state.token = ''; state.server = ''; LS.del('token'); LS.del('server'); saveServers()
@@ -8518,6 +8501,7 @@ async function clearWorkflowData(kind) {
8518
8501
  await window.DshImageCache.clear()
8519
8502
  resetAnnouncementStorage()
8520
8503
  window.DshWorkflow.clearStorage()
8504
+ if (window.NativeE2ee?.clear?.() === false) return toast(english ? 'Encrypted pairing could not be cleared. Retry.' : '加密配对未能清理,请重试。','err')
8521
8505
  location.reload()
8522
8506
  }
8523
8507
 
@@ -8563,3 +8547,12 @@ globalThis.DshFileInbox?.mount({ capture: captureConnection, url: apiUrl,
8563
8547
  headers: connection => ({ authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }),
8564
8548
  native: () => CAP?.isNativePlatform?.() ? window.NativeFile : null })
8565
8549
  globalThis.DshSessionDeck?.mount({ context: () => ({ sessionId: state.current, inChat: !$('view-session').classList.contains('hidden') }) })
8550
+ globalThis.DshApprovalSummary?.mount({ capture: captureConnection, items: () => state.approvals,
8551
+ url: (connection, path) => connection.server + path,
8552
+ headers: connection => ({ authorization: 'Bearer ' + connection.token, ...clientIdHeaders() }) })
8553
+ globalThis.DshCacheUpgrade?.mount({
8554
+ scopes:()=>state.servers.map(server=>historyCacheScope(server.url,serverToken(server))),
8555
+ safe:()=>!state.current&&!state.approvals.length&&!state.questions.length&&!composerSending
8556
+ &&![...document.querySelectorAll('textarea,input:not([type="checkbox"]):not([type="radio"])')].some(input=>input.getBoundingClientRect().width&&input.value)
8557
+ &&!document.querySelector('[data-transfer-id]')&&!state.sessions.some(session=>session.running)
8558
+ })
@@ -0,0 +1,78 @@
1
+ /* Explicit, cached explanations. No summary request is made during rendering. */
2
+ ;(function (root) {
3
+ 'use strict'
4
+ const cache = new Map()
5
+ let config, scope, mounted = false
6
+ const text = (zh, en) => root.I18N?.lang === 'en' ? en : zh
7
+ const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;' }[c]))
8
+ function context() {
9
+ const connection = config?.capture()
10
+ if (scope && !scope.valid()) reset()
11
+ if (connection) scope = connection
12
+ return connection
13
+ }
14
+ const keyOf = item => JSON.stringify([item.sessionId, item.approvalId, item.callId || '', item.reason || ''])
15
+ const eligible = item => /^Auto review denied tool "[^"]+"(?::|$)/.test(item?.reason || '')
16
+ const current = item => config.items().some(value => keyOf(value) === keyOf(item))
17
+ function html(item) {
18
+ if (!eligible(item)) return ''
19
+ context()
20
+ const row = cache.get(keyOf(item))
21
+ const label = text('AI 中文总结(消耗 token)', 'AI Chinese summary (uses tokens)')
22
+ return '<section class="approval-ai" data-approval-ai="' + esc(item.approvalId) + '" data-ai-session="' + esc(item.sessionId) + '">'
23
+ + '<button type="button" class="deck-summary-button" data-ai-generate' + (row ? ' disabled' : '') + '>' + (row?.phase === 'loading' ? text('正在生成…', 'Generating…') : label) + '</button>'
24
+ + '<p class="approval-ai-copy" role="status">' + esc(row?.text || text('按需生成,仅供参考;请结合完整请求决定。', 'Optional reference; decide using the full request.')) + '</p></section>'
25
+ }
26
+ function update(item) {
27
+ for (const node of root.document?.querySelectorAll('[data-approval-ai]') || []) {
28
+ if (node.dataset.approvalAi !== item.approvalId || node.dataset.aiSession !== item.sessionId) continue
29
+ // Set text only; model output is never interpreted as HTML or Markdown.
30
+ const row = cache.get(keyOf(item)), button = node.querySelector('[data-ai-generate]'), copy = node.querySelector('[role="status"]')
31
+ if (button) { button.disabled = !!row; button.textContent = row?.phase === 'loading' ? text('正在生成…','Generating…') : text('AI 中文总结(消耗 token)','AI Chinese summary (uses tokens)') }
32
+ if (copy && row) copy.textContent = row.text
33
+ }
34
+ }
35
+ async function generate(item) {
36
+ const connection = context(), key = keyOf(item)
37
+ if (!connection?.valid() || !eligible(item) || cache.has(key) || !current(item)) return
38
+ if (!root.confirm(text('将此审批的工具名和审查理由交给当前会话配置的模型生成中文短摘要,会消耗 token;不发送完整对话或工具参数。摘要仅供参考,原始请求和审批决定保持不变。是否继续?',
39
+ 'Send this approval’s tool name and review reason to the current session model for a Chinese summary? This uses tokens. Full conversation and tool arguments are excluded. The summary is only a reference; the request and approval decision remain unchanged.'))) return
40
+ if (!connection.valid() || !current(item)) return
41
+ while (cache.size >= 40) {
42
+ const old = [...cache].find(([, value]) => value.phase !== 'loading')
43
+ if (!old) return
44
+ cache.delete(old[0])
45
+ }
46
+ const controller = new AbortController(), row = { phase: 'loading', controller, text: text('正在生成,不影响允许或拒绝。','Generating; Allow and Reject remain available.') }
47
+ cache.set(key, row); update(item)
48
+ const timer = setTimeout(() => controller.abort(), 18_000)
49
+ try {
50
+ const response = await root.fetch(config.url(connection, '/remote/api/approval-summary'), { method: 'POST',
51
+ headers: { ...config.headers(connection), 'content-type':'application/json' },
52
+ body: JSON.stringify({ sessionId:item.sessionId, approvalId:item.approvalId, ...(item.callId ? { callId:item.callId } : {}), consent:true }),
53
+ signal:controller.signal })
54
+ const value = await response.json()
55
+ if (!response.ok || value.ok !== true || typeof value.summary !== 'string' || value.summary.length > 240) throw Error('unavailable')
56
+ row.phase = 'done'; row.text = text('AI 中文总结(仅供参考):','AI Chinese summary (reference only): ') + value.summary
57
+ } catch {
58
+ row.phase = 'error'; row.text = text('摘要未生成,可能已产生 token 消耗;请查看原始理由。本请求不会自动重试。','Summary unavailable; tokens may have been used. Read the original reason. This request will not retry automatically.')
59
+ } finally {
60
+ clearTimeout(timer)
61
+ if (connection.valid() && cache.get(key) === row && current(item)) update(item)
62
+ }
63
+ }
64
+ function reset() { for (const row of cache.values()) row.controller?.abort(); cache.clear(); scope = null }
65
+ function mount(value) {
66
+ config = value
67
+ if (mounted) return
68
+ mounted = true
69
+ root.document?.addEventListener('click', event => {
70
+ const button = event.target?.closest?.('[data-ai-generate]'), node = button?.closest('[data-approval-ai]')
71
+ if (!node) return
72
+ event.preventDefault(); event.stopPropagation()
73
+ const item = config.items().find(item => item.approvalId === node.dataset.approvalAi && item.sessionId === node.dataset.aiSession)
74
+ if (item) void generate(item)
75
+ })
76
+ }
77
+ root.DshApprovalSummary = { html, mount, reset, generate }
78
+ })(window)
package/public/build.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "schema": 1,
3
- "version": "0.8.3",
4
- "buildId": "3fded6fb0396b7b688f815ad40b1c440c512b3aac9ca322bcfb187fe4be6ef65"
3
+ "version": "0.8.4",
4
+ "buildId": "d269ebf822f3b66656a0f760a7c3063abdcc46fd700f90edb9e8e6fdb8efb83e"
5
5
  }
@@ -0,0 +1,51 @@
1
+ /* Trusted package/build identity and upgrade handling. Never clears credentials. */
2
+ ;(function(root){
3
+ 'use strict'
4
+ const HEX=/^[a-f0-9]{64}$/, loaded=root.document?.querySelector('meta[name="dsh-remote-build"]')?.content
5
+ const script=root.document?.currentScript?.src
6
+ let config,checking=false,banner,autoReloaded=false
7
+ const text=(zh,en)=>root.I18N?.lang==='en'?en:zh
8
+ async function check(){
9
+ if(checking||!config||!HEX.test(loaded||'')||!script)return
10
+ checking=true
11
+ try{
12
+ const url=new URL('build.json',script);url.searchParams.set('fresh',String(Date.now()))
13
+ const response=await root.fetch(url.href,{cache:'no-store',signal:AbortSignal.timeout(5000)})
14
+ if(!response.ok)return
15
+ const next=(await response.json()).buildId
16
+ if(!HEX.test(next||'')||next===loaded)return
17
+ if(!banner){
18
+ banner=root.document.createElement('aside');banner.className='cache-upgrade-notice';banner.setAttribute('role','status')
19
+ banner.style.cssText='position:fixed;z-index:39;top:8px;left:12px;right:12px;padding:12px;background:var(--dsr-panel,#fff);color:var(--dsr-text,#182331);border:1px solid var(--dsr-line,#778899);border-radius:12px;display:flex;gap:10px;align-items:center'
20
+ const copy=root.document.createElement('span'),button=root.document.createElement('button')
21
+ copy.textContent=text('新界面已就绪,重新载入即可更新;未发送内容会保留。','An updated interface is ready. Reload to update; unsent content is preserved.')
22
+ button.type='button';button.textContent=text('重新载入','Reload')
23
+ button.style.minHeight='44px'
24
+ button.addEventListener('click',()=>{if(config.safe())root.location.reload();else root.alert(text('请先处理当前审批、上传或未发送内容,再重新载入。','Finish pending approvals/uploads or save unsent content before reloading.'))})
25
+ banner.append(copy,button);root.document.body.append(banner)
26
+ }
27
+ // A running turn, draft, approval or upload must never be interrupted.
28
+ // One automatic reload per target build also prevents a bad cache loop.
29
+ const key='dshRemoteBuildReload:'+root.location.pathname
30
+ if(!autoReloaded&&config.safe()){
31
+ let saved
32
+ try{saved=root.sessionStorage.getItem(key)}catch{return}
33
+ if(saved===next)return
34
+ try{root.sessionStorage.setItem(key,next);if(root.sessionStorage.getItem(key)!==next)return}catch{return}
35
+ autoReloaded=true;root.location.reload()
36
+ }
37
+ }catch{}finally{checking=false}
38
+ }
39
+ async function migrate(){
40
+ try{const scopes=config?.scopes?.();if(scopes?.length)await root.DshHistory?.migrateLegacy?.(scopes)}catch{}
41
+ }
42
+ function mount(value){
43
+ if(config)return
44
+ config=value
45
+ const run=()=>{void check();void migrate()}
46
+ root.setTimeout(run,1500);root.setInterval(run,60_000)
47
+ root.document?.addEventListener('visibilitychange',()=>{if(!root.document.hidden)run()})
48
+ root.addEventListener?.('online',run)
49
+ }
50
+ root.DshCacheUpgrade={mount,check,migrate}
51
+ })(window)
@@ -1,46 +1,59 @@
1
- /* Explicit clipboard actions over the loaded history; no duplicate source cache. */
1
+ /* Clipboard actions belong to one displayed source block, never a whole reply. */
2
2
  ;(function(root) {
3
3
  'use strict'
4
4
  const scopes = new WeakMap(); let nextScope = 0
5
+ const resetTimers = new WeakMap()
5
6
  const label = (zh, en) => root.I18N?.lang === 'en' ? en : zh
6
7
  const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))
7
8
  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>`
9
+ function code(source, language = '', options = {}) {
10
+ const lang = /^[a-zA-Z0-9_+.-]{1,40}$/.test(String(language)) ? String(language) : ''
11
+ const markdown = /^(?:md|markdown)$/i.test(lang)
12
+ const name = markdown ? 'Markdown' : lang || label('代码', 'Code')
13
+ const action = markdown ? label('复制 Markdown', 'Copy Markdown') : options.label || label('复制代码', 'Copy code')
14
+ const scoped = options.scope == null ? '' : ` data-chat-copy-scope="${esc(options.scope)}"`
15
+ return `<div class="chat-code"><div class="chat-code-toolbar"><span class="chat-code-language">${esc(name)}</span><button type="button" class="chat-copy-button" data-chat-copy-code${scoped} aria-label="${esc(action)}" title="${esc(action)}"><svg class="chat-copy-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3"/></svg><svg class="chat-copy-check" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12 4 4L19 6"/></svg><span class="chat-copy-status" aria-live="polite"></span></button></div><pre><code>${esc(source)}</code></pre></div>`
19
16
  }
20
17
  function bind(box, host) {
21
18
  if (!box || box.dataset.chatCopyBound) return
22
19
  box.dataset.chatCopyBound = '1'
23
20
  box.addEventListener('click', async event => {
24
- const button = event.target.closest?.('[data-chat-copy-markdown],[data-chat-copy-code]')
21
+ const button = event.target.closest?.('[data-chat-copy-code]')
25
22
  if (!button || !box.contains(button) || button.disabled) return
26
23
  const context = host.capture()
27
24
  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
25
+ if (context.history && button.dataset.chatCopyScope !== scope(context.history)) return
26
+ const source = button.closest('.chat-code')?.querySelector('pre code')?.textContent
33
27
  if (source == null || source === '') return
34
28
  event.preventDefault(); event.stopPropagation()
29
+ clearTimeout(resetTimers.get(button))
30
+ delete button.dataset.copyState
35
31
  button.disabled = true
32
+ const original = button.getAttribute('aria-label')
33
+ const status = button.querySelector('.chat-copy-status')
34
+ if (status) status.textContent = ''
36
35
  try {
37
36
  const ok = await host.copy(source)
38
- if (context.valid()) host.notice(label(ok ? '已复制' : '复制失败,请重试', ok ? 'Copied' : 'Copy failed. Please retry.'), ok ? 'ok' : 'err')
37
+ if (context.valid() && box.contains(button)) {
38
+ button.dataset.copyState = ok ? 'copied' : 'error'
39
+ const feedback = label(ok ? '已复制' : '复制失败,请重试', ok ? 'Copied' : 'Copy failed. Please retry.')
40
+ button.setAttribute('aria-label', feedback); button.title = feedback
41
+ if (status) status.textContent = ok ? feedback : ''
42
+ if (!ok) host.notice(feedback, 'err')
43
+ }
39
44
  } catch { if (context.valid()) host.notice(label('复制失败,请重试', 'Copy failed. Please retry.'), 'err') }
40
- finally { button.disabled = false }
45
+ finally {
46
+ button.disabled = false
47
+ resetTimers.set(button, setTimeout(() => {
48
+ delete button.dataset.copyState
49
+ resetTimers.delete(button)
50
+ if (status) status.textContent = ''
51
+ if (original) { button.setAttribute('aria-label', original); button.title = original }
52
+ }, 1600))
53
+ }
41
54
  })
42
55
  }
43
- const api = { scope, messageText, button, code, bind }
56
+ const api = { scope, code, bind }
44
57
  if (typeof module !== 'undefined' && module.exports) module.exports = api
45
58
  else root.DshChatCopy = api
46
59
  })(typeof window === 'undefined' ? globalThis : window)
@@ -70,40 +70,9 @@ a.ds-btn { text-decoration: none; }
70
70
  .ds-nav-ico svg { width: 17px; height: 17px; display: block; }
71
71
  .ds-nav-item.active .ds-nav-ico { color: var(--dsr-accent-strong); }
72
72
 
73
- /* 侧边栏底部常驻反馈入口 */
74
- .ds-feedback { position: relative; margin-top: 4px; }
75
- .ds-feedback-btn {
76
- display: flex; align-items: center; gap: 8px; width: 100%;
77
- text-align: left; border: none; background: transparent; color: var(--dsr-text);
78
- font: inherit; font-size: 13px; padding: 9px 10px; border-radius: 9px; cursor: pointer;
79
- }
80
- .ds-feedback-btn:hover { background: var(--dsr-bg-2); }
81
- .ds-feedback-btn svg { width: 16px; height: 16px; flex-shrink: 0; color: var(--dsr-info); }
82
- .ds-feedback-menu {
83
- position: absolute; bottom: calc(100% + 8px); left: 0; right: 0; z-index: 45;
84
- background: var(--dsr-bg-2); border: 1px solid var(--dsr-line); border-radius: 14px;
85
- box-shadow: 0 12px 34px var(--dsr-shadow); padding: 6px;
86
- display: flex; flex-direction: column; gap: 2px;
87
- animation: ds-feedback-in .18s ease;
88
- }
89
- .ds-feedback-menu.hidden { display: none; }
90
- .ds-feedback-item {
91
- width: 100%; min-height: 44px; display: flex; align-items: center; gap: 10px;
92
- padding: 7px 8px; border-radius: 10px; border: none; background: transparent; color: var(--dsr-text);
93
- font: inherit; text-align: left; cursor: pointer; text-decoration: none;
94
- }
95
- .ds-feedback-item:hover, .ds-feedback-item:focus-visible { background: var(--dsr-bg); }
96
- .ds-feedback-ico {
97
- width: 32px; height: 32px; border-radius: 9px; flex-shrink: 0;
98
- display: grid; place-items: center; background: var(--dsr-panel); border: 1px solid var(--dsr-line); color: var(--dsr-accent-strong);
99
- }
100
- .ds-feedback-ico svg { width: 16px; height: 16px; fill: currentColor; }
101
- .ds-feedback-body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 1px; }
102
- .ds-feedback-name { font-size: 13px; font-weight: 600; }
103
- .ds-feedback-desc { font-size: 11px; color: var(--dsr-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
104
- @keyframes ds-feedback-in { from { opacity: 0; transform: translateY(6px) } to { opacity: 1; transform: translateY(0) } }
105
-
106
73
  /* ---------- 工作台 ---------- */
74
+ .ds-action-item{width:100%;min-height:44px;display:flex;align-items:center;gap:10px;padding:7px 8px;border-radius:10px;border:none;background:transparent;color:var(--dsr-text);font:inherit;text-align:left;cursor:pointer;text-decoration:none}
75
+ .ds-action-item:hover,.ds-action-item:focus-visible{background:var(--dsr-bg)}
107
76
  .ds-workbench { border: 1px solid var(--dsr-line); border-radius: 12px; background: var(--dsr-bg-2); padding: 8px; display: flex; flex-direction: column; gap: 6px; }
108
77
  .ds-wb-badge { font-size: 11.5px; font-weight: 700; color: var(--dsr-accent-strong); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
109
78
  .ds-wb-unbound, .ds-wb-bound { display: flex; flex-direction: column; gap: 6px; }
@@ -175,7 +144,6 @@ html.reorder-scroll-lock body { overscroll-behavior: none; }
175
144
  .ds-icon-btn { width: 32px; height: 32px; border-radius: 9px; border: 1px solid var(--dsr-line); background: var(--dsr-bg-2); color: var(--dsr-accent-strong); cursor: pointer; font-size: 15px; display: inline-flex; align-items: center; justify-content: center; }
176
145
  .ds-icon-btn svg { width: 17px; height: 17px; display: block; }
177
146
  .ds-icon-btn:hover { filter: brightness(1.06); }
178
- #btn-donate { color: var(--dsr-accent-2); }
179
147
  #btn-stats-top { color: var(--dsr-info); }
180
148
  #btn-cancel { color: var(--dsr-error); border-color: var(--dsr-error-line); }
181
149
  #btn-mobile-nav { display: none; }
@@ -828,10 +796,21 @@ input:focus-visible, select:focus-visible, textarea:focus-visible {
828
796
 
829
797
  /* Conversation copy controls remain reachable on touch and keyboard. */
830
798
  .ds-msg .role { display:flex; align-items:center; justify-content:space-between; gap:12px; opacity:1; }
831
- .chat-copy-button { min-height:36px; padding:4px 9px; border:1px solid var(--dsr-line); border-radius:8px; background:var(--dsr-panel); color:var(--dsr-muted); font:inherit; font-size:11px; cursor:pointer; }
832
- .chat-copy-button:focus-visible { outline:2px solid var(--dsr-accent); outline-offset:2px; }
833
- .chat-copy-button:disabled { opacity:.6; cursor:wait; }
834
- .chat-code { position:relative; margin:8px 0; }
835
- .chat-code > .chat-copy-button { display:block; margin-left:auto; margin-bottom:3px; }
799
+ .chat-code { margin:10px 0; min-width:0; max-width:100%; border:1px solid var(--dsr-line); border-radius:10px; background:var(--dsr-code-bg); overflow:hidden; }
800
+ .chat-code-toolbar { display:flex; align-items:center; justify-content:space-between; gap:8px; min-height:40px; padding:0 3px 0 12px; border-bottom:1px solid var(--dsr-line); white-space:normal; }
801
+ .chat-code-language { color:var(--dsr-muted); font:500 11px/1.4 ui-monospace,monospace; letter-spacing:.02em; }
802
+ .chat-copy-button { position:relative; display:inline-flex; flex:none; align-items:center; justify-content:center; width:44px; height:44px; min-height:44px; padding:12px; margin:0; border:0; border-radius:7px; background:transparent; color:var(--dsr-muted); box-shadow:none; font:inherit; cursor:pointer; touch-action:manipulation; }
803
+ .chat-copy-button svg { display:block; width:18px; height:18px; flex:none; pointer-events:none; }
804
+ .chat-copy-button .chat-copy-check { display:none; }
805
+ .chat-copy-button:hover { color:var(--dsr-accent-strong,var(--dsr-accent)); background:var(--dsr-accent-soft); }
806
+ .chat-copy-button:focus-visible { outline:2px solid var(--dsr-accent); outline-offset:-3px; }
807
+ .chat-copy-button:disabled { opacity:.55; cursor:wait; }
808
+ .chat-copy-button[data-copy-state=copied] { color:var(--dsr-success,var(--dsr-accent-strong,var(--dsr-accent))); }
809
+ .chat-copy-button[data-copy-state=copied] .chat-copy-icon { display:none; }
810
+ .chat-copy-button[data-copy-state=copied] .chat-copy-check { display:block; }
811
+ .chat-copy-status { position:absolute; right:42px; padding:3px 6px; border-radius:4px; background:var(--dsr-code-bg); color:inherit; font-size:11px; line-height:1.4; white-space:nowrap; pointer-events:none; }
812
+ .chat-copy-status:empty { display:none; }
813
+ .chat-code > pre { margin:0; border:0; border-radius:0; padding:12px 14px; background:transparent; white-space:pre; word-break:normal; }
814
+ .chat-code > pre > code { display:block; padding:0; border-radius:0; background:transparent; color:inherit; white-space:pre; overflow-wrap:normal; word-break:normal; }
836
815
  .feedback-length { margin:4px 0; color:var(--dsr-muted); font-size:12px; }
837
816
  #fb-msg[aria-invalid="true"] { outline:2px solid var(--dsr-danger, #dc4444); }