@linxin666/dsh-remote-bridge 0.4.7 → 0.4.9

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 (78) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +93 -26
  3. package/README.zh.md +91 -26
  4. package/icon.svg +3 -0
  5. package/lib/client.js +274 -253
  6. package/lib/client.js.map +1 -1
  7. package/lib/index.js +8891 -2433
  8. package/lib/types/client/PairEntry.d.ts +2 -2
  9. package/lib/types/client/PairPanel.d.ts +10 -2
  10. package/lib/types/client/icons.d.ts +5 -13
  11. package/lib/types/client/locales.d.ts +10 -14
  12. package/lib/types/client/semantic.d.ts +9 -5
  13. package/lib/types/core/approvals.d.ts +24 -0
  14. package/lib/types/core/commands.d.ts +59 -0
  15. package/lib/types/core/connection.d.ts +124 -5
  16. package/lib/types/core/delta.d.ts +101 -0
  17. package/lib/types/core/devices.d.ts +98 -2
  18. package/lib/types/core/dsh-frames.d.ts +155 -4
  19. package/lib/types/core/envelope.d.ts +34 -0
  20. package/lib/types/core/extension.d.ts +144 -0
  21. package/lib/types/core/hub.d.ts +96 -20
  22. package/lib/types/core/jobs.d.ts +204 -0
  23. package/lib/types/core/liveactivity.d.ts +324 -0
  24. package/lib/types/core/protocol.d.ts +491 -2
  25. package/lib/types/core/push.d.ts +178 -0
  26. package/lib/types/core/questions.d.ts +109 -9
  27. package/lib/types/core/session-meta.d.ts +55 -1
  28. package/lib/types/core/squads.d.ts +130 -0
  29. package/lib/types/core/usage-stats.d.ts +160 -0
  30. package/lib/types/core/usage.d.ts +294 -0
  31. package/lib/types/core/wire.d.ts +1 -1
  32. package/lib/types/core/ws-frames.d.ts +11 -0
  33. package/lib/types/host/apns.d.ts +151 -0
  34. package/lib/types/host/squads-ledger.d.ts +39 -0
  35. package/lib/types/host/squads.d.ts +77 -0
  36. package/lib/types/host/usage-stats.d.ts +75 -0
  37. package/lib/types/host/watchers.d.ts +88 -0
  38. package/lib/types/host/websocket.d.ts +8 -1
  39. package/lib/types/index.d.ts +34 -3
  40. package/lib/types/mount-once.d.ts +55 -0
  41. package/locale/en.json +6 -0
  42. package/locale/ru.json +6 -0
  43. package/locale/zh.json +6 -0
  44. package/package.json +20 -14
  45. package/src/client/PairEntry.tsx +58 -31
  46. package/src/client/PairPanel.tsx +181 -97
  47. package/src/client/icons.tsx +17 -60
  48. package/src/client/locales.ts +15 -23
  49. package/src/client/panel.module.css +239 -186
  50. package/src/client/semantic.ts +10 -6
  51. package/src/core/approvals.ts +32 -1
  52. package/src/core/commands.ts +95 -0
  53. package/src/core/connection.ts +1483 -31
  54. package/src/core/delta.ts +204 -0
  55. package/src/core/devices.ts +221 -3
  56. package/src/core/dsh-frames.ts +365 -8
  57. package/src/core/envelope.ts +46 -0
  58. package/src/core/extension.ts +197 -0
  59. package/src/core/hub.ts +441 -49
  60. package/src/core/jobs.ts +372 -0
  61. package/src/core/liveactivity.ts +833 -0
  62. package/src/core/protocol.ts +556 -2
  63. package/src/core/push.ts +354 -0
  64. package/src/core/questions.ts +264 -17
  65. package/src/core/session-meta.ts +73 -1
  66. package/src/core/squads.ts +345 -0
  67. package/src/core/usage-stats.ts +424 -0
  68. package/src/core/usage.ts +937 -0
  69. package/src/core/wire.ts +13 -1
  70. package/src/core/ws-frames.ts +14 -0
  71. package/src/host/apns.ts +320 -0
  72. package/src/host/squads-ledger.ts +105 -0
  73. package/src/host/squads.ts +206 -0
  74. package/src/host/usage-stats.ts +155 -0
  75. package/src/host/watchers.ts +272 -0
  76. package/src/host/websocket.ts +37 -3
  77. package/src/index.ts +310 -9
  78. package/src/mount-once.ts +142 -0
