@linxin666/dsh-remote-bridge 0.4.8 → 0.4.10

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 (72) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +75 -18
  3. package/README.zh.md +74 -18
  4. package/lib/client.js +783 -260
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +15849 -2913
  7. package/lib/types/client/PairEntry.d.ts +2 -2
  8. package/lib/types/client/PairPanel.d.ts +10 -2
  9. package/lib/types/client/UiPresentRow.d.ts +13 -0
  10. package/lib/types/client/icons.d.ts +5 -13
  11. package/lib/types/client/index.d.ts +4 -0
  12. package/lib/types/client/locales.d.ts +24 -15
  13. package/lib/types/client/semantic.d.ts +9 -5
  14. package/lib/types/client/toolview-slot.d.ts +68 -0
  15. package/lib/types/client/ui-card.d.ts +160 -0
  16. package/lib/types/core/commands.d.ts +59 -0
  17. package/lib/types/core/connection.d.ts +106 -0
  18. package/lib/types/core/devices.d.ts +102 -2
  19. package/lib/types/core/extension.d.ts +13 -0
  20. package/lib/types/core/hub.d.ts +129 -15
  21. package/lib/types/core/liveactivity.d.ts +324 -0
  22. package/lib/types/core/protocol.d.ts +328 -5
  23. package/lib/types/core/push.d.ts +186 -0
  24. package/lib/types/core/questions.d.ts +61 -9
  25. package/lib/types/core/session-meta.d.ts +55 -1
  26. package/lib/types/core/squads.d.ts +130 -0
  27. package/lib/types/core/turn-end-quiet.d.ts +135 -0
  28. package/lib/types/core/ui.d.ts +238 -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/host/apns.d.ts +151 -0
  32. package/lib/types/host/squads-ledger.d.ts +39 -0
  33. package/lib/types/host/squads.d.ts +77 -0
  34. package/lib/types/host/ui-tools.d.ts +80 -0
  35. package/lib/types/host/usage-stats.d.ts +75 -0
  36. package/lib/types/host/watchers.d.ts +95 -0
  37. package/lib/types/index.d.ts +47 -3
  38. package/package.json +15 -14
  39. package/src/client/PairEntry.tsx +58 -31
  40. package/src/client/PairPanel.tsx +181 -97
  41. package/src/client/UiPresentRow.tsx +149 -0
  42. package/src/client/icons.tsx +17 -60
  43. package/src/client/index.ts +11 -0
  44. package/src/client/locales.ts +36 -24
  45. package/src/client/panel.module.css +239 -186
  46. package/src/client/semantic.ts +10 -6
  47. package/src/client/toolview-slot.ts +84 -0
  48. package/src/client/ui-card.ts +368 -0
  49. package/src/client/ui-present.module.css +87 -0
  50. package/src/core/commands.ts +95 -0
  51. package/src/core/connection.ts +811 -12
  52. package/src/core/devices.ts +337 -5
  53. package/src/core/extension.ts +20 -0
  54. package/src/core/hub.ts +518 -43
  55. package/src/core/liveactivity.ts +833 -0
  56. package/src/core/protocol.ts +370 -5
  57. package/src/core/push.ts +385 -0
  58. package/src/core/questions.ts +81 -10
  59. package/src/core/session-meta.ts +73 -1
  60. package/src/core/squads.ts +345 -0
  61. package/src/core/turn-end-quiet.ts +388 -0
  62. package/src/core/ui.ts +398 -0
  63. package/src/core/usage-stats.ts +424 -0
  64. package/src/core/usage.ts +937 -0
  65. package/src/core/wire.ts +8 -0
  66. package/src/host/apns.ts +320 -0
  67. package/src/host/squads-ledger.ts +105 -0
  68. package/src/host/squads.ts +206 -0
  69. package/src/host/ui-tools.ts +233 -0
  70. package/src/host/usage-stats.ts +155 -0
  71. package/src/host/watchers.ts +296 -0
  72. package/src/index.ts +327 -10
