dsh-remote-plugin 0.8.8 → 0.9.1

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 (66) hide show
  1. package/README.en.md +16 -5
  2. package/README.md +15 -4
  3. package/apk/dsh-remote.apk +0 -0
  4. package/gateway.cjs +583 -84
  5. package/index.mjs +1 -0
  6. package/package.json +8 -3
  7. package/public/activity.js +97 -10
  8. package/public/admin.html +34 -33
  9. package/public/admin.js +10 -2
  10. package/public/announcements.json +36 -0
  11. package/public/app.js +1564 -226
  12. package/public/bc-integration.css +81 -0
  13. package/public/build.json +2 -2
  14. package/public/composer-tools.css +184 -0
  15. package/public/composer-tools.js +888 -0
  16. package/public/desktop/desktop.html +94 -73
  17. package/public/desktop/desktop.js +726 -83
  18. package/public/e2ee-config.js +5 -0
  19. package/public/e2ee-transport.js +23 -4
  20. package/public/file-inbox.js +77 -18
  21. package/public/genui.css +10 -0
  22. package/public/genui.js +22 -4
  23. package/public/history.js +114 -17
  24. package/public/host-queue.js +232 -0
  25. package/public/host-schedule.js +301 -0
  26. package/public/host-state.css +19 -0
  27. package/public/index.html +332 -140
  28. package/public/md.js +21 -1
  29. package/public/network.js +33 -1
  30. package/public/onboarding.js +3 -3
  31. package/public/operations.js +4 -3
  32. package/public/plan-review.css +297 -0
  33. package/public/plan-review.js +642 -0
  34. package/public/plugin.html +29 -28
  35. package/public/relay-autopair.js +30 -10
  36. package/public/relay-devices.js +7 -3
  37. package/public/relay-settings.css +11 -0
  38. package/public/relay-settings.js +372 -30
  39. package/public/session-cache.js +85 -0
  40. package/public/session-management.css +61 -0
  41. package/public/session-management.js +742 -0
  42. package/public/session-search.css +137 -0
  43. package/public/session-search.js +977 -0
  44. package/public/skins/blue-fish/preview.html +3 -3
  45. package/public/skins/bocchi/preview.html +5 -5
  46. package/public/skins/kita/preview.html +6 -6
  47. package/public/skins/miku/SOURCES.json +10 -0
  48. package/public/skins/miku/chibi.png +0 -0
  49. package/public/skins/miku/preview.html +33 -0
  50. package/public/skins/miku/skin.css +82 -0
  51. package/public/skins/nijika/preview.html +6 -6
  52. package/public/skins/penguin/preview.html +3 -3
  53. package/public/skins/ryo/preview.html +6 -6
  54. package/public/slash-suggestions.js +15 -3
  55. package/public/sponsor-entry.js +11 -3
  56. package/public/styles.css +141 -21
  57. package/public/subagents.css +5 -0
  58. package/public/subagents.js +52 -0
  59. package/public/theme-vars.css +65 -1
  60. package/public/theme.js +4 -3
  61. package/public/turn-diff.css +323 -0
  62. package/public/turn-diff.js +778 -0
  63. package/public/update.json +12 -12
  64. package/public/version.json +1 -1
  65. package/public/workflow.css +305 -34
  66. package/public/workflow.js +141 -41
@@ -0,0 +1,5 @@
1
+ /* E2EE transport policy: runtime plan gating decides whether the relay UI is offered. */
2
+ ;(function(root) {
3
+ 'use strict'
4
+ root.DSH_REMOTE_E2EE_DISABLED = false
5
+ })(typeof window === 'undefined' ? globalThis : window)
@@ -1,6 +1,10 @@
1
1
  /* Packaged Android WebUI: paired public origins always use the native TLS proxy. */
2
2
  ;(function(root) {
3
3
  'use strict'
4
+ if (root.DSH_REMOTE_E2EE_DISABLED === true) {
5
+ root.DshE2eeTransport = { resolve: input => input, mount() {} }
6
+ return
7
+ }
4
8
  const bridge = root.NativeE2ee
5
9
  if (!bridge?.resolve) return
6
10
  const active = new Set()
@@ -265,8 +269,8 @@
265
269
  } })
266
270
  })
267
271
  const modeLabel = document.createElement('label'), modeSwitch = document.createElement('input'), modeText = document.createElement('span'), modeStatus = document.createElement('p')
268
- modeLabel.className = 'relay-encryption-switch'; modeSwitch.type = 'checkbox'; modeSwitch.checked = true; modeSwitch.dataset.e2eeToggle = 'true'
269
- modeText.textContent = text('端到端加密(默认开启)', 'End-to-end encryption (on by default)'); modeLabel.append(modeSwitch, modeText)
272
+ modeLabel.className = 'relay-encryption-switch'; modeSwitch.type = 'checkbox'; modeSwitch.checked = false; modeSwitch.dataset.e2eeToggle = 'true'
273
+ modeText.textContent = text('端到端加密(默认关闭)', 'End-to-end encryption (off by default)'); modeLabel.append(modeSwitch, modeText)
270
274
  modeStatus.setAttribute('role', 'status'); modeStatus.className = 'relay-encryption-status'
271
275
  title.textContent = text('手机公网配对', 'Pair this phone for public access')
272
276
  explanation.textContent = text('电脑开通中转后,用这台手机扫描电脑管理页的连接码。已连上电脑局域网时,也可在这里直接配对。', 'After enabling relay on your computer, scan its connection code with this phone. You can also pair here over an existing LAN connection.')
@@ -281,7 +285,21 @@
281
285
  guide.append(title, explanation, progress, scan, autoPair, status)
282
286
  advanced.append(advancedTitle, modeLabel, modeStatus, button, file, logBox)
283
287
  target.append(guide, advanced)