@@ -0,0 +1,372 @@
1
+ /**
2
+ * The bridge's read-only window on the host's background jobs: one minimal
3
+ * projection per job, and the change notification a phone's navigation bar
4
+ * needs to keep a count honest.
5
+ *
6
+ * There is exactly one source of truth here and it is the host's own job
7
+ * registry (`ctx.jobs`, the service the `dsh-api-job-controller` Remote
8
+ * namespace is itself a projection of). This module adds no second store, no
9
+ * polling loop and no invented status vocabulary: it reads `list()`, publishes
10
+ * the host's own `kind` and `status` strings verbatim, and hears changes from
11
+ * the registry's own event stream.
12
+ *
13
+ * Two shapes of the host's API matter to what a phone can be shown:
14
+ *
15
+ * - `list(caller)` is owner-fenced. Naming a session returns that session's own
16
+ * jobs plus every job no session owns; naming no session returns only the
17
+ * unowned jobs. Those are TWO truthful scopes, not one global view, and the
18
+ * host has no global view to offer: a job list is never "every job in the
19
+ * process" unless every job in the process happens to be unowned.
20
+ * - The event stream reports `output` appends as well as lifecycle commits. An
21
+ * append says nothing about the SET, so it is dropped here: this channel
22
+ * never publishes per output byte, which is the whole reason the roster is
23
+ * not a projection of `job/follow`.
24
+ *
25
+ * The types below mirror `@deepseek-ai/dsh-jobs` field for field. That package
26
+ * is the host's, not this one's, so the contract is declared structurally
27
+ * instead of imported — the same rule `questions.ts` and `wire.ts` follow, and
28
+ * what keeps a test double down to the two members actually called.
29
+ * @module dsh-remote-bridge/core/jobs
30
+ */
31
+
32
+ import { failureText } from './gateway-errors.ts'
33
+
34
+ /**
35
+ * The slice of the host's `JobView` this bridge reads.
36
+ *
37
+ * Deliberately not the whole view: `output` (the ring's offsets and spill
38
+ * paths), `progress`, `detail` and `outputLimitBytes` are host bookkeeping a
39
+ * phone neither shows nor needs, and a projection that read them would tempt a
40
+ * later change into publishing bytes.
41
+ */
42
+ export interface JobViewLike {
43
+ readonly id: string
44
+ readonly kind: string
45
+ readonly label: string
46
+ /** Owning session; absent for an unowned job, which every caller can see. */
47
+ readonly owner?: string
48
+ readonly status: string
49
+ /** Epoch milliseconds. */
50
+ readonly startedAt: number
51
+ /** Epoch milliseconds; absent while the job is live. */
52
+ readonly finishedAt?: number
53
+ }
54
+
55
+ /** One lifecycle event of the host's event stream, as far as this bridge reads it. */
56
+ export interface JobEventLike {
57
+ /** `output` is the one type this bridge drops without reading further. */
58
+ readonly type: string
59
+ /** The job's projection after the commit; absent on an `output` append. */
60
+ readonly job?: JobViewLike
61
+ /** Owning session, carried by `output` events, which carry no projection. */
62
+ readonly owner?: string
63
+ }
64
+
65
+ /** Who a subscription hears about. `all` is what a bridge serving every session asks for. */
66
+ export type JobEventFilterLike = { readonly owners: 'all' | 'scope' } | { readonly owner: string }
67
+
68
+ /** The host registry's event stream. */
69
+ export interface JobEventsFace {
70
+ subscribe(filter: JobEventFilterLike, listener: (event: JobEventLike) => void): () => void
71
+ }
72
+
73
+ /**
74
+ * The slice of `ctx.jobs` this package reads.
75
+ *
76
+ * Optional in the plugin's faces for the reason the metadata faces are: the
77
+ * registry is not in this plugin's `inject` list, and a host that composes no
78
+ * job plugin answers `jobs-unavailable` instead of failing to start.
79
+ */
80
+ export interface JobRegistryFace {
81
+ list(caller?: string): readonly JobViewLike[]
82
+ readonly events: JobEventsFace
83
+ }
84
+
85
+ /** Which truthful scope one roster answer covers. */
86
+ export type JobScope = 'session' | 'unowned'
87
+
88
+ /**
89
+ * One job in protocol v1 vocabulary: the minimal, stable view.
90
+ *
91
+ * `kind` and `status` are the host's own strings, verbatim — this protocol
92
+ * publishes no enum of its own, so a producer kind or a lifecycle status added
93
+ * in the host crosses unchanged instead of being flattened into a guess.
94
+ * Every optional key is omitted when the host omitted it, never filled in.
95
+ */
96
+ export interface JobRow {
97
+ readonly id: string
98
+ readonly kind: string
99
+ readonly status: string
100
+ /** The host's `label`: its own one-line description, the field a phone renders as the job's title. */
101
+ readonly label?: string
102
+ /** The host's `owner`, verbatim, under a name that cannot be read as an object. */
103
+ readonly ownerSessionId?: string
104
+ readonly startedAt?: number
105
+ readonly finishedAt?: number
106
+ }
107
+
108
+ /**
109
+ * The body of one `jobs.list` answer and of one `jobs.changed` event.
110
+ *
111
+ * One box for both, so a client parses its navigation-bar count out of the same
112
+ * shape it refreshes through, and so a client holding two scopes open can tell
113
+ * whose set moved. `sessionId` is present exactly when the scope is `session`.
114
+ */
115
+ export interface JobsPayload {
116
+ readonly sessionId?: string
117
+ readonly scope: JobScope
118
+ readonly jobs: readonly JobRow[]
119
+ }
120
+
121
+ /**
122
+ * Coalescing window of one roster publish, in milliseconds.
123
+ *
124
+ * The host registry announces every commit synchronously, so a job that
125
+ * registers, reports progress and settles in one turn is three events for one
126
+ * fact a phone renders as one row. This window folds a burst into a single
127
+ * whole-set read, which is why the topic can never turn into a stream of
128
+ * frames. It matches the job controller's own `observeFlushMs` default, so a
129
+ * browser and a phone watching the same set refresh at the same cadence.
130
+ */
131
+ export const JOBS_FLUSH_MS = 100
132
+
133
+ /** Largest number of job rows one payload carries before it risks the frame budget. */
134
+ export const JOBS_MAX_ROWS = 200
135
+
136
+ /**
137
+ * Project one host job into the protocol's own fields.
138
+ *
139
+ * Explicitly field by field: an unknown key the host adds later must not reach
140
+ * the wire, and a value of the wrong type is dropped rather than coerced — the
141
+ * key is simply absent, which a client already has to handle.
142
+ * @param job - the host's projection.
143
+ * @returns the minimal row, or undefined when the host gave no usable id.
144
+ */
145
+ export function projectJob(job: JobViewLike): JobRow | undefined {
146
+ if (typeof job.id !== 'string' || job.id === '') return undefined
147
+ return {
148
+ id: job.id,
149
+ kind: typeof job.kind === 'string' ? job.kind : '',
150
+ status: typeof job.status === 'string' ? job.status : '',
151
+ ...(typeof job.label === 'string' && job.label !== '' ? { label: job.label } : {}),
152
+ ...(typeof job.owner === 'string' && job.owner !== '' ? { ownerSessionId: job.owner } : {}),
153
+ ...(Number.isFinite(job.startedAt) ? { startedAt: job.startedAt } : {}),
154
+ ...(Number.isFinite(job.finishedAt) ? { finishedAt: job.finishedAt } : {}),
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Project a whole host roster.
160
+ * @param jobs - the host's projections.
161
+ * @returns the rows, in the host's own order, bounded by {@link JOBS_MAX_ROWS}.
162
+ */
163
+ export function projectJobs(jobs: readonly JobViewLike[]): readonly JobRow[] {
164
+ const rows: JobRow[] = []
165
+ for (const job of jobs) {
166
+ const row = projectJob(job)
167
+ if (row !== undefined) rows.push(row)
168
+ if (rows.length >= JOBS_MAX_ROWS) break
169
+ }
170
+ return rows
171
+ }
172
+
173
+ /** The key one scope is subscribed and deduplicated under. */
174
+ export function scopeKey(sessionId?: string): string {
175
+ return sessionId === undefined ? 'unowned' : `session:${sessionId}`
176
+ }
177
+
178
+ /**
179
+ * Whether one job belongs in one scope's visible set.
180
+ *
181
+ * This is the host's own fence, restated for routing events: a session sees its
182
+ * own jobs plus every unowned one, and the unowned scope sees exactly the jobs
183
+ * no session owns.
184
+ * @param owner - the job's owning session, when it has one.
185
+ * @param sessionId - the scope's session; omitted for the unowned scope.
186
+ */
187
+ export function inScope(owner: string | undefined, sessionId?: string): boolean {
188
+ if (sessionId === undefined) return owner === undefined
189
+ return owner === undefined || owner === sessionId
190
+ }
191
+
192
+ /** One watched scope and everything published for it. */
193
+ interface ScopeWatch {
194
+ readonly sessionId: string | undefined
195
+ readonly key: string
196
+ /** One listener per connection that asked for this scope. */
197
+ readonly listeners: Set<(payload: JobsPayload) => void>
198
+ /** Set while a burst is waiting for its coalescing window to elapse. */
199
+ timer: NodeJS.Timeout | undefined
200
+ }
201
+
202
+ /** Everything one mount's roster was built with. */
203
+ export interface JobRosterOptions {
204
+ /** Resolves the host registry now; called per read, never captured once, so a registry that mounts later is still picked up. */
205
+ readonly faces: () => { readonly jobs?: JobRegistryFace | undefined }
206
+ readonly log: (message: string) => void
207
+ /** Coalescing window; the default is {@link JOBS_FLUSH_MS}. */
208
+ readonly flushMs?: number
209
+ }
210
+
211
+ /**
212
+ * The bridge's background-job reads and change notifications.
213
+ *
214
+ * One instance is built per host mount and shared by every connection, because
215
+ * a job is a fact about the host, not about the device that asked. Scopes are
216
+ * reference-counted by their listeners: a scope nobody watches holds no timer,
217
+ * and the registry subscription itself exists only while at least one scope
218
+ * does. That is what makes "a connection that never asked receives nothing"
219
+ * structural rather than a filter someone has to remember to apply.
220
+ */
221
+ export class JobRoster {
222
+ readonly #options: JobRosterOptions
223
+ readonly #flushMs: number
224
+ readonly #watches = new Map<string, ScopeWatch>()
225
+ #unsubscribe: (() => void) | undefined
226
+ #disposed = false
227
+
228
+ constructor(options: JobRosterOptions) {
229
+ this.#options = options
230
+ this.#flushMs = options.flushMs ?? JOBS_FLUSH_MS
231
+ }
232
+
233
+ /** @returns whether this host composes a job registry at all. */
234
+ get available(): boolean {
235
+ return this.#face() !== undefined
236
+ }
237
+
238
+ /**
239
+ * Read one scope's visible set.
240
+ *
241
+ * Synchronous, because the host registry projects in memory: no stream is
242
+ * opened and no socket is waited on, which is what makes this cheap enough to
243
+ * answer on request and again after every coalesced burst.
244
+ * @param sessionId - the scope's session; omitted for the unowned scope.
245
+ * @returns the payload, or undefined when this host has no job registry.
246
+ */
247
+ read(sessionId?: string): JobsPayload | undefined {
248
+ const face = this.#face()
249
+ if (face === undefined) return undefined
250
+ try {
251
+ const jobs = face.list(sessionId)
252
+ return {
253
+ ...(sessionId === undefined ? {} : { sessionId }),
254
+ scope: sessionId === undefined ? 'unowned' : 'session',
255
+ jobs: projectJobs(Array.isArray(jobs) ? jobs : []),
256
+ }
257
+ } catch (error) {
258
+ // The registry is in-process and synchronous, so a throw is a defect in it
259
+ // rather than a transient outage. It still must not fail the method for
260
+ // every other scope: an unreadable set is answered as an empty one below,
261
+ // and the read is retried on the next call.
262
+ this.#options.log(`the background job roster could not be read: ${failureText(error)}`)
263
+ return undefined
264
+ }
265
+ }
266
+
267
+ /**
268
+ * Watch one scope, and publish each coalesced change to every watcher of it.
269
+ *
270
+ * Watching is what a `jobs.list` call earns: a scope nobody listed is never
271
+ * read again, so a phone that declared the capability and asked for nothing
272
+ * receives no `jobs.changed` — the requirement that keeps N open sessions
273
+ * from becoming N sets streaming at a phone that asked for none.
274
+ * @param sessionId - the scope's session; omitted for the unowned scope.
275
+ * @param listener - receives one whole-set payload per coalesced change.
276
+ * @returns the disposer, or undefined when this host has no job registry.
277
+ */
278
+ watch(sessionId: string | undefined, listener: (payload: JobsPayload) => void): (() => void) | undefined {
279
+ if (this.#disposed || this.#face() === undefined) return undefined
280
+ const key = scopeKey(sessionId)
281
+ let watch = this.#watches.get(key)
282
+ if (watch === undefined) {
283
+ watch = { sessionId, key, listeners: new Set(), timer: undefined }
284
+ this.#watches.set(key, watch)
285
+ }
286
+ watch.listeners.add(listener)
287
+ this.#subscribe()
288
+ return () => { this.#unwatch(watch, listener) }
289
+ }
290
+
291
+ /** Stop every watch and clear every timer. Idempotent. */
292
+ dispose(): void {
293
+ if (this.#disposed) return
294
+ this.#disposed = true
295
+ for (const watch of this.#watches.values()) {
296
+ if (watch.timer !== undefined) clearTimeout(watch.timer)
297
+ watch.timer = undefined
298
+ }
299
+ this.#watches.clear()
300
+ this.#unsubscribe?.()
301
+ this.#unsubscribe = undefined
302
+ }
303
+
304
+ /** Resolve the host registry now, or undefined when this host mounts none. */
305
+ #face(): JobRegistryFace | undefined {
306
+ if (this.#disposed) return undefined
307
+ try {
308
+ return this.#options.faces().jobs
309
+ } catch (error) {
310
+ this.#options.log(`the background job registry could not be resolved: ${failureText(error)}`)
311
+ return undefined
312
+ }
313
+ }
314
+
315
+ /** Subscribe to the registry's event stream once, while any scope is watched. */
316
+ #subscribe(): void {
317
+ if (this.#unsubscribe !== undefined) return
318
+ const face = this.#face()
319
+ if (face === undefined) return
320
+ try {
321
+ // `all` on purpose: the bridge serves every session of this host, and a
322
+ // scope filter here would silently hide another preset's jobs from a
323
+ // phone that is allowed to read them through `list()`.
324
+ this.#unsubscribe = face.events.subscribe({ owners: 'all' }, (event) => { this.#onEvent(event) })
325
+ } catch (error) {
326
+ this.#options.log(`the background job event stream could not be subscribed: ${failureText(error)}`)
327
+ }
328
+ }
329
+
330
+ /** Route one registry event to the scopes it can change. */
331
+ #onEvent(event: JobEventLike): void {
332
+ // An output append moves no row. Dropping it here is the reason this channel
333
+ // can never degrade into one frame per byte of job output.
334
+ if (event.type === 'output') return
335
+ const owner = event.job?.owner ?? event.owner
336
+ for (const watch of this.#watches.values()) {
337
+ if (inScope(owner, watch.sessionId)) this.#schedule(watch)
338
+ }
339
+ }
340
+
341
+ /** Arm one scope's coalescing window; a burst inside it publishes once. */
342
+ #schedule(watch: ScopeWatch): void {
343
+ if (watch.timer !== undefined) return
344
+ const timer = setTimeout(() => {
345
+ watch.timer = undefined
346
+ this.#publish(watch)
347
+ }, this.#flushMs)
348
+ timer.unref?.()
349
+ watch.timer = timer
350
+ }
351
+
352
+ /** Read one scope again and hand its whole set to every watcher. */
353
+ #publish(watch: ScopeWatch): void {
354
+ if (this.#disposed || this.#watches.get(watch.key) !== watch) return
355
+ const payload = this.read(watch.sessionId)
356
+ if (payload === undefined) return
357
+ for (const listener of watch.listeners) listener(payload)
358
+ }
359
+
360
+ /** Drop one listener, and its scope with it when it was the last. */
361
+ #unwatch(watch: ScopeWatch, listener: (payload: JobsPayload) => void): void {
362
+ if (this.#watches.get(watch.key) !== watch) return
363
+ watch.listeners.delete(listener)
364
+ if (watch.listeners.size > 0) return
365
+ if (watch.timer !== undefined) clearTimeout(watch.timer)
366
+ watch.timer = undefined
367
+ this.#watches.delete(watch.key)
368
+ if (this.#watches.size > 0) return
369
+ this.#unsubscribe?.()
370
+ this.#unsubscribe = undefined
371
+ }
372
+ }