dsh-remote-plugin 0.8.7 → 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 (70) 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 +659 -130
  5. package/index.mjs +33 -1
  6. package/package.json +8 -3
  7. package/public/activity.js +196 -52
  8. package/public/admin.html +34 -32
  9. package/public/admin.js +11 -2
  10. package/public/app.js +1341 -223
  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 +104 -76
  16. package/public/desktop/desktop.js +668 -101
  17. package/public/diagnostics.js +30 -4
  18. package/public/e2ee-transport.js +154 -7
  19. package/public/file-inbox.js +77 -18
  20. package/public/genui.css +10 -0
  21. package/public/genui.js +22 -4
  22. package/public/history.js +15 -2
  23. package/public/host-queue.js +232 -0
  24. package/public/host-schedule.js +301 -0
  25. package/public/host-state.css +19 -0
  26. package/public/index.html +347 -140
  27. package/public/md.js +21 -1
  28. package/public/network.js +33 -1
  29. package/public/onboarding.js +3 -3
  30. package/public/operations.js +26 -12
  31. package/public/plan-review.css +297 -0
  32. package/public/plan-review.js +621 -0
  33. package/public/plugin.html +29 -27
  34. package/public/relay-autopair.js +25 -10
  35. package/public/relay-settings.css +11 -0
  36. package/public/relay-settings.js +350 -28
  37. package/public/session-management.css +61 -0
  38. package/public/session-management.js +742 -0
  39. package/public/session-search.css +137 -0
  40. package/public/session-search.js +977 -0
  41. package/public/skins/blue-fish/preview.html +3 -3
  42. package/public/skins/bocchi/preview.html +5 -5
  43. package/public/skins/kita/preview.html +6 -6
  44. package/public/skins/miku/SOURCES.json +10 -0
  45. package/public/skins/miku/chibi.png +0 -0
  46. package/public/skins/miku/preview.html +33 -0
  47. package/public/skins/miku/skin.css +82 -0
  48. package/public/skins/nijika/preview.html +6 -6
  49. package/public/skins/penguin/preview.html +3 -3
  50. package/public/skins/penguin-logistics/cargo.svg +4 -0
  51. package/public/skins/penguin-logistics/console.svg +4 -0
  52. package/public/skins/penguin-logistics/mark.svg +4 -0
  53. package/public/skins/penguin-logistics/radio.svg +4 -0
  54. package/public/skins/penguin-logistics/skin.css +292 -0
  55. package/public/skins/penguin-logistics/standing.png +0 -0
  56. package/public/skins/ryo/preview.html +6 -6
  57. package/public/slash-suggestions.css +43 -0
  58. package/public/slash-suggestions.js +196 -0
  59. package/public/sponsor-entry.js +11 -3
  60. package/public/styles.css +141 -21
  61. package/public/subagents.css +7 -0
  62. package/public/subagents.js +83 -10
  63. package/public/theme-vars.css +102 -3
  64. package/public/theme.js +7 -4
  65. package/public/turn-diff.css +323 -0
  66. package/public/turn-diff.js +778 -0
  67. package/public/update.json +12 -12
  68. package/public/version.json +1 -1
  69. package/public/workflow.css +322 -43
  70. package/public/workflow.js +148 -44
@@ -2,7 +2,8 @@
2
2
  'use strict'
