dsh-remote-plugin 0.8.8 → 0.9.0

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 (60) 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 +527 -78
  5. package/index.mjs +1 -0
  6. package/package.json +8 -3
  7. package/public/activity.js +53 -4
  8. package/public/admin.html +34 -33
  9. package/public/admin.js +10 -2
  10. package/public/app.js +1204 -174
  11. package/public/bc-integration.css +81 -0
  12. package/public/build.json +2 -2
  13. package/public/composer-tools.css +184 -0
  14. package/public/composer-tools.js +888 -0
  15. package/public/desktop/desktop.html +92 -73
  16. package/public/desktop/desktop.js +631 -77
  17. package/public/file-inbox.js +77 -18
  18. package/public/genui.css +10 -0
  19. package/public/genui.js +22 -4
  20. package/public/host-queue.js +232 -0
  21. package/public/host-schedule.js +301 -0
  22. package/public/host-state.css +19 -0
  23. package/public/index.html +330 -140
  24. package/public/md.js +21 -1
  25. package/public/network.js +33 -1
  26. package/public/onboarding.js +3 -3
  27. package/public/operations.js +4 -3
  28. package/public/plan-review.css +297 -0
  29. package/public/plan-review.js +621 -0
  30. package/public/plugin.html +29 -28
  31. package/public/relay-autopair.js +25 -10
  32. package/public/relay-settings.css +11 -0
  33. package/public/relay-settings.js +350 -28
  34. package/public/session-management.css +61 -0
  35. package/public/session-management.js +742 -0
  36. package/public/session-search.css +137 -0
  37. package/public/session-search.js +977 -0
  38. package/public/skins/blue-fish/preview.html +3 -3
  39. package/public/skins/bocchi/preview.html +5 -5
  40. package/public/skins/kita/preview.html +6 -6
  41. package/public/skins/miku/SOURCES.json +10 -0
  42. package/public/skins/miku/chibi.png +0 -0
  43. package/public/skins/miku/preview.html +33 -0
  44. package/public/skins/miku/skin.css +82 -0
  45. package/public/skins/nijika/preview.html +6 -6
  46. package/public/skins/penguin/preview.html +3 -3
  47. package/public/skins/ryo/preview.html +6 -6
  48. package/public/slash-suggestions.js +15 -3
  49. package/public/sponsor-entry.js +11 -3
  50. package/public/styles.css +141 -21
  51. package/public/subagents.css +5 -0
  52. package/public/subagents.js +52 -0
  53. package/public/theme-vars.css +65 -1
  54. package/public/theme.js +4 -3
  55. package/public/turn-diff.css +323 -0
  56. package/public/turn-diff.js +778 -0
  57. package/public/update.json +8 -8
  58. package/public/version.json +1 -1
  59. package/public/workflow.css +305 -34
  60. package/public/workflow.js +141 -41