@@ -0,0 +1,388 @@
1
+ /**
2
+ * When a finished turn may be announced: after the session it belongs to falls
3
+ * quiet, not when the frame arrives.
4
+ *
5
+ * A `turn/end` increment is a fact about one turn and nothing more. The work the
6
+ * user started with it may still be going: the child sessions it delegated to and
7
+ * the background jobs the host still holds under those sessions outlive the turn
8
+ * that started them. A phone told "turn finished" at the frame wakes on a session
9
+ * the roster still badges as running, reads a card that says ended while the work
10
+ * goes on, and is told again by a second turn end it never asked for. §28's
11
+ * notification and §29's card answer the same question — "is this session working
12
+ * right now" — and that question has one answer, the one the client already
13
+ * computes in `SessionRun`: the host's own `agentRunning` for the session, any
14
+ * descendant session still running, and any job the host attributes to either.
15
+ *
16
+ * So a turn end is registered here instead of sent, and sent once the host says
17
+ * the session is quiet. Three rules hold that together:
18
+ *
19
+ * - the answer comes from the host and nowhere else: one `session/list` read for
20
+ * the running flag and the parent chain, and the host's job registry for the
21
+ * jobs it attributes to a session. This module invents no timer-based guess and
22
+ * reads no client state, because a guess that says "quiet" is a lock screen
23
+ * saying the work finished when it did not;
24
+ * - nothing on the frame path waits: a registration stores five fields and arms a
25
+ * timer, so a follow stream still publishes its increment at the speed it did
26
+ * before;
27
+ * - the wait is bounded. At {@link TURN_END_QUIET_MAX_MS} the announcement goes
28
+ * out anyway and the line it logs names what was still going, because a
29
+ * notification that never arrives is the failure this channel exists to prevent.
30
+ * @module dsh-remote-bridge/core/turn-end-quiet
31
+ */
32
+
33
+ import { failureText } from './gateway-errors.ts'
34
+ import type { JobRoster } from './jobs.ts'
35
+ import type { LiveActivityNotifier } from './liveactivity.ts'
36
+ import { pushEventOfTurnEnd, type PushEvent, type PushNotifier } from './push.ts'
37
+ import { wireArgs, type BridgeGateway, type GatewayPeer } from './wire.ts'
38
+
39
+ /** Longest a registered turn end waits for its session to fall quiet, in milliseconds. */
40
+ export const TURN_END_QUIET_MAX_MS = 600_000
41
+
42
+ /**
43
+ * How long a held turn end waits before asking the host again, in milliseconds.
44
+ *
45
+ * A turn end usually finds its session already quiet — the host clears the flag
46
+ * as the turn finishes — so the first question is the one that matters, and five
47
+ * seconds is short enough that the notification a user waits for is not visibly
48
+ * late. The interval is also what bounds how many questions one held turn end can
49
+ * cost: at most one every five seconds, never more than one in flight.
50
+ */
51
+ export const TURN_END_QUIET_INTERVAL_MS = 5_000
52
+
53
+ /** The host's answer about the work one session still holds. */
54
+ export interface QuietAnswer {
55
+ /** Whether nothing under this session is still going. */
56
+ readonly quiet: boolean
57
+ /** What was still going when it was not, in one token for the log line. */
58
+ readonly busy?: string
59
+ }
60
+
61
+ /** Whether one session is quiet right now, as the host answers it. */
62
+ export type QuietProbe = (sessionId: string) => Promise<QuietAnswer>
63
+
64
+ export interface TurnEndQuietOptions {
65
+ /** The notification path of §28; absent is a bridge that sends no notification. */
66
+ readonly push?: PushNotifier
67
+ /** The card path of §29; absent for the same reason. */
68
+ readonly liveActivity?: LiveActivityNotifier
69
+ /**
70
+ * The host's own answer, asked off the frame path.
71
+ *
72
+ * Absent is a bridge assembled without one, which cannot tell a quiet session
73
+ * from a busy one and therefore reports at the frame rather than holding
74
+ * anything back.
75
+ */
76
+ readonly probe?: QuietProbe
77
+ readonly now?: () => number
78
+ readonly log?: (message: string) => void
79
+ /** The wait budget; the default is {@link TURN_END_QUIET_MAX_MS}, and a deployment moves it. */
80
+ readonly maxWaitMs?: number
81
+ /** The re-check interval; the default is {@link TURN_END_QUIET_INTERVAL_MS}. */
82
+ readonly intervalMs?: number
83
+ }
84
+
85
+ /** One turn end held until its session is quiet. */
86
+ interface Waiting {
87
+ readonly sessionId: string
88
+ /** §28's event, decided when the turn end was registered. */
89
+ event: PushEvent
90
+ /** The host's own reason, kept because §29 decides ended versus failed from it. */
91
+ reason: string
92
+ readonly registeredAt: number
93
+ readonly deadline: number
94
+ /** The question to the host that is armed, if one is. */
95
+ check: NodeJS.Timeout | undefined
96
+ /** The timer that announces at the deadline whatever the answer is then. */
97
+ expiry: NodeJS.Timeout | undefined
98
+ /** Why the last question answered "not quiet". */
99
+ busy: string | undefined
100
+ /** Set while a question is in flight, so one entry never has two out at once. */
101
+ asking: boolean
102
+ }
103
+
104
+ /**
105
+ * The bridge's outbound turn-end path: registration now, announcement when quiet.
106
+ *
107
+ * Deliberately inert when neither channel can send: {@link enabled} is false, no
108
+ * entry is stored and no timer is armed, so a bridge without an Apple signing key
109
+ * behaves — byte for byte, frame for frame — exactly as it did before this module
110
+ * existed, and no host call is ever made on its behalf.
111
+ */
112
+ export class TurnEndQuietGate {
113
+ readonly #options: TurnEndQuietOptions
114
+ readonly #now: () => number
115
+ readonly #log: (message: string) => void
116
+ /** Held turn ends by session id; one session has one thing to announce. */
117
+ readonly #waiting = new Map<string, Waiting>()
118
+ #disposed = false
119
+
120
+ constructor(options: TurnEndQuietOptions) {
121
+ this.#options = options
122
+ this.#now = options.now ?? (() => Date.now())
123
+ this.#log = options.log ?? (() => undefined)
124
+ }
125
+
126
+ /** @returns whether either channel can send, which is the only case a turn end is held at all. */
127
+ get enabled(): boolean {
128
+ if (this.#disposed) return false
129
+ return this.#options.push?.enabled === true || this.#options.liveActivity?.enabled === true
130
+ }
131
+
132
+ /** @returns how many turn ends are held right now. */
133
+ get held(): number {
134
+ return this.#waiting.size
135
+ }
136
+
137
+ /**
138
+ * Hold one finished turn until its session is quiet, then announce it.
139
+ *
140
+ * Returns at once and never awaits a host read: the caller is a follow stream
141
+ * that has already published its increment.
142
+ * @param sessionId - the session the turn belonged to.
143
+ * @param reason - the host's own reason for ending it.
144
+ */
145
+ noteTurnEnd(sessionId: string, reason: string): void {
146
+ if (!this.enabled) return
147
+ try {
148
+ this.#register(sessionId, reason)
149
+ } catch (error) {
150
+ this.#log(`turn-end for ${sessionId} could not be held: ${failureText(error)}`)
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Drop a held turn end because another turn is on.
156
+ *
157
+ * A caller reports this from the evidence it actually has — an increment for the
158
+ * session that is not a turn end — so a turn the bridge cannot see costs the user
159
+ * nothing: the held end is still announced, and the turn that is really running
160
+ * ends with its own report.
161
+ * @param sessionId - the session that started working again.
162
+ */
163
+ noteTurnStarted(sessionId: string): void {
164
+ if (this.#waiting.size === 0) return
165
+ const waiting = this.#waiting.get(sessionId)
166
+ if (waiting === undefined) return
167
+ this.#forget(waiting)
168
+ this.#log(`turn-end dropped session=${sessionId} reason=new-turn`)
169
+ }
170
+
171
+ /** Drop every held turn end and every timer. Idempotent. */
172
+ dispose(): void {
173
+ if (this.#disposed) return
174
+ this.#disposed = true
175
+ for (const waiting of [...this.#waiting.values()]) this.#forget(waiting)
176
+ this.#waiting.clear()
177
+ }
178
+
179
+ /** Store one registration, or fold it into the one already held for that session. */
180
+ #register(sessionId: string, reason: string): void {
181
+ const held = this.#waiting.get(sessionId)
182
+ if (held !== undefined) {
183
+ // One session has one thing to announce, so a second turn end replaces what
184
+ // will be said and keeps the deadline the first one registered: a session
185
+ // that keeps ending turns cannot postpone its own announcement for ever.
186
+ held.event = pushEventOfTurnEnd(reason)
187
+ held.reason = reason
188
+ this.#log(`turn-end registered session=${sessionId} event=${held.event} replaces=held`)
189
+ return
190
+ }
191
+ const now = this.#now()
192
+ const waiting: Waiting = {
193
+ sessionId,
194
+ event: pushEventOfTurnEnd(reason),
195
+ reason,
196
+ registeredAt: now,
197
+ deadline: now + Math.max(0, this.#options.maxWaitMs ?? TURN_END_QUIET_MAX_MS),
198
+ check: undefined,
199
+ expiry: undefined,
200
+ busy: undefined,
201
+ asking: false,
202
+ }
203
+ this.#waiting.set(sessionId, waiting)
204
+ if (this.#options.probe === undefined) {
205
+ this.#deliver(waiting)
206
+ return
207
+ }
208
+ this.#log(`turn-end registered session=${sessionId} event=${waiting.event}`)
209
+ const expiry = setTimeout(() => {
210
+ waiting.expiry = undefined
211
+ this.#deliver(waiting, waiting.busy ?? 'unanswered')
212
+ }, Math.max(0, waiting.deadline - now))
213
+ // A notification waiting on work it did not start must never keep the host
214
+ // process alive.
215
+ expiry.unref?.()
216
+ waiting.expiry = expiry
217
+ this.#arm(waiting)
218
+ }
219
+
220
+ /** Arm the next question to the host, unless the budget runs out first. */
221
+ #arm(waiting: Waiting): void {
222
+ if (this.#disposed || this.#waiting.get(waiting.sessionId) !== waiting) return
223
+ const remaining = waiting.deadline - this.#now()
224
+ // The expiry timer is what answers a budget that has run out, so no question
225
+ // is armed past it: two timers due in the same millisecond would otherwise
226
+ // turn into a zero-delay loop on a session that never falls quiet.
227
+ if (remaining <= 0) return
228
+ const interval = this.#options.intervalMs ?? TURN_END_QUIET_INTERVAL_MS
229
+ const timer = setTimeout(() => {
230
+ waiting.check = undefined
231
+ this.#check(waiting)
232
+ }, Math.max(0, Math.min(interval, remaining)))
233
+ timer.unref?.()
234
+ waiting.check = timer
235
+ }
236
+
237
+ /** Ask the host once whether a held entry's session is quiet. */
238
+ #check(waiting: Waiting): void {
239
+ if (this.#disposed || this.#waiting.get(waiting.sessionId) !== waiting) return
240
+ const probe = this.#options.probe
241
+ if (probe === undefined || waiting.asking) return
242
+ waiting.asking = true
243
+ void Promise.resolve()
244
+ .then(async () => await probe(waiting.sessionId))
245
+ .then((answer) => {
246
+ waiting.asking = false
247
+ if (this.#disposed || this.#waiting.get(waiting.sessionId) !== waiting) return
248
+ if (answer.quiet) {
249
+ this.#deliver(waiting)
250
+ return
251
+ }
252
+ // The reason is kept rather than logged here: a session that is busy for a
253
+ // minute would otherwise write twelve lines saying the same thing, and the
254
+ // one line worth reading is the one the announcement carries.
255
+ waiting.busy = answer.busy ?? 'unstated'
256
+ this.#arm(waiting)
257
+ })
258
+ .catch((error: unknown) => {
259
+ waiting.asking = false
260
+ if (this.#disposed || this.#waiting.get(waiting.sessionId) !== waiting) return
261
+ // An unreadable answer is one line and another try: the host may answer the
262
+ // next one, and the expiry timer bounds how long that can go on.
263
+ waiting.busy = 'unreadable'
264
+ this.#log(`turn-end quiet check failed session=${waiting.sessionId}: ${failureText(error)}`)
265
+ this.#arm(waiting)
266
+ })
267
+ }
268
+
269
+ /**
270
+ * Announce one held turn end and forget it.
271
+ *
272
+ * The rate windows are booked inside the two calls below, at this instant: what
273
+ * the channels admit is what they really send, never what was once registered.
274
+ * @param waiting - the entry to announce.
275
+ * @param stillBusy - what kept it waiting, when the budget ran out first.
276
+ */
277
+ #deliver(waiting: Waiting, stillBusy?: string): void {
278
+ this.#forget(waiting)
279
+ const sessionId = waiting.sessionId
280
+ const waited = this.#now() - waiting.registeredAt
281
+ this.#log(stillBusy === undefined
282
+ ? `turn-end quiet session=${sessionId} waited=${waited}ms event=${waiting.event}`
283
+ : `turn-end session=${sessionId} still-busy(${stillBusy}) waited=${waited}ms, announcing anyway`)
284
+ try {
285
+ this.#options.push?.notify(waiting.event, sessionId)
286
+ } catch (error) {
287
+ this.#log(`turn-end ${waiting.event} for ${sessionId} could not be sent: ${failureText(error)}`)
288
+ }
289
+ try {
290
+ // The reason comes from the registration, not from anything read now: §29's
291
+ // ended-versus-failed is a fact about how that turn ended.
292
+ this.#options.liveActivity?.noteTurnEnd(sessionId, waiting.reason)
293
+ } catch (error) {
294
+ this.#log(`turn-end card for ${sessionId} could not be ended: ${failureText(error)}`)
295
+ }
296
+ }
297
+
298
+ /** Drop one entry and both of its timers. */
299
+ #forget(waiting: Waiting): void {
300
+ if (waiting.check !== undefined) clearTimeout(waiting.check)
301
+ if (waiting.expiry !== undefined) clearTimeout(waiting.expiry)
302
+ waiting.check = undefined
303
+ waiting.expiry = undefined
304
+ if (this.#waiting.get(waiting.sessionId) === waiting) this.#waiting.delete(waiting.sessionId)
305
+ }
306
+ }
307
+
308
+ /** What {@link sessionQuietProbe} reads the host through. */
309
+ export interface SessionQuietProbeOptions {
310
+ /** The host's gateway, the same one every connection speaks through. */
311
+ readonly gateway: BridgeGateway
312
+ /** The in-process owner peer every call of this bridge speaks for. */
313
+ readonly peer: GatewayPeer
314
+ /** The host's job registry, read for the jobs it attributes to a session. */
315
+ readonly jobs: JobRoster
316
+ }
317
+
318
+ /**
319
+ * The host's answer to "is this session quiet", built from its own two facts.
320
+ *
321
+ * The session list is where the running flag and the parent chain come from, and
322
+ * the job registry is where a job's owner and status come from; neither is
323
+ * captured once, because both move while a held turn end waits. A read that cannot
324
+ * be made is thrown rather than answered as quiet: "the host did not answer" and
325
+ * "nothing is running" are different facts, and the caller retries the one and
326
+ * announces the other.
327
+ * @param options - the faces the answer is read through.
328
+ * @returns the probe the gate asks.
329
+ */
330
+ export function sessionQuietProbe(options: SessionQuietProbeOptions): QuietProbe {
331
+ return async (sessionId: string): Promise<QuietAnswer> => {
332
+ const value = await options.gateway.invoke({
333
+ namespace: 'session',
334
+ method: 'list',
335
+ args: wireArgs('session', 'list', {}),
336
+ peer: options.peer,
337
+ })
338
+ const items = typeof value === 'object' && value !== null ? (value as { items?: unknown }).items : undefined
339
+ if (!Array.isArray(items)) throw new Error('session/list returned no item table')
340
+ const running = new Set<string>()
341
+ const parents = new Map<string, string>()
342
+ for (const item of items) {
343
+ if (typeof item !== 'object' || item === null) continue
344
+ const row = item as { sessionId?: unknown; running?: unknown; parentSessionId?: unknown }
345
+ if (typeof row.sessionId !== 'string' || row.sessionId === '') continue
346
+ if (row.running === true) running.add(row.sessionId)
347
+ if (typeof row.parentSessionId === 'string' && row.parentSessionId !== '') parents.set(row.sessionId, row.parentSessionId)
348
+ }
349
+ // The host answers `running` for a session's own agent, so a parent reads idle
350
+ // while the work it started goes on: the parent chain is walked here, to any
351
+ // depth, and stops at an id it has already walked so a looping chain ends.
352
+ if (running.has(sessionId)) return { quiet: false, busy: 'session-running' }
353
+ for (const id of running) {
354
+ if (descendsFrom(id, sessionId, parents)) return { quiet: false, busy: `descendant-running(${id})` }
355
+ }
356
+ const family = new Set<string>([sessionId])
357
+ for (const id of parents.keys()) if (descendsFrom(id, sessionId, parents)) family.add(id)
358
+ for (const id of family) {
359
+ const roster = options.jobs.read(id)
360
+ // A host that composes no job registry holds no job this bridge can name,
361
+ // and a scope that cannot be read is not evidence of work either.
362
+ if (roster === undefined) continue
363
+ for (const job of roster.jobs) {
364
+ // Only the jobs the host names an owner for count: an unowned job is not a
365
+ // fact about this session, and spreading it over the roster would be a
366
+ // claim the payload does not support.
367
+ if (job.ownerSessionId === undefined || !family.has(job.ownerSessionId)) continue
368
+ // The host's own projection omits `finishedAt` while a job is live, which
369
+ // is what makes `stopping` count as work in progress and keeps a status
370
+ // this bridge has never heard of from being read as a finished one.
371
+ if (job.finishedAt === undefined) return { quiet: false, busy: `job-live(${job.id})` }
372
+ }
373
+ }
374
+ return { quiet: true }
375
+ }
376
+ }
377
+
378
+ /** @returns whether one session sits under another in the host's own parent chain. */
379
+ function descendsFrom(sessionId: string, ancestorId: string, parents: ReadonlyMap<string, string>): boolean {
380
+ const walked = new Set<string>([sessionId])
381
+ let cursor = parents.get(sessionId)
382
+ while (cursor !== undefined && !walked.has(cursor)) {
383
+ if (cursor === ancestorId) return true
384
+ walked.add(cursor)
385
+ cursor = parents.get(cursor)
386
+ }
387
+ return false
388
+ }