288
+ guide.hidden = true; advanced.hidden = true
284
289
  let selectedOrigin = '', identity = ''
290
+ async function loadPlanPolicy() {
291
+ try {
292
+ const ctx = connection()
293
+ const response = await root.fetch(ctx.url('/relay'), { headers: ctx.headers, cache: 'no-store', signal: root.AbortSignal?.timeout?.(8000) })
294
+ const value = response.ok ? await response.json() : null
295
+ const allowed = value?.e2ee?.allowed !== false && value?.e2ee?.enabled === true
296
+ if (!allowed) { try { bridge.clear?.() } catch {} }
297
+ guide.hidden = !allowed
298
+ advanced.hidden = !allowed
299
+ if (allowed) renderMode()
300
+ } catch { /* keep the encryption UI hidden until the host proves eligibility */ }
301
+ }
302
+ void loadPlanPolicy()
285
303
  function modeContext() {
286
304
  const ctx = connection(), key = JSON.stringify([ctx.url('/relay'),ctx.headers?.authorization||''])
287
305
  if (key !== identity) { identity = key; selectedOrigin = new URL(ctx.url('/relay'),root.location.href).origin }
@@ -289,6 +307,7 @@
289
307
  return ctx
290
308
  }
291
309
  function renderMode() {
310
+ if (guide.hidden) return
292
311
  try {
293
312
  const ctx = modeContext(), pairing = root.DshRelayAutoPair?.progress?.(ctx)
294
313
  const local = root.DshRelayAutoPair?.localUrl(ctx.url('/relay')) && /^Bearer \S+$/.test(ctx.headers?.authorization || '')
@@ -302,11 +321,11 @@
302
321
  autoPair.disabled = !local || pairing?.phase === 'working'
303
322
  scan.disabled = pairing?.phase === 'working'
304
323
  const state = JSON.parse(bridge.info(selectedOrigin))
305
- modeSwitch.checked = state.encrypted !== false
324
+ modeSwitch.checked = !!state.configured && state.encrypted !== false
306
325
  modeSwitch.disabled = !!state.error || !state.configured || typeof bridge.setEncryption !== 'function'
307
326
  modeStatus.dataset.security = !state.configured || state.error ? 'pending' : modeSwitch.checked ? 'encrypted' : 'legacy'
308
327
  modeStatus.textContent = selectedOrigin + ' · ' + (state.error ? text('无法读取安全状态,请重试;不会自动降级。','Security status unavailable. No automatic fallback.') : !state.configured
309
- ? text('默认开启,待本地配对;当前连接尚不能标记为已加密。','On by default; local pairing required. This connection is not yet verified as encrypted.')
328
+ ? text('默认关闭,待本地配对;当前连接尚不能标记为已加密。','Off by default; local pairing required. This connection is not yet verified as encrypted.')
310
329
  : modeSwitch.checked ? text('端到端加密已启用;每次连接仍需通过主机证书校验。','End-to-end encryption enabled; each connection must verify the host certificate.')
311
330
  : text('警告:端到端加密已关闭。仅有 HTTPS,中转方在技术上可读取内容和访问令牌。','Warning: end-to-end encryption is OFF. HTTPS remains, but the relay can technically read content and access tokens.'))
312
331
  } catch { modeSwitch.disabled = true; modeStatus.textContent = text('无法读取安全状态。','Security status unavailable.') }
@@ -13,24 +13,69 @@
13
13
  let current = null, epoch = 0
14
14
  const requests = new Set()
15
15
  const stored = key => { try { return JSON.parse(root.localStorage.getItem(key) || 'null') } catch { return null } }
16
+ const validKey = value => /^[a-f0-9]{64}$/.test(value?.key || '')
17
+ const newKey = () => [...root.crypto.getRandomValues(new Uint8Array(32))].map(n => n.toString(16).padStart(2, '0')).join('')
18
+ const defaultName = () => config.native?.() ? 'Android' : label('浏览器', 'Browser')
19
+ const saveProfile = ctx => root.localStorage.setItem(ctx.profileStorage, JSON.stringify(ctx.profile))
16
20
  const persist = ctx => { if (ctx.valid()) root.localStorage.setItem(ctx.storage, JSON.stringify(ctx.prefs)) }
17
21
  const requireCurrent = ctx => { if (!ctx.valid()) throw Error(label('连接已改变,请重新打开收件箱', 'Connection changed. Reopen the inbox.')) }
18
22
  async function identity() {
19
23
  const connection = config.capture(), generation = epoch
20
24
  if (!connection.token) throw Error(label('请先连接主机', 'Connect to a host first'))
21
25
  if (current?.valid()) return current
22
- const scope = await hash(new TextEncoder().encode(config.url('/api/file-inbox') + '\0' + connection.token))
26
+ const encode = input => new TextEncoder().encode(input)
27
+ const [legacyScope, deviceScope] = await Promise.all([
28
+ hash(encode(config.url('/api/file-inbox') + '\0' + connection.token)),
29
+ hash(encode('file-inbox-device\0' + connection.token)),
30
+ ])
23
31
  if (generation !== epoch || !connection.valid()) throw Error('connection-changed')
24
- const storage = 'dshRemoteFileInboxV1:' + scope
25
- let prefs = stored(storage)
26
- if (!/^[a-f0-9]{64}$/.test(prefs?.key || '')) {
27
- prefs = { key: [...root.crypto.getRandomValues(new Uint8Array(32))].map(n => n.toString(16).padStart(2, '0')).join(''), name: config.native?.() ? 'Android' : label('浏览器', 'Browser'), jobs: {}, receipts: {} }
28
- }
29
- prefs.jobs ||= {}; prefs.receipts ||= {}
30
- const ctx = { connection, storage, prefs, lastRegister: 0, valid: () => generation === epoch && connection.valid() }
31
- persist(ctx); current = ctx
32
+ if (current?.valid()) return current
33
+ const legacyStorage = 'dshRemoteFileInboxV1:' + legacyScope
34
+ const profileStorage = 'dshRemoteFileInboxV2:' + deviceScope
35
+ const previous = stored(legacyStorage), legacy = validKey(previous) ? previous : null
36
+ let profile = stored(profileStorage)
37
+ if (!validKey(profile)) profile = { key: newKey(), name: '' }
38
+ if (!profile.name && typeof legacy?.name === 'string' && legacy.name !== defaultName()) profile.name = legacy.name
39
+ const ctx = { connection, legacyStorage, legacy, profileStorage, profile, lastRegister: 0, valid: () => generation === epoch && connection.valid() }
40
+ saveProfile(ctx); current = ctx
32
41
  return ctx
33
42
  }
43
+ async function register(ctx) {
44
+ if (!ctx.legacyMode) {
45
+ try {
46
+ const device = await api(ctx, { action: 'register-device', name: ctx.profile.name || defaultName(), ...(ctx.legacy ? { legacyKey: ctx.legacy.key } : {}) })
47
+ const storage = ctx.profileStorage + ':' + device.id
48
+ if (ctx.storage !== storage) {
49
+ ctx.storage = storage
50
+ ctx.prefs = stored(storage) || { jobs: {}, receipts: {}, imported: {} }
51
+ }
52
+ if (ctx.legacy && !ctx.prefs.imported[ctx.legacyStorage]) {
53
+ ctx.prefs.jobs = { ...ctx.legacy.jobs, ...ctx.prefs.jobs }
54
+ ctx.prefs.receipts = { ...ctx.legacy.receipts, ...ctx.prefs.receipts }
55
+ ctx.prefs.imported[ctx.legacyStorage] = true
56
+ }
57
+ ctx.device = device; persist(ctx)
58
+ return
59
+ } catch (error) {
60
+ if (error.status !== 400 || error.code !== 'invalid-action') throw error
61
+ ctx.legacyMode = true
62
+ }
63
+ }
64
+ if (ctx.storage !== ctx.legacyStorage) {
65
+ ctx.storage = ctx.legacyStorage
66
+ ctx.prefs = ctx.legacy || { key: newKey(), name: defaultName(), jobs: {}, receipts: {} }
67
+ ctx.prefs.jobs ||= {}; ctx.prefs.receipts ||= {}; persist(ctx)
68
+ ctx.legacy = ctx.prefs
69
+ }
70
+ ctx.device = await api(ctx, { action: 'register', name: ctx.prefs.name })
71
+ }
72
+ async function registered(ctx) {
73
+ if (!ctx.device || Date.now() - ctx.lastRegister > 20000) {
74
+ if (!ctx.registration) ctx.registration = register(ctx).then(() => { ctx.lastRegister = Date.now() }).finally(() => { ctx.registration = null })
75
+ await ctx.registration
76
+ }
77
+ requireCurrent(ctx)
78
+ }
34
79
  async function read(ctx, url, options, timeoutMs, decode) {
35
80
  requireCurrent(ctx)
36
81
  const controller = new AbortController(), timeout = AbortSignal.timeout(timeoutMs), abort = () => controller.abort()
@@ -44,9 +89,10 @@
44
89
  } finally { requests.delete(controller); timeout.removeEventListener('abort', abort) }
45
90
  }