3
3
  function createDiagnosticSchema() {
4
4
  const MAX_EVENTS=160,MAX_CRITICAL=40,MAX_BYTES=48000
5
- const kinds=new Set(['rpc','history.load','history.cache','history.render','history.row','session.open','session.back','stream.state','stream.retry','poll.state','client.lifecycle','client.error','feedback.submit','announcement.storage','announcement.fetch','announcement.show','announcement.close','announcement.vote','storage.write','diagnostics.persist'])
5
+ const kinds=new Set(['rpc','history.load','history.cache','history.render','history.row','session.open','session.back','stream.state','stream.retry','poll.state','client.lifecycle','client.error','feedback.submit','announcement.storage','announcement.fetch','announcement.show','announcement.close','announcement.vote','storage.write','diagnostics.persist','relay.http','relay.fetch'])
6
+ kinds.add('relay.native')
6
7
  const enums={phase:['start','response','prepared','rendered','complete','failed','navigate','cleanup','hit','miss','retry'],channel:['mux','host'],status:['open','closed','connecting','poll','ws','visible','hidden','online','offline','running','stopped','starting','disabled','start-failed','timeout','error','unknown','granted','denied','default'],category:['authentication','timeout','network','render','syntax','upstream','unknown'],errorName:['Error','TypeError','RangeError','SyntaxError','ReferenceError','AbortError','TimeoutError','NetworkError']}
7
8
  enums.serviceState=['starting','running','stopped','disabled','start-failed','system-timeout','auth-expired']
8
9
  enums.storageKey=['seen','history','votes']
@@ -13,8 +14,18 @@ function createDiagnosticSchema() {
13
14
  enums.category.push('storage','validation')
14
15
  enums.errorName.push('QuotaExceededError','SecurityError','InvalidStateError','DataError','UnknownError')
15
16
  enums.reason=['already-open','already-read','version-warning','empty','http','network','invalid-json','too-large','unavailable']
17
+ enums.httpMethod=['GET','OPTIONS','POST']
18
+ enums.relayRoute=['session.list','session.history','ws-ticket','operations']
19
+ enums.relayStage=['received','opening-channel','forwarding-headers','waiting-response','response','local-busy','connect-failed','forward-failed','request-closed','closed-before-response','response-timeout','response-invalid','response-header-limit','resolve-failed','fetch-failed','accepted','reading-headers','worker-rejected','accept-interrupted','header-eof','header-timeout','header-too-large','header-read-failed','request-line-rejected','request-headers-rejected','listener-closed']
20
+ enums.relayStage.push('native-response','native-timeout','native-network','native-unavailable','native-too-large','native-invalid','native-aborted')
21
+ enums.relayCors=['allowed','missing','mismatch']
22
+ enums.relayMode=['mapped','direct']
23
+ enums.relayListenerBefore=['open','closed','missing']
24
+ enums.relayListenerAfter=['open','closed','missing']
16
25
  const numbers=['durationMs','httpStatus','closeCode','attempt','delayMs','count','rawCount','renderedCount','renderErrors','lastSuccessAt','intervalMin','apiLevel','storageChars','storageKeys','legacyCacheChars','legacyCacheKeys','historyCacheChars','sessionCacheChars','announcementChars','diagnosticChars','droppedEvents']
17
- const booleans=['reset','cached','loading','loaded','hasMore','online','enabled','serviceRunning','loginExpired','powerSave','ignoreBatteryOptimizations','notificationsEnabled','persisted','indexedDbAvailable','storageAvailable']
26
+ numbers.push('relayProxyId','relayAcceptNumber','relayAcceptBefore','relayAcceptAfter')
27
+ numbers.push('relaySlotLimit','relaySlotsUsedBefore','relaySlotsUsedAfter','relayBusyBefore','relayBusyAfter')
28
+ const booleans=['reset','cached','loading','loaded','hasMore','online','enabled','serviceRunning','loginExpired','powerSave','ignoreBatteryOptimizations','notificationsEnabled','persisted','indexedDbAvailable','storageAvailable','relayForwarded','relayBodyForwarded']
18
29
  const methods=new Set(['session.list','session.history','session.create','session.prompt','session.fork','session.cancel','session.rename','session.selectModel','session.updateQueue','session.getModels','session.getQueue','session.getCompactionStatus','workspace.list','workspace.create','workspace.archiveSession','host.describe','subagent.list','subagent.interrupt','goal.edit','goal.pause','goal.resume','goal.complete','goal.clear'])
19
30
  for(const method of ['session.models','llm.discoverModels','llm.providers','credentials.describe','credentials.set','credentials.unset','settings.describe','settings.mutate','settings.openDocument'])methods.add(method)
20
31
  const hex=(v,n)=>typeof v==='string'&&new RegExp('^[a-f0-9]{'+n+'}$').test(v)?v:undefined
@@ -84,7 +95,22 @@ function createDiagnosticSchema() {
84
95
  storageAt=now();storageInventory=value;return value
85
96
  }
86
97
  function snapshot(force=false){let value={};try{value=config.snapshot?.()||{}}catch{};return schema.facts({...value,...storageFacts(force),droppedEvents,sessionRef:pseudonym(value.sessionId),serverRef:pseudonym(value.server||env.location?.origin),online:env.navigator?.onLine!==false})}
87
- function makeReport(force=false){trim();return schema.sanitizeReport({schema:1,reportId:random(),capturedAt:now(),client:{...metadata,surface:config.surface||'mobile'},snapshot:snapshot(force),persistence,events:rows})}
98
+ function nativeHttpEvents() {
99
+ try {
100
+ const native = JSON.parse(env.NativeE2ee?.httpDiagnostics?.() || '[]')
101
+ if (!Array.isArray(native)) return []
102
+ const active = new Set(['accepted','reading-headers','received','opening-channel','forwarding-headers','waiting-response'])
103
+ return native.slice(-64).filter(row => Number.isFinite(row?.at)).map(row => ({
104
+ ...row, kind:'relay.http',
105
+ phase: active.has(row.relayStage) ? 'start' : row.relayStage === 'response' && row.httpStatus < 400 ? 'response' : 'failed',
106
+ }))
107
+ } catch { return [] }
108
+ }
109
+ function makeReport(force=false){
110
+ trim()
111
+ const events=force?[...rows,...nativeHttpEvents()].sort((a,b)=>a.at-b.at):rows
112
+ return schema.sanitizeReport({schema:1,reportId:random(),capturedAt:now(),client:{...metadata,surface:config.surface||'mobile'},snapshot:snapshot(force),persistence,events})
113
+ }
88
114
  const report=()=>makeReport(true)
89
115
  function openDatabase(){
90
116
  if(database)return database
@@ -151,7 +177,7 @@ function createDiagnosticSchema() {
151
177
  function start(kind,fields={}){const begun=now(),traceId=run.slice(0,12)+(++sequence).toString(16).padStart(12,'0');record(kind,{...fields,phase:'start',traceId});return {traceId,end:value=>record(kind,{...fields,...value,traceId,durationMs:now()-begun}),fail:error=>record(kind,{...fields,...errorFacts(error),phase:'failed',traceId,durationMs:now()-begun})}}
152
178
  function nativeSnapshot(){try{const value=JSON.parse(env.NativeBackground?.getBackgroundConfig?.()||'{}');return schema.facts({...value,httpStatus:value.lastHttpStatus})}catch{return {}}}
153
179
  function configure(value){config=value;record('client.lifecycle',{status:env.document?.visibilityState==='hidden'?'hidden':'visible',...nativeSnapshot()});mount()}
154
- function clear(){epoch++;rows=[];droppedEvents=0;flush();refreshPreview()}
180
+ function clear(){epoch++;rows=[];droppedEvents=0;try{env.NativeE2ee?.clearHttpDiagnostics?.()}catch{};flush();refreshPreview()}
155
181
  function storageFailure(key,error,backend='local'){const category=/^historyCache/.test(key)?'history':/^sessionsCache/.test(key)?'session-list':key==='seenAnnouncementsV1'?'seen':key==='announcementHistoryV1'?'history':key==='announcementVotesV1'?'votes':/^dshApprovalRecordsV1/.test(key)?'approvals':'settings';storageFacts(true);return record('storage.write',{phase:'failed',storageKey:category,storageBackend:backend,...errorFacts(error)})}
156
182
  function text(){return JSON.stringify(report(),null,2)}
157
183
  const label=(zh,en)=>env.I18N?.lang==='en'?en:zh
@@ -5,25 +5,172 @@
5
5
  if (!bridge?.resolve) return
6
6
  const active = new Set()
7
7
  function changed(origin) { for (const request of [...active]) if (request.origin === origin) request.cancel() }
8
- function resolve(input) {
8
+ function resolveMapping(input) {
9
9
  const original = String(input), value = JSON.parse(bridge.resolve(original))
10
10
  if (value.error || typeof value.url !== 'string') throw new Error('E2EE_TRANSPORT_UNAVAILABLE')
11
11
  if ((value.secure || value.paired) && !/^(?:http|ws):\/\/127\.0\.0\.1:\d+\/e2ee-[a-f0-9]{48}\//.test(value.url)) throw new Error('E2EE_TRANSPORT_UNAVAILABLE')
12
- return value.url
12
+ return value
13
+ }
14
+ const resolve = input => resolveMapping(input).url
15
+ function listenerState(mapped) {
16
+ try { return JSON.parse(bridge.localHttpState?.(mapped) || '{}') || {} } catch { return {} }
17
+ }
18
+ function listenerFacts(mapped, initial) {
19
+ if (!initial) return {}
20
+ const current = listenerState(mapped)
21
+ return {
22
+ relayProxyId: initial.relayProxyId,
23
+ relayListenerBefore: initial.relayListener,
24
+ relayListenerAfter: current.relayListener,
25
+ relayAcceptBefore: initial.relayAcceptCount,
26
+ relayAcceptAfter: current.relayAcceptCount,
27
+ relaySlotLimit: initial.relaySlotLimit,
28
+ relaySlotsUsedBefore: initial.relaySlotsUsed,
29
+ relaySlotsUsedAfter: current.relaySlotsUsed,
30
+ relayBusyBefore: initial.relayBusyCount,
31
+ relayBusyAfter: current.relayBusyCount,
32
+ }
33
+ }
34
+ async function nativeHttp({ mapped, init, signal, traceId, route, method, timeout, start, read }) {
35
+ const initial = listenerState(mapped)
36
+ const started = Date.now()
37
+ let id, status, stage = 'native-unavailable', response
38
+ try {
39
+ if (signal.aborted) { stage = 'native-aborted'; return null }
40
+ const headers = new Headers(init.headers)
41
+ id = start(headers.get('authorization') || '', headers.get('x-dsh-remote-client-id') || '')
42
+ if (!id) return null
43
+ stage = 'native-timeout'
44
+ while (!signal.aborted && Date.now() - started < timeout) {
45
+ const raw = bridge.pollHttpRequest(id)
46
+ if (raw) {
47
+ const result = JSON.parse(raw)
48
+ stage = result.outcome
49
+ status = result.status || undefined
50
+ if (stage === 'native-response') {
51
+ stage = 'native-invalid'
52
+ response = read(result)
53
+ if (response) stage = 'native-response'
54
+ }
55
+ return response || null
56
+ }
57
+ await new Promise(resolve => setTimeout(resolve, 60))
58
+ }
59
+ if (signal.aborted) stage = 'native-aborted'
60
+ return null
61
+ } catch {
62
+ if (stage !== 'native-invalid') stage = 'native-network'
63
+ return null
64
+ } finally {
65
+ if (id) { try { bridge.cancelHttpRequest(id) } catch {} }
66
+ root.DshDiagnostics?.record('relay.native', {
67
+ ...listenerFacts(mapped, initial), phase: response?.ok ? 'response' : 'failed', relayStage: stage, relayMode: 'mapped',
68
+ relayRoute: route, httpMethod: method, traceId, httpStatus: status, durationMs: Date.now() - started,
69
+ })
70
+ }
71
+ }
72
+ function jsonResponse(body, status) {
73
+ return new Response([204, 205, 304].includes(status) ? null : body, { status, headers: { 'content-type': 'application/json' } })
74
+ }
75
+ function nativeSessionList(mapped, init, signal, traceId) {
76
+ if (typeof bridge.startListProbe !== 'function' || signal.aborted || typeof init?.body !== 'string') return null
77
+ let body
78
+ try { body = JSON.parse(init.body) } catch { return null }
79
+ if (body?.type !== 'client-request' || body.method !== 'session.list' || typeof body.rpcId !== 'string'
80
+ || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload) || Object.keys(body.payload).length) return null
81
+ return nativeHttp({ mapped, init, signal, traceId, route: 'session.list', method: 'POST', timeout: 6000,
82
+ start: (auth, clientId) => bridge.startListProbe(mapped, auth, clientId, body.rpcId),
83
+ read: ({ status, body }) => {
84
+ if (status !== 200) return null
85
+ const rpc = JSON.parse(body)?.result
86
+ return rpc?.ok === true && Array.isArray(rpc.value?.items) ? jsonResponse(body, status) : null
87
+ },
88
+ })
89
+ }
90
+ function nativeHistory(mapped, init, signal, traceId) {
91
+ return nativeHttp({ mapped, init, signal, traceId, route: 'session.history', method: 'POST', timeout: 13000,
92
+ start: (auth, clientId) => bridge.startHistoryRequest(mapped, auth, clientId, init.body),
93
+ read: ({ status, body }) => jsonResponse(body, status),
94
+ })
95
+ }
96
+ async function nativeOperation(mapped, method, init, signal) {
97
+ if (signal.aborted) throw signal.reason
98
+ const body = method === 'POST' ? init.body : null
99
+ if (body?.length > 4 * 1024 * 1024) return jsonResponse('{"error":"body-too-large"}', 413)
100
+ const response = await nativeHttp({ mapped, init, signal, route: 'operations', method, timeout: 15000,
101
+ start: (auth, clientId) => bridge.startOperationRequest(mapped, method, auth, clientId, body),
102
+ read: ({ status, body }) => jsonResponse(body, status),
103
+ })
104
+ if (signal.aborted) throw signal.reason
105
+ if (!response) throw new TypeError('E2EE_OPERATION_TRANSPORT_FAILED')
106
+ return response
13
107
  }
14
108
  const fetch = root.fetch.bind(root)
15
109
  root.fetch = function(input, init) {
110
+ let diagnostic, diagnosticRoute, relayMode, mapped, initialListener, cleanup
16
111
  try {
17
112
  const request = typeof root.Request === 'function' && input instanceof root.Request
18
113
  const url = request ? input.url : new URL(String(input), root.location.href).href
19
- const mapped = resolve(url)
114
+ const parsed = new URL(url)
115
+ const method = String(init?.method || (request ? input.method : 'GET')).toUpperCase()
116
+ if (typeof bridge.httpDiagnostics === 'function' && method === 'POST') {
117
+ const route = parsed.pathname.slice(5)
118
+ if (parsed.pathname.startsWith('/api/') && ['session.list', 'session.history', 'ws-ticket', 'operations'].includes(route)) diagnosticRoute = route
119
+ }
120
+ const mapping = resolveMapping(url)
121
+ mapped = mapping.url
122
+ relayMode = mapped === url ? 'direct' : 'mapped'
123
+ const useNativeOperation = relayMode === 'mapped' && mapping.secure === true && !request
124
+ && typeof bridge.startOperationRequest === 'function' && parsed.pathname === '/api/operations'
125
+ && /^\?id=[A-Za-z0-9_-]{16,80}$/.test(parsed.search)
126
+ && (method === 'POST' ? typeof init?.body === 'string' : method === 'GET' && init?.body == null)
127
+ const useNativeTicket = relayMode === 'mapped' && mapping.secure === true && !request && method === 'POST'
128
+ && parsed.pathname === '/api/ws-ticket' && !parsed.search && init?.body == null && typeof bridge.startTicketRequest === 'function'
129
+ const useNativeHistory = relayMode === 'mapped' && mapping.secure === true && !request && method === 'POST'
130
+ && parsed.pathname === '/api/session.history' && !parsed.search && typeof init?.body === 'string'
131
+ && init.body.length <= 8192 && typeof bridge.startHistoryRequest === 'function'
132
+ if (!useNativeOperation && !useNativeTicket && diagnosticRoute) diagnostic = root.DshDiagnostics?.start('relay.fetch', { relayRoute: diagnosticRoute, httpMethod: method })
133
+ if (diagnostic && relayMode === 'mapped') initialListener = listenerState(mapped)
20
134
  const controller = new root.AbortController(), signal = init?.signal || (request ? input.signal : null)
21
- const cancel = () => controller.abort(signal?.reason), entry = { origin: new URL(url).origin, cancel: () => controller.abort() }
135
+ const cancel = () => controller.abort(signal?.reason), entry = { origin: parsed.origin, cancel: () => controller.abort() }
22
136
  if (signal?.aborted) cancel(); else signal?.addEventListener('abort', cancel, { once: true })
23
137
  active.add(entry)
24
- return fetch(mapped === url ? input : request ? new root.Request(mapped, input) : mapped, { ...init, signal: controller.signal })
25
- .finally(() => { active.delete(entry); signal?.removeEventListener('abort', cancel) })
26
- } catch (error) { return Promise.reject(error) }
138
+ cleanup = () => { active.delete(entry); signal?.removeEventListener('abort', cancel) }
139
+ if (useNativeOperation) return nativeOperation(mapped, method, init || {}, controller.signal).finally(cleanup)
140
+ const browserFetch = () => fetch(mapped === url ? input : request ? new root.Request(mapped, input) : mapped, { ...init, signal: controller.signal })
141
+ if (useNativeTicket) {
142
+ return nativeHttp({ mapped, init, signal: controller.signal, route: 'ws-ticket', method, timeout: 6000,
143
+ start: (auth, clientId) => bridge.startTicketRequest(mapped, auth, clientId),
144
+ read: ({ status, body }) => jsonResponse(body, status),
145
+ }).then(response => {
146
+ if (controller.signal.aborted) throw controller.signal.reason
147
+ return response || browserFetch()
148
+ }).finally(cleanup)
149
+ }
150
+ const result = browserFetch()
151
+ if (!diagnostic && !useNativeHistory) return result.finally(cleanup)
152
+ return result.then(response => {
153
+ diagnostic?.end({ ...listenerFacts(mapped, initialListener), phase: response.ok ? 'response' : 'failed', relayStage: 'response', relayMode, httpStatus: response.status })
154
+ return response
155
+ }, async error => {
156
+ diagnostic?.end({ ...root.DshDiagnostics.errorFacts(error), ...listenerFacts(mapped, initialListener), phase: 'failed', relayStage: 'fetch-failed', relayMode })
157
+ if (error.name === 'TypeError' && !controller.signal.aborted) {
158
+ let recovered
159
+ if (useNativeHistory) recovered = await nativeHistory(mapped, init, controller.signal, diagnostic?.traceId)
160
+ else if (relayMode === 'mapped' && !request && method === 'POST' && parsed.pathname === '/api/session.list' && !parsed.search) {
161
+ recovered = await nativeSessionList(mapped, init, controller.signal, diagnostic?.traceId)
162
+ }
163
+ if (controller.signal.aborted) throw controller.signal.reason || error
164
+ if (recovered) return recovered
165
+ }
166
+ throw error
167
+ }).finally(cleanup)
168
+ } catch (error) {
169
+ cleanup?.()
170
+ if (!mapped && diagnosticRoute) diagnostic = root.DshDiagnostics?.start('relay.fetch', { relayRoute: diagnosticRoute, httpMethod: 'POST' })
171
+ diagnostic?.end({ ...root.DshDiagnostics.errorFacts(error), ...listenerFacts(mapped, initialListener), phase: 'failed', relayStage: relayMode ? 'fetch-failed' : 'resolve-failed', relayMode })
172
+ return Promise.reject(error)
173
+ }
27
174
  }
28
175
  if (root.WebSocket) {
29
176
  const WebSocket = root.WebSocket
@@ -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
@@ -31,7 +31,11 @@
31
31
  this.retry=document.createElement('button');this.retry.type='button';this.retry.className='history-page-control';this.retry.textContent=options.retryLabel?.()||'Retry'
32
32
  this.retry.addEventListener('click',()=>options.retry?.())
33
33
  this.live=document.createElement('div'); this.live.className='history-live'
34
- box.addEventListener('toggle',event=>{const detail=event.target;if(detail?.dataset?.activityKey)this.rememberDisclosure(detail)},true)
34
+ box.addEventListener('toggle',event=>{
35
+ const detail=event.target
36
+ if(detail?.dataset?.activityKey)this.rememberDisclosure(detail)
37
+ if(detail?.dataset?.activitySummary!=null)this.updateActivityRows()
38
+ },true)
35
39
  const intent=()=>{this.intentUntil=Date.now()+1200}
36
40
  const hold=()=>{intent();this.reading=true;this.options.changed?.(this)}
37
41
  box.addEventListener('wheel',event=>{intent();if(event.deltaY<0)hold()},{passive:true})
@@ -48,7 +52,7 @@
48
52
  }
49
53
  anchor() {
50
54
  const top=this.box.getBoundingClientRect().top
51
- for(const node of this.box.querySelectorAll('.history-entry'))if(node.getBoundingClientRect().bottom>=top+1)return {seq:Number(node.dataset.historySeq),top:node.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}
52
56
  return null
53
57
  }
54
58
  get unread() {return Math.max(0,this.entries.length-this.end)}
@@ -88,6 +92,14 @@
88
92
  }
89
93
  captureDisclosures(node) {for(const detail of node.querySelectorAll('details[data-activity-key]'))this.rememberDisclosure(detail)}
90
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)}
95
+ updateActivityRows() {
96
+ 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]')){
98
+ const id=detail.dataset.activityTurn, controller=rendered.get(id), row=detail.parentNode
99
+ // If the summary has scrolled out of the rendered page, keep this group reachable.
100
+ row.hidden=!!controller&&!controller.open
101
+ }
102
+ }
91
103
  render(anchor, bottom=false) {
92
104
  const box=this.box, slice=this.entries.slice(this.start,Math.min(this.end,this.start+WINDOW_SIZE)), desired=[]
93
105
  this.captureDisclosures(box)
@@ -112,6 +124,7 @@
112
124
  if(this.more.parentNode!==box)box.prepend(this.more)
113
125
  let cursor=this.more.nextSibling
114
126
  for(const node of desired){if(node===cursor)cursor=cursor.nextSibling;else box.insertBefore(node,cursor)}
127
+ this.updateActivityRows()
115
128
  const empty=!desired.length&&!this.liveHtml, unreadable=empty&&slice.length>0
116
129
  this.empty.textContent=unreadable?(this.options.unreadableLabel?.()||this.emptyLabel):this.emptyLabel
117
130
  if(empty){if(this.empty.parentNode!==box)box.append(this.empty)}else this.empty.remove()