@@ -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) {
@@ -0,0 +1,232 @@
1
+ ;(function (root) {
2
+ 'use strict'
3
+ const tr = (zh, en) => root.I18N?.lang === 'en' ? en : zh
4
+ const text = value => String(value ?? '').replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char])
5
+ const contentOf = item => item?.message?.content ?? item?.content
6
+ const editable = item => Array.isArray(contentOf(item)) && contentOf(item).length > 0
7
+ && contentOf(item).every(part => part?.type === 'text' && typeof part.text === 'string')
8
+ const bodyOf = item => (Array.isArray(contentOf(item)) ? contentOf(item) : []).filter(part => part?.type === 'text').map(part => part.text).join('\n')
9
+ const actionable = item => ['queued', 'steering'].includes(item?.placement)
10
+ const denied = error => [error?.code, error?.message].some(value => typeof value === 'string' && /host-state\/access-denied|HTTP 403|permission.denied|forbidden/i.test(value))
11
+ const knownRejection = error => !!(error?.rpcRejected || denied(error) || error?.message === 'AUTH' || /^(?:session\/|schedule[\/_])/.test(error?.code || '')) && !error?.operationPending
12
+
13
+ async function readAccess(connection, url) {
14
+ if (!connection.valid() || !connection.token) return false
15
+ const response = await root.fetch(url('/api/host-state-access'), {
16
+ headers: { authorization: 'Bearer ' + connection.token }, cache: 'no-store', signal: AbortSignal.timeout(8000),
17
+ })
18
+ if (response.status === 403) return false
19
+ if (!response.ok) throw new Error('HTTP ' + response.status)
20
+ return (await response.json()).writable === true
21
+ }
22
+
23
+ function explain(error) {
24
+ if (denied(error)) return tr('此设备无权修改主机状态。', 'This device cannot modify Host state.')
25
+ switch (error?.code) {
26
+ case 'session/queue-item-not-found': return tr('已不在队列中', 'No longer pending')
27
+ case 'session/steer-unavailable': return tr('当前轮次已不接受插队', 'The current turn no longer accepts steering')
28
+ case 'session/queue-conflict': return tr('内容已变化,请重新打开编辑', 'Item changed; reopen the editor')
29
+ case 'session/queue-edit-attachments': return tr('主机编辑接口无法保留附件', 'The Host cannot preserve attachments when editing')
30
+ case 'session/queue-state-unsupported': return tr('该主机无法提供可核对的队列快照', 'This Host does not provide a verifiable queue snapshot')
31
+ default: return error?.message || tr('主机未确认', 'Not confirmed by the Host')
32
+ }
33
+ }
34
+
35
+ async function writeItems({ rpc, sessionId, wanted, snapshot, action, valid }) {
36
+ const targets = new Map(wanted.map(item => [item.id, item]))
37
+ const current = new Map(snapshot.items.map(item => [item.id, item]))
38
+ const ordered = [...snapshot.items.filter(item => targets.has(item.id)), ...wanted.filter(item => !current.has(item.id))]
39
+ const results = []
40
+ let stop = false
41
+ for (const item of ordered) {
42
+ const row = current.get(item.id)
43
+ let result = 'rejected', detail = ''
44
+ if (!valid() || stop) {
45
+ result = 'skipped'
46
+ detail = tr('未提交', 'Not submitted')
47
+ } else if (!row || !actionable(row)) detail = explain({ code: 'session/queue-item-not-found' })
48
+ else if (action.kind === 'steer' && (row.placement !== 'queued' || !snapshot.running)) detail = explain({ code: 'session/steer-unavailable' })
49
+ else if (action.kind === 'edit' && (!editable(row) || JSON.stringify(contentOf(row)) !== JSON.stringify(contentOf(targets.get(item.id))))) {
50
+ detail = explain({ code: editable(row) ? 'session/queue-conflict' : 'session/queue-edit-attachments' })
51
+ } else {
52
+ const expected = action.kind === 'edit' ? { expectedContent: contentOf(row) } : {}
53
+ try {
54
+ const reply = await rpc('session.updateQueue', { sessionId, itemId: row.id, action, ...expected })
55
+ if (!reply?.accepted) throw new Error()
56
+ result = 'accepted'
57
+ detail = tr('主机已接受', 'Accepted by the Host')
58
+ } catch (error) {
59
+ if (knownRejection(error)) {
60
+ detail = explain(error)
61
+ if (denied(error) || error?.message === 'AUTH') stop = true
62
+ }
63
+ else {
64
+ stop = true
65
+ result = 'unknown'
66
+ detail = tr('结果未确认,不会重发', 'Unconfirmed; not retried')
67
+ }
68
+ }
69
+ }
70
+ results.push({ item: targets.get(item.id), result, detail })
71
+ }
72
+ return results
73
+ }
74
+
75
+ function create(config) {
76
+ let context, latestSeq, run, revision = 0, results = [], message = '', writable = null, dialog, signature
77
+ const valid = entry => entry && entry === context && entry.connection.valid() && config.session() === entry.sessionId
78
+ const current = () => {
79
+ if (!valid(context)) {
80
+ context = { connection: config.capture(), sessionId: config.session() }
81
+ latestSeq = undefined
82
+ results = []; message = ''; writable = null; signature = undefined
83
+ dialog?.close()
84
+ }
85
+ return context
86
+ }
87
+ function accept(sessionId, seq) {
88
+ const entry = current()
89
+ if (entry.sessionId !== sessionId || !Number.isSafeInteger(seq)) return true
90
+ if (Number.isSafeInteger(latestSeq) && seq < latestSeq) return false
91
+ latestSeq = seq
92
+ return true
93
+ }
94
+ async function refresh(entry = current()) {
95
+ if (!entry.sessionId || !entry.connection.token) return
96
+ const generation = ++revision
97
+ const readQueue = () => config.rpc('session.queueState', { sessionId: entry.sessionId })
98
+ let [snapshot, access] = await Promise.all([readQueue(), config.access(entry.connection)])
99
+ const checkSnapshot = () => {
100
+ if (!Array.isArray(snapshot?.items) || typeof snapshot.running !== 'boolean') throw new Error(tr('未收到主机队列', 'Host queue unavailable'))
101
+ return accept(entry.sessionId, snapshot.seq)
102
+ }
103
+ if (!valid(entry) || generation !== revision) return
104
+ if (!checkSnapshot()) {
105
+ snapshot = await readQueue()
106
+ if (!valid(entry) || generation !== revision) return
107
+ if (!checkSnapshot()) throw new Error(tr('队列正在变化,请重新读取', 'The queue is changing. Read it again.'))
108
+ }
109
+ writable = access
110
+ config.apply(entry.sessionId, snapshot)
111
+ return snapshot
112
+ }
113
+ function reconnect() {
114
+ const entry = current()
115
+ if (!entry.sessionId || !entry.connection.token || run?.entry === entry) return
116
+ writable = null
117
+ render()
118
+ void refresh(entry).then(() => { if (valid(entry)) render() }).catch(error => {
119
+ if (!valid(entry)) return
120
+ writable = denied(error) ? false : null
121
+ message = explain(error)
122
+ render()
123
+ })
124
+ }
125
+ async function mutate(wanted, action) {
126
+ const entry = current()
127
+ if (run || writable !== true || !wanted.length) return
128
+ run = { entry }
129
+ results = []; message = ''
130
+ render()
131
+ try {
132
+ const snapshot = await refresh(entry)
133
+ if (!snapshot || !valid(entry)) return
134
+ if (!writable) throw new Error('host-state/access-denied')
135
+ results = await writeItems({ rpc: config.rpc, sessionId: entry.sessionId, wanted, snapshot, action, valid: () => valid(entry) })
136
+ } catch (error) {
137
+ if (valid(entry)) message = explain(error)
138
+ } finally {
139
+ if (valid(entry)) {
140
+ try { await refresh(entry) } catch (error) {
141
+ if (valid(entry)) {
142
+ writable = denied(error) ? false : null
143
+ message = tr('未能重新读取队列;刷新前不能再次操作。', 'Could not reread the queue. Refresh before another change.')
144
+ }
145
+ }
146
+ }
147
+ run = null
148
+ if (!valid(entry)) results = []
149
+ render()
150
+ }
151
+ }
152
+ function edit(item) {
153
+ if (!editable(item) || writable !== true || run) return
154
+ if (!dialog) {
155
+ dialog = root.document.createElement('dialog')
156
+ dialog.className = 'host-state-dialog'
157
+ dialog.setAttribute('aria-labelledby', 'host-queue-edit-title')
158
+ root.document.body.append(dialog)
159
+ }
160
+ dialog.innerHTML = `<form method="dialog"><h2 id="host-queue-edit-title">${tr('编辑排队消息', 'Edit pending message')}</h2><label>${tr('正文', 'Message')}<textarea rows="6" required></textarea></label><div class="host-state-actions"><button value="cancel" formnovalidate>${tr('取消', 'Cancel')}</button><button value="save">${tr('保存', 'Save')}</button></div></form>`
161
+ const input = dialog.querySelector('textarea')
162
+ input.value = bodyOf(item)
163
+ const entry = current()
164
+ dialog.querySelector('form').onsubmit = event => {
165
+ if (event.submitter?.value !== 'save') return
166
+ event.preventDefault()
167
+ if (!input.value.trim() || !valid(entry)) return
168
+ dialog.close()
169
+ if (input.value !== bodyOf(item)) void mutate([item], { kind: 'edit', content: [{ type: 'text', text: input.value }] })
170
+ }
171
+ dialog.showModal()
172
+ }
173
+ function render() {
174
+ const entry = current()
175
+ const box = config.box()
176
+ if (!box) return
177
+ const items = (config.items() || []).filter(item => item?.id && ['queued', 'steering', 'context'].includes(item.placement))
178
+ const queued = items.filter(item => item.placement === 'queued')
179
+ const running = config.running(), busy = !!run
180
+ const next = JSON.stringify([items, running, busy, writable, results, message, root.I18N?.lang])
181
+ if (signature === next) return
182
+ signature = next
183
+ const expanded = new Set([...box.querySelectorAll('details[open]')].map(node => node.dataset.queueRow))
184
+ box.classList.toggle('hidden', !items.length && (!results.length && !busy))
185
+ const disabled = busy || writable !== true
186
+ const label = placement => placement === 'queued' ? tr('等待下轮', 'Waiting for next turn')
187
+ : placement === 'steering' ? tr('已插队 · 待注入', 'Steered · awaiting injection') : tr('待注入的主机上下文', 'Pending Host context')
188
+ const button = (action, title, locked, reason = '') => `<button type="button" data-queue-action="${action}" ${locked ? 'disabled' : ''} ${reason ? `title="${text(reason)}"` : ''}>${title}</button>`
189
+ box.innerHTML = `<div class="host-state-actions"><strong>${tr('主机队列', 'Host queue')} · ${items.length}</strong>${queued.length ? button('all', tr('全部按顺序插队', 'Steer all in order'), disabled || !running) : ''}${button('refresh', tr('刷新', 'Refresh'), busy)}</div>
190
+ ${writable === false ? `<small>${tr('此设备在这里是只读的。', 'This device has read-only access here.')}</small>` : ''}
191
+ ${message ? `<p role="status">${text(message)}</p>` : ''}
192
+ <div class="host-queue-rows">${items.map(item => `<details data-queue-row="${text(item.id)}" ${expanded.has(item.id) ? 'open' : ''}>
193
+ <summary><strong>${label(item.placement)}</strong> · ${text(bodyOf(item).replace(/\s+/g, ' ').slice(0, 100) || tr('展开查看内容', 'Expand for content'))}</summary>
194
+ <div data-queue-body></div>${actionable(item) ? `<div class="host-state-actions">${button('edit', tr('编辑', 'Edit'), disabled || !editable(item), editable(item) ? '' : explain({ code: 'session/queue-edit-attachments' }))}${button('remove', tr('删除', 'Delete'), disabled)}${item.placement === 'queued' ? button('steer', tr('插队', 'Steer'), disabled || !running) : ''}</div>${!editable(item) ? `<small>${explain({ code: 'session/queue-edit-attachments' })}</small>` : ''}` : ''}
195
+ </details>`).join('')}</div>
196
+ ${results.length ? `<ul class="host-state-results" aria-label="${tr('逐条结果', 'Per-item results')}">${results.map(({ item, detail }) => `<li>${text(bodyOf(item).replace(/\s+/g, ' ').slice(0, 60) || item.id)}:${text(detail)}</li>`).join('')}</ul>` : ''}`
197
+ for (const node of box.querySelectorAll('[data-queue-row]')) {
198
+ const item = items.find(row => row.id === node.dataset.queueRow)
199
+ const showBody = () => {
200
+ const body = node.querySelector('[data-queue-body]')
201
+ if (!node.open || body.dataset.loaded) return
202
+ body.dataset.loaded = '1'
203
+ const parts = contentOf(item)
204
+ body.innerHTML = Array.isArray(parts) ? parts.map(part => {
205
+ if (part?.type === 'text') return `<div class="host-state-pre">${text(part.text)}</div>`
206
+ if (part?.type === 'image' && part.attachment && root.DshImagePreview) return root.DshImagePreview.attachmentHtml(part.attachment, tr('图片', 'Image'), entry.sessionId)
207
+ if (part?.type === 'file' && root.DshChatFiles) return root.DshChatFiles.render(part)
208
+ return `<p>${tr('附件', 'Attachment')}:${text(part?.attachment?.name || part?.name || tr('无可预览内容', 'No preview available'))}</p>`
209
+ }).join('') : tr('正文未公开。', 'Content is not available.')
210
+ }
211
+ node.addEventListener('toggle', showBody)
212
+ showBody()
213
+ }
214
+ box.onclick = event => {
215
+ const trigger = event.target.closest('[data-queue-action]')
216
+ if (!trigger || trigger.disabled || !valid(entry)) return
217
+ const action = trigger.dataset.queueAction
218
+ if (action === 'refresh') return reconnect()
219
+ if (action === 'all') return void mutate(queued, { kind: 'steer' })
220
+ const item = items.find(row => row.id === trigger.closest('[data-queue-row]')?.dataset.queueRow)
221
+ if (!item) return
222
+ if (action === 'edit') return edit(item)
223
+ if (action === 'remove' && !root.confirm(tr('删除这条尚未注入的消息?', 'Delete this pending message?'))) return
224
+ void mutate([item], { kind: action })
225
+ }
226
+ }
227
+ return { accept, reconnect, render }
228
+ }
229
+ const api = { create, writeItems, editable, denied, knownRejection, readAccess }
230
+ if (typeof module !== 'undefined' && module.exports) module.exports = api
231
+ else root.DshHostQueue = api
232
+ })(globalThis)