46
91
  async function api(ctx, body) {
47
- const { response, data } = await read(ctx, config.url('/api/file-inbox'), { method: body ? 'POST' : 'GET', headers: { ...config.headers(ctx.connection), 'content-type': 'application/json', 'x-dsh-remote-inbox-key': ctx.prefs.key }, ...(body ? { body: JSON.stringify(body) } : {}) }, 12000, async response => ({ response, data: await response.json() }))
92
+ const key = ctx.legacyMode ? ctx.prefs.key : ctx.profile.key
93
+ const { response, data } = await read(ctx, config.url('/api/file-inbox'), { method: body ? 'POST' : 'GET', headers: { ...config.headers(ctx.connection), 'content-type': 'application/json', 'x-dsh-remote-inbox-key': key }, ...(body ? { body: JSON.stringify(body) } : {}) }, 12000, async response => ({ response, data: await response.json() }))
48
94
  requireCurrent(ctx)
49
- if (!response.ok) throw Error(response.status === 404 ? label('主机尚不支持文件收件箱,请升级 Remote 插件', 'Update the host Remote plugin to use the file inbox') : String(data.error || 'HTTP ' + response.status))
95
+ if (!response.ok) throw Object.assign(Error(response.status === 404 ? label('主机尚不支持文件收件箱,请升级 Remote 插件', 'Update the host Remote plugin to use the file inbox') : String(data.error || 'HTTP ' + response.status)), { status: response.status, code: data.error })
50
96
  return data
51
97
  }
52
98
  async function acknowledge(ctx, id, phase) {
@@ -57,7 +103,7 @@
57
103
  }
58
104
  async function sync() {
59
105
  const ctx = await identity()
60
- if (Date.now() - ctx.lastRegister > 20000) { ctx.device = await api(ctx, { action: 'register', name: ctx.prefs.name }); ctx.lastRegister = Date.now() }
106
+ await registered(ctx)
61
107
  const before = await api(ctx)
62
108
  for (const id of Object.keys(ctx.prefs.jobs)) {
63
109
  const row = before.transfers.find(row => row.id === id)
@@ -78,15 +124,24 @@
78
124
  }
79
125
  for (const [id, phase] of Object.entries(ctx.prefs.receipts)) { try { await acknowledge(ctx, id, phase) } catch {} }
80
126
  const value = await api(ctx)
81
- return { ...value, device: ctx.device, name: ctx.prefs.name, jobs: { ...ctx.prefs.jobs } }
127
+ return { ...value, device: ctx.device, name: ctx.legacyMode ? ctx.prefs.name : ctx.profile.name || defaultName(), jobs: { ...ctx.prefs.jobs } }
82
128
  }
83
129
  return {
84
130
  sync,
85
131
  reset() { epoch++; current = null; for (const request of requests) request.abort(); requests.clear() },
86
- async rename(name) { const ctx = await identity(); requireCurrent(ctx); ctx.prefs.name = String(name).trim().slice(0, 60) || 'Remote'; persist(ctx); ctx.lastRegister = 0; return sync() },
87
- async reject(row) { const ctx = await identity(); return api(ctx, { action: 'reject', id: row.id }) },
132
+ async rename(name) {
133
+ const ctx = await identity(); await registered(ctx)
134
+ const value = String(name).trim().slice(0, 60) || 'Remote'
135
+ if (ctx.legacyMode) { ctx.prefs.name = value; persist(ctx) }
136
+ ctx.profile.name = value; saveProfile(ctx)
137
+ ctx.lastRegister = 0
138
+ return sync()
139
+ },
140
+ async reject(row) { const ctx = await identity(); await registered(ctx); return api(ctx, { action: 'reject', id: row.id }) },
88
141
  async receive(row) {
89
142
  const ctx = await identity()
143
+ await registered(ctx)
144
+ if (ctx.prefs.jobs[row.id]) return { native: true }
90
145
  const accepted = await api(ctx, { action: 'accept', id: row.id })
91
146
  requireCurrent(ctx)
92
147
  const url = new URL(config.url('/fs/inbox-file'), root.location.href)
@@ -94,9 +149,13 @@
94
149
  const native = config.native?.()
95
150
  try {
96
151
  if (native?.downloadToDownloads && native?.getFileDownloadStatus) {
97
- const job = native.downloadToDownloads(url.href, accepted.fileName, ctx.connection.token)
98
- if (!/^\d+$/.test(String(job))) throw Error(label('系统下载未启动', 'System download did not start'))
99
- ctx.prefs.jobs[row.id] = String(job); persist(ctx)
152
+ const job = String(native.downloadToDownloads(url.href, accepted.fileName, ctx.connection.token))
153
+ // The Android bridge uses numeric IDs for DownloadManager and UUIDs for encrypted downloads.
154
+ if (!/^(?:\d+|e2ee-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12})$/.test(job)) {
155
+ throw Error(label('系统下载未启动', 'System download did not start'))
156
+ }
157
+ ctx.prefs.jobs[row.id] = job
158
+ try { persist(ctx) } catch {} // Continue tracking an already-started native download in memory.
100
159
  return { native: true }
101
160
  }
102
161
  const bytes = await read(ctx, url.href, { headers: config.headers(ctx.connection) }, 20 * 60 * 1000, async response => {
package/public/genui.css CHANGED
@@ -6,3 +6,13 @@
6
6
  .genui .genui-spark{display:block;width:120px;height:30px;max-width:100%;color:#2563eb}.genui-ring{display:inline-flex;gap:8px;align-items:center}.genui-ring svg{width:40px;height:40px;flex:none;color:#2563eb}
7
7
  .genui-positive{color:#059669}.genui-negative{color:#dc2626}.genui-table tfoot{font-weight:600}.genui-table th[aria-sort=ascending] button::after{content:' ↑'}.genui-table th[aria-sort=descending] button::after{content:' ↓'}
8
8
  .genui-tree{list-style:none;padding-left:16px;border-left:1px solid #8884}.genui-diff{margin:10px 0}.genui-diff section{min-width:0}.genui-diff pre{white-space:pre;overflow:auto}.genui-diff .genui-grid{gap:12px;margin-top:8px}@media(max-width:520px){.genui-diff .genui-grid{grid-template-columns:1fr}}
9
+ .genui .genui-table-wrap>:is(thead,tbody,tfoot)>tr>:is(th,td){min-width:6rem;white-space:pre-wrap;overflow-wrap:anywhere;vertical-align:top}
10
+ .genui-table-wrap>thead>tr>th>button{white-space:inherit}
11
+ .genui-compare-panels{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}
12
+ .genui-compare-stack{grid-template-columns:minmax(0,1fr)}
13
+ .genui-image{display:grid;align-content:start;gap:4px;min-width:0;margin:0}
14
+ .genui-image strong,.genui-image figcaption{overflow-wrap:anywhere}
15
+ .genui-image .chat-image{width:100%;min-width:0}
16
+ .genui-image .chat-image img{display:block;width:100%;height:auto;max-height:var(--genui-image-height,260px);object-fit:contain}
17
+ .genui-image-unavailable{display:block;padding:8px;font-size:12px}
18
+ @media(max-width:520px){.genui-compare-panels{grid-template-columns:minmax(0,1fr)}}
package/public/genui.js CHANGED
@@ -106,10 +106,16 @@
106
106
  return '<figure class="genui-chart">' + (node.title ? '<figcaption>' + esc(node.title) + '</figcaption>' : '') + svg + '<details><summary>数据 / Data</summary>' + table + '</details></figure>'
107
107
  }
108
108
 
109
- function render(spec) {
109
+ function render(spec, { image } = {}) {
110
110
  if (!spec || typeof spec !== 'object') throw Error('Invalid spec')
111
111
  let count = 0
112
112
  function nodes(items, depth) { return array(items).map(n => node(n, depth)).join('') }
113
+ function imagePanel(panel, label = '') {
114
+ const title = panel.alt || label || '图片 / Image'
115
+ const preview = image?.(panel.src, title) || '<span class="genui-image-unavailable">图片无法预览 / Image unavailable</span>'
116
+ return '<figure class="genui-image">' + (label ? '<strong>' + esc(label) + '</strong>' : '') + preview +
117
+ (panel.caption ? '<figcaption>' + esc(panel.caption) + '</figcaption>' : '') + '</figure>'
118
+ }
113
119
  function fileTree(items, depth) {
114
120
  if (depth > 12 || (count += array(items).length) > 240) throw Error('Component limit')
115
121
  return '<ul class="genui-tree">' + array(items).map(v => !v || typeof v !== 'object' ? '<li>' + esc(v) + '</li>' : '<li>' + (v.type === 'dir' || Array.isArray(v.children) ? '<details open><summary>' + esc(v.name) + '</summary>' + fileTree(v.children, depth + 1) + '</details>' : '<span>' + esc(v.name) + '</span>') + '</li>').join('') + '</ul>'
@@ -132,7 +138,7 @@
132
138
  const values = rows.map(r => numeric(r[j]))
133
139
  return '<td>' + (j === 0 ? '合计 / Total' : values.length && values.every(Number.isFinite) && !['index', 'spark', 'ring', 'bar'].includes(types[j]) ? esc(Number(values.reduce((a, b) => a + b, 0).toPrecision(12))) : '') + '</td>'
134
140
  }).join('') + '</tr></tfoot>'
135
- return '<div class="genui-scroll"><table class="genui-table"><thead><tr>' + columns.map((v, j) => '<th aria-sort="none"><button type="button" data-genui-sort="' + j + '">' + esc(v) + ' ↕</button></th>').join('') + '</tr></thead>' + rows.map((r, i) => '<tbody data-genui-order="' + i + '"><tr>' + columns.map((_, j) => '<td data-genui-value="' + esc(r[j]) + '">' + cell(r[j], types[j], i) + '</td>').join('') + '</tr>' + (array(n.details?.[i]).length ? '<tr><td colspan="' + columns.length + '"><details><summary>详情 / Details</summary>' + nodes(n.details[i], depth + 1) + '</details></td></tr>' : '') + '</tbody>').join('') + foot + '</table></div>' + (n.export ? '<details><summary>导出数据 / CSV</summary>' + raw([columns, ...rows].map(r => r.map(v => '"' + String(v ?? '').replace(/"/g, '""') + '"').join(',')).join('\n')) + '</details>' : '')
141
+ return '<div class="genui-scroll"><table class="genui-table' + (n.wrap === true ? ' genui-table-wrap' : '') + '"><thead><tr>' + columns.map((v, j) => '<th aria-sort="none"><button type="button" data-genui-sort="' + j + '">' + esc(v) + ' ↕</button></th>').join('') + '</tr></thead>' + rows.map((r, i) => '<tbody data-genui-order="' + i + '"><tr>' + columns.map((_, j) => '<td data-genui-value="' + esc(r[j]) + '">' + cell(r[j], types[j], i) + '</td>').join('') + '</tr>' + (array(n.details?.[i]).length ? '<tr><td colspan="' + columns.length + '"><details><summary>详情 / Details</summary>' + nodes(n.details[i], depth + 1) + '</details></td></tr>' : '') + '</tbody>').join('') + foot + '</table></div>' + (n.export ? '<details><summary>导出数据 / CSV</summary>' + raw([columns, ...rows].map(r => r.map(v => '"' + String(v ?? '').replace(/"/g, '""') + '"').join(',')).join('\n')) + '</details>' : '')
136
142
  }
137
143
  function node(n, depth) {
138
144
  if (++count > 240 || depth > 12) throw Error('Component limit')
@@ -141,8 +147,10 @@
141
147
  n = { ...n }
142
148
  if (n.type === 'text' && n.content === undefined) n.content = n.text
143
149
  if (n.type === 'table') { n.columns ??= n.headers; n.rows ??= n.data }
144
- if (n.type === 'card') { n.title ??= n.label; n.items ??= n.content }
150
+ if (n.type === 'card') { n.title ??= n.label; n.items ??= n.content ?? n.body }
151
+ if (n.type === 'grid') n.cols ??= n.columns
145
152
  const type = n.type
153
+ if (Object.hasOwn(n, 'when')) return unsupported(n, '条件显示 / conditional visibility')
146
154
  // Reject data-transforming options rather than silently displaying different data.
147
155
  if (n.filter || n.sortField) return unsupported(n, type + ' filter/sort')
148
156
  if ((type === 'table' && (array(n.rows).length > 200 || array(n.columns).length > 30)) ||
@@ -161,6 +169,16 @@
161
169
  if (type === 'progress' && n.variant === 'ring') return '<div>' + esc(n.label) + ring(n.value, n.valueLabel || n.value + '%') + (number(n.target) ? '<small>目标 / Target: ' + esc(n.target) + '%</small>' : '') + '</div>'
162
170
  if (type === 'progress') return '<div>' + esc(n.label) + '<progress max="100" value="' + Math.max(0, Math.min(100, Number(n.value) || 0)) + '"></progress><small>' + esc(n.valueLabel || String(n.value || 0) + '%') + '</small>' + (number(n.target) ? '<small> · 目标 / Target: ' + esc(n.target) + '%</small>' : '') + '</div>'
163
171
  if (type === 'callout') return '<aside class="genui-callout"><strong>' + esc(n.title) + '</strong><p>' + esc(n.content) + '</p></aside>'
172
+ if (type === 'image') return typeof n.src === 'string' ? imagePanel(n, n.alt) : unsupported(n)
173
+ if (type === 'compare') {
174
+ if (typeof n.before?.src !== 'string' || typeof n.after?.src !== 'string') return unsupported(n)
175
+ const height = number(n.height) ? Math.round(Math.min(640, Math.max(120, n.height))) : 260
176
+ return '<section class="genui-compare" style="--genui-image-height:' + height + 'px">' +
177
+ (n.title ? '<h4>' + esc(n.title) + '</h4>' : '') +
178
+ '<div class="genui-compare-panels' + (n.mode === 'stack' ? ' genui-compare-stack' : '') + '">' +
179
+ imagePanel(n.before, n.before.label || '改动前 / Before') +
180
+ imagePanel(n.after, n.after.label || '改动后 / After') + '</div></section>'
181
+ }
164
182
  if (type === 'code' || type === 'json') return raw(type === 'code' ? n.code : n.value)
165
183
  if (type === 'list' || type === 'timeline' || type === 'steps') return '<ul>' + array(n.items || n.steps).slice(0, 100).map(v => '<li>' + (v && typeof v === 'object' ? (v.type ? node(v, depth + 1) : '<strong>' + esc(v.title) + '</strong> ' + esc(v.desc) + ' ' + esc(v.time)) : esc(v)) + '</li>').join('') + '</ul>'
166
184
  if (type === 'keyvalue') return '<dl>' + array(n.pairs).slice(0, 100).map(v => '<dt>' + esc(v?.key) + '</dt><dd>' + esc(v?.value) + '</dd>').join('') + '</dl>'
@@ -183,7 +201,7 @@
183
201
  }
184
202
  const body = Array.isArray(spec) ? nodes(spec, 0) : spec.type ? node(spec, 0) : nodes(spec.items, 0)
185
203
  if (!body) throw Error('No components')
186
- return '<section class="genui"><div class="genui-caption">DSH UI · 只读预览 / Read-only</div>' + (spec.title ? '<h3>' + esc(spec.title) + '</h3>' : '') + body + details(spec) + '</section>'
204
+ return '<section class="genui"><div class="genui-caption">DSH UI · 只读预览 / Read-only</div>' + (spec.title && !Object.hasOwn(spec, 'when') ? '<h3>' + esc(spec.title) + '</h3>' : '') + body + details(spec) + '</section>'
187
205
  }
188
206
 
189
207
  function html(source) {
package/public/history.js CHANGED
@@ -33,7 +33,11 @@
33
33
  this.live=document.createElement('div'); this.live.className='history-live'
34
34
  box.addEventListener('toggle',event=>{
35
35
  const detail=event.target
36
- if(detail?.dataset?.activityKey)this.rememberDisclosure(detail)
36
+ if(detail?.dataset?.activityKey){
37
+ this.rememberDisclosure(detail)
38
+ // The document capture listener has already hydrated the opened body.
39
+ if(detail.open)this.restoreDisclosures(detail)
40
+ }
37
41
  if(detail?.dataset?.activitySummary!=null)this.updateActivityRows()
38
42
  },true)
39
43
  const intent=()=>{this.intentUntil=Date.now()+1200}
@@ -51,8 +55,21 @@
51
55
  },{passive:true})
52
56
  }
53
57
  anchor() {
54
- const top=this.box.getBoundingClientRect().top
55
- for(const node of this.box.querySelectorAll('.history-entry'))if(!node.hidden&&node.getBoundingClientRect().bottom>=top+1)return {seq:Number(node.dataset.historySeq),top:node.getBoundingClientRect().top}
58
+ const box=this.box, bounds=box.getBoundingClientRect()
59
+ for(const node of box.querySelectorAll('.history-entry')){
60
+ if(node.hidden)continue
61
+ const row=node.getBoundingClientRect()
62
+ if(row.bottom<bounds.top+1)continue
63
+ const anchor={seq:Number(node.dataset.historySeq),top:row.top,scrollTop:box.scrollTop}
64
+ // Within a tall group, use the visible tool/reasoning heading as the anchor.
65
+ for(const summary of node.querySelectorAll('details[data-activity-key] > summary')){
66
+ const rect=summary.getBoundingClientRect()
67
+ if(rect.bottom<=bounds.top||rect.top>=bounds.bottom||rect.height===0)continue
68
+ anchor.activity={key:summary.parentNode.dataset.activityKey,top:rect.top}
69
+ break
70
+ }
71
+ return anchor
72
+ }
56
73
  return null
57
74
  }
58
75
  get unread() {return Math.max(0,this.entries.length-this.end)}
@@ -70,10 +87,23 @@
70
87
  if(this.reading&&!reset)live=this.liveHtml||''
71
88
  if(!reset&&!this.renderErrors&&entries.length===this.entries.length&&entries.every((entry,i)=>entry===this.entries[i])&&hasMore===this.hasMore&&loading===this.loading&&(this.end===entries.length?live:'')===this.liveHtml){this.more.disabled=loading;this.more.textContent=loading?this.options.loadingLabel():this.options.olderLabel();this.domChanged=false;this.options.changed?.(this);return}
72
89
  const oldWidth=this.end-this.start
90
+ // Real position wins over the intent flag: never snap a reader back to the tail just
91
+ // because a layout scroll cleared `reading` while new content arrived.
92
+ const wasAtBottom=this.atBottom
73
93
  const anchor=this.anchor(), oldStart=this.entries[this.start]?.seq, oldEnd=this.entries[Math.max(this.start,this.end-1)]?.seq
74
94
  this.entries=entries.slice(); this.hasMore=hasMore; this.loading=loading
75
95
  if(reset || !this.end){this.end=entries.length;this.start=Math.max(0,this.end-WINDOW_SIZE);this.reading=false}
76
- else if(!this.reading && this.end>=this.previousLength){this.end=entries.length;this.start=Math.max(0,this.end-WINDOW_SIZE)}
96
+ else if(!this.reading && this.end>=this.previousLength){
97
+ this.end=entries.length;this.start=Math.max(0,this.end-WINDOW_SIZE)
98
+ // Appending to a full window must not evict its visible anchor.
99
+ if(!wasAtBottom&&anchor){
100
+ const position=entries.findIndex(entry=>entry.seq===anchor.seq)
101
+ if(position>=0&&position<this.start){
102
+ this.start=Math.max(0,entries.findIndex(entry=>entry.seq===oldStart))
103
+ this.reading=true
104
+ }
105
+ }
106
+ }
77
107
  else {
78
108
  let start=entries.findIndex(e=>e.seq===oldStart),end=entries.findIndex(e=>e.seq===oldEnd)
79
109
  if(start<0)start=anchor?entries.findIndex(e=>e.seq===anchor.seq):0
@@ -83,7 +113,7 @@
83
113
  this.emptyLabel=emptyLabel
84
114
  this.more.textContent=loading?this.options.loadingLabel():this.options.olderLabel();this.more.disabled=loading;this.more.hidden=this.start===0&&!hasMore
85
115
  this.liveHtml=this.reading&&!reset ? this.liveHtml||'' : this.end===entries.length?live:''
86
- this.render(anchor,reset || (!this.reading && this.end===entries.length))
116
+ this.render(anchor,reset || (!this.reading && wasAtBottom && this.end===entries.length))
87
117
  }
88
118
  rememberDisclosure(detail) {
89
119
  const key=detail.dataset.activityKey;if(!key)return
@@ -91,10 +121,25 @@
91
121
  if(this.disclosures.size>512)this.disclosures.delete(this.disclosures.keys().next().value)
92
122
  }
93
123
  captureDisclosures(node) {for(const detail of node.querySelectorAll('details[data-activity-key]'))this.rememberDisclosure(detail)}
94
- restoreDisclosures(node) {for(const detail of node.querySelectorAll('details[data-activity-key]'))if(this.disclosures.has(detail.dataset.activityKey))detail.open=this.disclosures.get(detail.dataset.activityKey)}
124
+ restoreDisclosures(node) {
125
+ for(const detail of node.querySelectorAll('details[data-activity-key]')){
126
+ const key=detail.dataset.activityKey
127
+ if(this.disclosures.has(key))detail.open=this.disclosures.get(key)
128
+ if(detail.open){
129
+ // Hydrating a group creates disclosures absent from the original NodeList.
130
+ for(const body of globalThis.DshActivity?.hydrate?.(detail)||[])this.restoreDisclosures(body)
131
+ }
132
+ }
133
+ }
95
134
  updateActivityRows() {
96
135
  const rendered = new Map([...this.box.querySelectorAll('[data-activity-summary]')].map(el=>[el.dataset.activitySummary,el]))
97
- for(const detail of this.box.querySelectorAll('[data-activity-turn]')){
136
+ const groups=this.box.querySelectorAll('[data-activity-turn]')
137
+ for(const detail of groups){
138
+ const controller=rendered.get(detail.dataset.activityTurn)
139
+ // Completing a turn can add its summary around a group the user is reading.
140
+ if(detail.open&&controller&&!this.disclosures.has(controller.dataset.activityKey))controller.open=true
141
+ }
142
+ for(const detail of groups){
98
143
  const id=detail.dataset.activityTurn, controller=rendered.get(id), row=detail.parentNode
99
144
  // If the summary has scrolled out of the rendered page, keep this group reachable.
100
145
  row.hidden=!!controller&&!controller.open
@@ -110,10 +155,12 @@
110
155
  this.renderErrors=0
111
156
  for(const entry of slice) {
112
157
  // Hidden events render an empty string; keeping their node would leave dead gaps.
113
- let html,key,failed=false
114
- try{html=this.options.html(entry);key=signature(entry)}catch(error){failed=true;this.renderErrors++;key='render-error';globalThis.DshDiagnostics?.record('history.row',{phase:'failed',...globalThis.DshDiagnostics.errorFacts(error),category:'render'})}
158
+ let key=null,cached=this.nodes.get(entry.seq),html,failed=false
159
+ try{key=signature(entry)}catch{key=null}
160
+ // Unchanged rows keep their DOM and skip markdown/JSON rendering entirely.
161
+ if(key!=null&&cached?.key===key){desired.push(cached.node);continue}
162
+ try{html=this.options.html(entry);if(key==null)key=signature(entry)}catch(error){failed=true;this.renderErrors++;key='render-error';globalThis.DshDiagnostics?.record('history.row',{phase:'failed',...globalThis.DshDiagnostics.errorFacts(error),category:'render'})}
115
163
  if(!html&&!failed){if(this.nodes.delete(entry.seq))changed=true;continue}
116
- let cached=this.nodes.get(entry.seq)
117
164
  if(!cached || cached.key!==key){changed=true;const node=document.createElement('div');node.className='history-entry';node.dataset.historySeq=String(entry.seq);if(failed)node.textContent=this.options.errorLabel?.()||'This message could not be displayed. Retry loading history.';else{node.innerHTML=html;this.restoreDisclosures(node)}cached={key,node};this.nodes.set(entry.seq,cached)}
118
165
  desired.push(cached.node)
119
166
  }
@@ -132,7 +179,20 @@
132
179
  if(this.live.innerHTML!==this.liveHtml){this.live.innerHTML=this.liveHtml;this.restoreDisclosures(this.live)}
133
180
  if(this.live.parentNode!==box)box.append(this.live)
134
181
  if(bottom)box.scrollTop=box.scrollHeight
135
- else if(anchor){const current=this.nodes.get(anchor.seq)?.node;if(current?.parentNode===box)box.scrollTop+=current.getBoundingClientRect().top-anchor.top}
182
+ else if(anchor){
183
+ const current=this.nodes.get(anchor.seq)?.node
184
+ let summary
185
+ if(anchor.activity){
186
+ for(const heading of (current||box).querySelectorAll('details[data-activity-key] > summary')){
187
+ if(heading.parentNode.dataset.activityKey!==anchor.activity.key||!heading.getClientRects().length)continue
188
+ summary=heading
189
+ break
190
+ }
191
+ }
192
+ if(summary)box.scrollTop+=summary.getBoundingClientRect().top-anchor.activity.top
193
+ else if(current?.parentNode===box&&!current.hidden)box.scrollTop+=current.getBoundingClientRect().top-anchor.top
194
+ else box.scrollTop=anchor.scrollTop
195
+ }
136
196
  const active=new Set(slice.map(entry=>entry.seq));for(const seq of this.nodes.keys())if(!active.has(seq))this.nodes.delete(seq)
137
197
  cancelAnimationFrame(this.releaseFrame);this.releaseFrame=requestAnimationFrame(()=>{this.suppress=false})
138
198
  this.lastScrollTop=box.scrollTop
@@ -196,6 +256,41 @@
196
256
  try{return Promise.resolve(JSON.parse(raw)[id]||null)}catch{return Promise.resolve(null)}
197
257
  }
198
258
  const cacheKey=(scope,id)=>scope+':session:'+encodeURIComponent(id)
259
+ const TRACE_BLOCKS = new Set(['thinking', 'reasoning', 'tool-call', 'tool-result'])
260
+ function compactCacheEvents(events) {
261
+ let starts = 0, prompts = 0, turnStart = -1, promptStart = -1
262
+ for (let i = events.length - 1; i >= 0; i--) {
263
+ const event = events[i]?.event
264
+ if (event?.type === 'turn/start' && ++starts === 2) { turnStart = i; break }
265
+ const source = event?.data?.source ?? event?.data?.message?.source
266
+ if (event?.type === 'user/message' && (!source || source.kind === 'user') && ++prompts === 2) promptStart = i
267
+ }
268
+ const keepTracesFrom = turnStart >= 0 ? turnStart : Math.max(0, promptStart)
269
+ const kept = []
270
+ for (let i = 0; i < events.length; i++) {
271
+ const entry = events[i], event = entry?.event
272
+ if (i >= keepTracesFrom || !event) { kept.push(entry); continue }
273
+ const { type, data } = event
274
+ if (typeof type === 'string' && type.startsWith('tool/')) continue
275
+ if (type === 'assistant/attempt' && data?.stream) {
276
+ kept.push({ ...entry, event: { ...event, data: { ...data, stream: [] } } })
277
+ } else if (type === 'assistant/message') {
278
+ const message = data?.message, content = message?.content ?? data?.content
279
+ if (!Array.isArray(content) || !content.some(block => TRACE_BLOCKS.has(block?.type))) {
280
+ kept.push(entry)
281
+ } else {
282
+ const blocks = content.filter(block => !TRACE_BLOCKS.has(block?.type))
283
+ if (blocks.length) kept.push({ ...entry, event: { ...event, data: message?.content
284
+ ? { ...data, message: { ...message, content: blocks } } : { ...data, content: blocks } } })
285
+ }
286
+ } else kept.push(entry)
287
+ }
288
+ return kept
289
+ }
290
+ function compactCachedValue(value) {
291
+ if (!Array.isArray(value?.events) || value.traceTurns === 2) return value
292
+ return { ...value, events: compactCacheEvents(value.events), traceTurns: 2 }
293
+ }
199
294
  async function cacheLoad(scope,id,legacy) {
200
295
  const key=cacheKey(scope,id),db=await openDatabase()
201
296
  if(db){const value=await new Promise(resolve=>{
@@ -203,16 +298,18 @@
203
298
  const done=value=>{if(settled)return;settled=true;clearTimeout(timer);resolve(value)}
204
299
  const timer=setTimeout(()=>{globalThis.DshDiagnostics?.storageFailure(scope,{name:'TimeoutError'},'indexeddb');done(null);try{tx?.abort()}catch{}},1500)
205
300
  try{tx=db.transaction('history');const request=tx.objectStore('history').get(key);request.onsuccess=()=>done(request.result);request.onerror=tx.onabort=tx.onerror=()=>done(null)}catch{done(null)}
206
- });if(value)return value}
207
- try{const value=JSON.parse(localStorage.getItem(key)||'null');if(value)return value}catch{}
301
+ });if(value)return compactCachedValue(value)}
302
+ try{const value=JSON.parse(localStorage.getItem(key)||'null');if(value)return compactCachedValue(value)}catch{}
208
303
  // One-time compatibility with the old per-connection JSON cache.
209
- try{const value=await legacy?.(id);if(value){void cacheSave(scope,id,value);return value}return null}catch{return null}
304
+ try{const value=await legacy?.(id);if(value){void cacheSave(scope,id,value);return compactCachedValue(value)}return null}catch{return null}
210
305
  }
211
- async function cacheSave(scope,id,value) {
306
+ async function cacheSave(scope,id,value,maxEvents=Infinity) {
212
307
  const epoch=cacheEpoch,key=cacheKey(scope,id),kept=[];let size=0
213
- for(let i=(value.events||[]).length-1;i>=0;i--){const entry=value.events[i],length=signature(entry).length;if(size+length>750000)break;kept.unshift(entry);size+=length}
308
+ const events=compactCacheEvents(value.events||[])
309
+ for(let i=events.length-1;i>=0&&kept.length<maxEvents;i--){const entry=events[i],length=signature(entry).length;if(size+length>750000)break;kept.push(entry);size+=length}
214
310
  if(!kept.length)return false
215
- const data={...value,events:kept,minSeq:kept[0].seq,hasMore:value.hasMore||kept.length<(value.events||[]).length,key,scope,id,updatedAt:Date.now()},db=await openDatabase()
311
+ kept.reverse()
312
+ const data={...value,events:kept,traceTurns:2,minSeq:kept.length<events.length?kept[0].seq:value.minSeq??kept[0].seq,hasMore:value.hasMore||kept.length<events.length,key,scope,id,updatedAt:Date.now()},db=await openDatabase()
216
313
  if(epoch!==cacheEpoch)return false
217
314
  if(db)try{const saved=await new Promise(resolve=>{
218
315
  const tx=db.transaction('history','readwrite'),store=tx.objectStore('history');store.put(data)