@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
package/src/core/hub.ts CHANGED
@@ -2,26 +2,38 @@
2
2
  * The bridge's process-wide connection registry and its claims on
3
3
  * `approval/request` and `user-questions/request`.
4
4
  *
5
- * The hub is what makes "phone not answering equals refusal" true: a question
6
- * is claimed only while at least one paired device is connected, the publish
7
- * has to actually reach someone, and every other path (timeout, agent
8
- * cancellation, the last phone leaving) delegates to the next answerer, which
9
- * the Host normalizes to `'unavailable'`.
5
+ * The hub is what makes "phone not answering equals refusal" true: an approval
6
+ * is claimed only while at least one paired device is connected, the publish has
7
+ * to actually reach someone, and every other path (timeout, agent cancellation,
8
+ * the last phone leaving) delegates to the next answerer, which the Host
9
+ * normalizes to `'unavailable'`.
10
10
  *
11
- * The claim on `user-questions/request` follows the same two rules, with two
11
+ * A user question adds the one case where "reach someone" is the notification
12
+ * rather than the socket: with no paired connection on the wire but a device on
13
+ * the roster that registered for pushes, the question is claimed for that phone
14
+ * and the alert is its delivery (§11.3, §32). One predicate decides it — "can a
15
+ * device that is reachable right now receive a question card" — and it is asked
16
+ * again every time a connection finishes its hello, because a client that never
17
+ * declares `questions.v1` going online turns that answer into no.
18
+ *
19
+ * The claim on `user-questions/request` follows the same rules, with three
12
20
  * differences that belong to the host's own semantics: delegating is not a
13
21
  * refusal, because only a phone that declares `questions.v1` is ever shown the
14
- * question; and a question is named on the wire even when the host named none,
22
+ * question; a question is named on the wire even when the host named none,
15
23
  * because a blocking ask carries no call id and the phone still needs a handle
16
- * to answer with.
24
+ * to answer with; and the claim outlives the last paired device by a grace
25
+ * window, because a phone whose app the system suspended has refused nothing.
17
26
  * @module dsh-remote-bridge/core/hub
18
27
  */
19
28
 
20
29
  import type { ApprovalOutcome } from '@deepseek-ai/dsh-user-approval'
30
+ import type { PendingPromptView } from './approvals.ts'
21
31
  import type { BridgeConnectionOptions, BridgeTransport, ConnectionAuth } from './connection.ts'
22
32
  import { BridgeConnection } from './connection.ts'
23
- import { CAP_QUESTIONS, TOPIC_APPROVAL_REQUEST, TOPIC_QUESTION_REQUEST } from './protocol.ts'
24
- import type { ClaimedQuestionView, QuestionAnswer, QuestionRequestPayload, QuestionState, UserQuestionRequestLike } from './questions.ts'
33
+ import { CAP_APPROVALS, CAP_QUESTIONS, TOPIC_APPROVAL_REQUEST, TOPIC_QUESTION_REQUEST } from './protocol.ts'
34
+ import { questionPayload } from './questions.ts'
35
+ import type { ClaimedQuestion, QuestionAnswer, UserQuestionRequestLike } from './questions.ts'
36
+ import { isDeadPushToken, type PushDeliveryReport } from './push.ts'
25
37
 
26
38
  /**
27
39
  * The fields of an approval question this bridge reads. Structural on purpose:
@@ -41,25 +53,103 @@ export function approvalSummary(request: ApprovalRequestLike): string {
41
53
  return request.displayReason?.zh ?? request.displayReason?.en ?? request.toolName
42
54
  }
43
55
 
56
+ /** The `approval.request` payload one claim is published with. */
57
+ export interface ApprovalRequestPayload {
58
+ readonly sessionId: string
59
+ readonly id: string
60
+ readonly summary: string
61
+ readonly toolName: string
62
+ }
63
+
44
64
  /**
45
- * The `question.request` payload for one claim.
65
+ * The `approval.request` payload for one claim.
46
66
  *
47
- * No `expiresAt`: the host's foreground deadline is not part of the request the
48
- * waterfall carries, and a bridge-invented deadline would be a timeout of the
49
- * bridge's own — the exact thing this channel must not have.
50
- * @param state - whether the foreground ask still holds the question.
51
- * @param question - the claim being published.
67
+ * The first broadcast and the replay of a still-open claim go through this one
68
+ * function, so the card a phone was originally shown and the same card handed to
69
+ * it again after a reconnect cannot drift apart.
70
+ * @param prompt - the claim being published.
52
71
  */
53
- function questionPayload(state: QuestionState, question: ClaimedQuestionView): QuestionRequestPayload {
54
- return { sessionId: question.sessionId, callId: question.callId, state, questions: question.questions }
72
+ function approvalPayload(prompt: PendingPromptView): ApprovalRequestPayload {
73
+ return { sessionId: prompt.sessionId, id: prompt.id, summary: prompt.summary, toolName: prompt.toolName }
74
+ }
75
+
76
+ /**
77
+ * How long a user question outlives the last paired device, in milliseconds.
78
+ *
79
+ * A push notification carries a session link and nothing else: the phone can
80
+ * draw a question card only while this bridge still holds the claim, and it has
81
+ * to reconnect before it can read one. A phone whose app was suspended is gone
82
+ * for tens of seconds, so releasing the claim the instant its socket drops
83
+ * decides the question for it — the ask went back to the host's own answerer
84
+ * chain, the Mac showed the card, and the tap that arrived afterwards opened a
85
+ * session with nothing in it (measured 2026-10-23). The window is that reconnect
86
+ * budget, not a second deadline: a claim no phone came back for is released on
87
+ * expiry exactly as it was before.
88
+ */
89
+ export const QUESTION_CLAIM_GRACE_MS = 60_000
90
+
91
+ /**
92
+ * How long a user question is held for a phone this bridge reached by
93
+ * notification only, in milliseconds (§32.2).
94
+ *
95
+ * Inside this window the question exists only on the phone's side: the alert is
96
+ * out, no socket has it, and the host's own answerer chain has not been started.
97
+ * When it runs out the claim is withdrawn and delegated, so the agent behind a
98
+ * timed ask waits at most this long past its own deadline and the agent behind a
99
+ * blocking ask (no call id, no deadline) waits at most this long in total — an
100
+ * accepted cost, because the alternative is a question that vanished while the
101
+ * phone was asleep. The window is the bridge's own constant and not the host's:
102
+ * a deployment overrides it, the host never sees it.
103
+ */
104
+ export const OFFLINE_QUESTION_CLAIM_TTL_MS = 600_000
105
+
106
+ // Those two windows are different timers and never one. QUESTION_CLAIM_GRACE_MS
107
+ // is a grace on the way OUT: a phone was on the wire, it left, and the window is
108
+ // that phone's reconnect budget before the held claim is delegated.
109
+ // OFFLINE_QUESTION_CLAIM_TTL_MS is the whole lifetime of a claim that never had a
110
+ // phone on the wire at all. One claim can be covered by both in turn — claimed for
111
+ // the absent phone, handed to the phone that then declared the channel, left by
112
+ // that phone again — and whichever is due first releases it. The release is
113
+ // idempotent (the claim is deleted before it is delegated and the chain it starts
114
+ // is memoized), so the later timer finds no claim and the host's own answerer is
115
+ // started at most once.
116
+
117
+ /** Which path a user question takes right now (§11.3). */
118
+ type QuestionMode = 'online' | 'offline' | 'nobody'
119
+
120
+ /** What the hub is built with: the bridge's shared options plus the windows it owns. */
121
+ export interface BridgeHubOptions extends BridgeConnectionOptions {
122
+ /**
123
+ * The offline claim window, in milliseconds.
124
+ *
125
+ * Defaults to {@link OFFLINE_QUESTION_CLAIM_TTL_MS}; a deployment knob, and the
126
+ * seam a suite uses to move the window instead of waiting it out.
127
+ */
128
+ readonly offlineClaimTtlMs?: number
55
129
  }
56
130
 
57
131
  /** The bridge's live connections plus the answerer it composes onto the approval chain. */
58
132
  export class BridgeHub {
59
- readonly #options: BridgeConnectionOptions
133
+ readonly #options: BridgeHubOptions
60
134
  readonly #connections = new Set<BridgeConnection>()
135
+ /**
136
+ * The release this hub has scheduled for the user questions no paired device
137
+ * can answer any more. The claim table is global, so one timer covers every
138
+ * claim and there is never more than one of them.
139
+ */
140
+ #questionReleaseTimer: NodeJS.Timeout | undefined
141
+ /**
142
+ * The offline claims still waiting on a phone, by wire call id, each with the
143
+ * timer that holds it for its window.
144
+ *
145
+ * A question leaves this table the moment the phone takes it over, answers it,
146
+ * or the window releases it, so a call id in here is a question no reachable
147
+ * device has been shown — which is exactly what {@link #reviewOfflineClaims}
148
+ * withdraws when a hello makes that permanent.
149
+ */
150
+ readonly #offlineClaims = new Map<string, NodeJS.Timeout>()
61
151
 
62
- constructor(options: BridgeConnectionOptions) {
152
+ constructor(options: BridgeHubOptions) {
63
153
  this.#options = options
64
154
  }
65
155
 
@@ -78,14 +168,25 @@ export class BridgeHub {
78
168
  attach(transport: BridgeTransport, auth?: ConnectionAuth): BridgeConnection {
79
169
  // The replay hook is wired here rather than by the caller: a phone that
80
170
  // reconnects mid-question was not there for the broadcast, and every
81
- // construction path has to hand it the live claims.
171
+ // construction path has to hand it the live claims — the approval ones and
172
+ // the user-question ones alike.
82
173
  const connection = new BridgeConnection(
83
- { ...this.#options, onDeclare: (fresh) => { this.replayQuestions(fresh) } },
174
+ {
175
+ ...this.#options,
176
+ onDeclare: (fresh) => {
177
+ this.replayQuestions(fresh)
178
+ this.replayApprovals(fresh)
179
+ this.#reviewOfflineClaims()
180
+ },
181
+ },
84
182
  transport,
85
183
  auth,
86
184
  )
87
185
  this.#connections.add(connection)
88
186
  connection.startHeartbeat()
187
+ // A paired device is the phone the window was being held open for: it is
188
+ // here now, so the release it was waiting out is no longer due.
189
+ if (connection.paired) this.#cancelQuestionRelease()
89
190
  if (auth !== undefined) void this.#options.roster.touch(auth.deviceId).catch(() => undefined)
90
191
  this.#options.log(`connection open (${auth === undefined ? 'unpaired' : `device ${auth.deviceId}`})`)
91
192
  return connection
@@ -93,18 +194,20 @@ export class BridgeHub {
93
194
 
94
195
  /**
95
196
  * Forget one connection and abort everything it owns. When it was the last
96
- * paired device, every pending question is withdrawn: nobody left can answer.
197
+ * paired device, every pending approval is withdrawn at once and every pending
198
+ * user question is released when its grace window ends.
97
199
  */
98
200
  detach(connection: BridgeConnection): void {
99
201
  this.#connections.delete(connection)
100
202
  connection.dispose()
101
203
  if (this.pairedClients > 0) return
102
- const withdrawn = this.#options.approvals.abandonAll()
103
- if (withdrawn > 0) this.#options.log(`${withdrawn} approval question(s) withdrew: no paired device is connected`)
104
- // A user question is delegated rather than refused: the next answerer in the
105
- // host's chain decides, and the question's own deadline still holds.
106
- const released = this.#options.questions.withdrawAll()
107
- if (released > 0) this.#options.log(`${released} user question(s) released: no paired device is connected`)
204
+ // An approval takes no window: the tool behind it is the agent's own wait,
205
+ // and a card no connected phone can answer must not hold it a second longer.
206
+ this.#abandonApprovals()
207
+ // A user question is delegated rather than refused, so the next answerer in
208
+ // the host's chain decides and the question's own deadline still holds — but
209
+ // only once the window in which the phone can come back for it has run out.
210
+ if (this.#options.questions.size > 0) this.#armQuestionRelease()
108
211
  }
109
212
 
110
213
  /**
@@ -120,10 +223,6 @@ export class BridgeHub {
120
223
  return delivered
121
224
  }
122
225
 
123
- /**
124
- * Publish one event to every paired device that announced a capability.
125
- * @returns how many connections actually took the frame.
126
- */
127
226
  /**
128
227
  * Hand one freshly declared connection the questions it can now answer.
129
228
  *
@@ -133,11 +232,47 @@ export class BridgeHub {
133
232
  */
134
233
  replayQuestions(connection: BridgeConnection): void {
135
234
  if (!connection.paired || !connection.declares(CAP_QUESTIONS)) return
136
- for (const claim of this.#options.questions.openClaims()) {
137
- connection.emit(TOPIC_QUESTION_REQUEST, questionPayload('open', claim))
235
+ // A phone that can take a card is on the wire: the windows that held these
236
+ // claims for nobody are over. The claims themselves are handed over below
237
+ // rather than released — they are this phone's to answer now.
238
+ this.#cancelOfflineClaims()
239
+ // The claim's own state, not `open` for every claim: a question whose
240
+ // foreground wait the host already ended is `continued`, and replaying it as
241
+ // open tells the phone to wait on an agent that has already moved on. The
242
+ // held set is read the way `question.list` publishes it, so the replayed card
243
+ // and the row the phone reads back stay one shape.
244
+ for (const held of this.#options.questions.listed()) {
245
+ connection.emit(TOPIC_QUESTION_REQUEST, held.payload)
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Hand one freshly declared connection the approvals it can now answer.
251
+ *
252
+ * The same shape as {@link replayQuestions} and for the same reason: the first
253
+ * `approval.request` of a question was broadcast to the phones that were
254
+ * connected at that instant, so a phone that reconnected — or a session screen
255
+ * opened after the fact — holds no card and has no other way to learn the
256
+ * question exists. Only unsettled questions are in the registry, so one that
257
+ * was answered, one the bridge timed out and one withdrawn with the last phone
258
+ * cannot be replayed.
259
+ *
260
+ * The replay emits a frame and nothing else: the claim keeps the deadline it
261
+ * was opened with, so re-handing a question never lengthens how long the agent
262
+ * waits for it.
263
+ * @param connection - the connection that just declared its capabilities.
264
+ */
265
+ replayApprovals(connection: BridgeConnection): void {
266
+ if (!connection.paired || !connection.declares(CAP_APPROVALS)) return
267
+ for (const prompt of this.#options.approvals.openPrompts()) {
268
+ connection.emit(TOPIC_APPROVAL_REQUEST, approvalPayload(prompt))
138
269
  }
139
270
  }
140
271
 
272
+ /**
273
+ * Publish one event to every paired device that announced a capability.
274
+ * @returns how many connections actually took the frame.
275
+ */
141
276
  broadcastTo(capability: string, topic: string, payload: unknown): number {
142
277
  let delivered = 0
143
278
  for (const connection of this.#connections) {
@@ -162,15 +297,19 @@ export class BridgeHub {
162
297
  summary: approvalSummary(request),
163
298
  ...(request.signal === undefined ? {} : { signal: request.signal }),
164
299
  })
165
- const delivered = this.broadcast(TOPIC_APPROVAL_REQUEST, {
166
- sessionId,
167
- id: prompt.id,
168
- summary: prompt.summary,
169
- toolName: request.toolName,
170
- })
300
+ const delivered = this.broadcast(TOPIC_APPROVAL_REQUEST, approvalPayload(prompt))
171
301
  // A question nobody could receive is withdrawn immediately instead of
172
302
  // waiting out the phone's timeout with the agent blocked on it.
173
303
  if (delivered === 0) this.#options.approvals.abandon([prompt.id])
304
+ // Only a claim that reached someone is worth a notification: the question a
305
+ // withdrawn claim stood for can no longer be answered by any phone, and a
306
+ // notification about it would be a card with nothing behind it (§28.5).
307
+ else {
308
+ this.#options.push?.notify('approval', sessionId)
309
+ // The card is not a second answerer: it only says a tool is blocked, with
310
+ // the fixed line and none of the tool's own reason text (§29).
311
+ this.#options.liveActivity?.noteApproval(sessionId)
312
+ }
174
313
  const answer = await prompt.answer
175
314
  return answer === undefined ? await next() : answer
176
315
  }
@@ -178,13 +317,17 @@ export class BridgeHub {
178
317
  /**
179
318
  * The body of this plugin's `user-questions/request` listener.
180
319
  *
181
- * Claimed only while a paired device is connected and the ask names an agent:
182
- * the payload has no session field of its own, and a question nobody can be
183
- * told about is not one this bridge may hold. The wire id is the host's own
184
- * when the ask is timed, and minted here when it is blocking and the host
185
- * assigned none — either way the phone answers the id it was shown. A claim
320
+ * Claimed only while a device that is reachable right now can be shown the
321
+ * card: a paired connection that declared `questions.v1`, or — with no phone on
322
+ * the wire — a roster device that registered for notifications, which the alert
323
+ * reaches instead of a frame (§11.3, §32). The payload has no session field of
324
+ * its own, so an ask that names no agent is delegated either. The wire id is the
325
+ * host's own when the ask is timed, and minted here when it is blocking and the
326
+ * host assigned none — either way the phone answers the id it was shown. A claim
186
327
  * nobody received is withdrawn at once instead of holding the agent until the
187
- * host's deadline.
328
+ * host's deadline. For a timed ask the host's own remaining wait travels with
329
+ * the first frame as `expiresAt`, and every later move of that deadline is
330
+ * re-published under the same call id.
188
331
  * @param request - the pending question batch.
189
332
  * @param next - the rest of the answerer chain.
190
333
  * @returns the phone's answer, the host's own deadline outcome, or whatever the next answerer says.
@@ -192,7 +335,14 @@ export class BridgeHub {
192
335
  async question(request: UserQuestionRequestLike, next: () => Promise<QuestionAnswer>): Promise<QuestionAnswer> {
193
336
  const sessionId = request.agent?.id
194
337
  if (sessionId === undefined) return await next()
195
- if (this.pairedClients === 0) return await next()
338
+ // With no phone on the wire the roster decides, and reading it is the file the
339
+ // mount already loaded: awaiting the memoized load keeps the first question of
340
+ // a process from being delegated only because that read had not finished.
341
+ if (this.pairedClients === 0) await this.#options.roster.load()
342
+ const mode = this.#questionMode()
343
+ // Nobody reachable can be shown this question: it belongs to the next answerer,
344
+ // exactly as it did before the offline window existed.
345
+ if (mode === 'nobody') return await next()
196
346
  // A blocking ask carries no `wait`: the host has no call id for it, but the
197
347
  // phone needs a handle to answer with, so one is minted in this bridge's own
198
348
  // namespace. Resolving the promise held here needs no host identity.
@@ -209,25 +359,66 @@ export class BridgeHub {
209
359
  // The phone's card has to go when the desktop answered it, or the phone
210
360
  // keeps offering a question that no longer exists.
211
361
  this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload('settled', question))
362
+ // The lock-screen card says the same thing: a card still asking for an
363
+ // answer nobody owes any more is the one state it must never show.
364
+ this.#options.liveActivity?.noteSettled(sessionId)
212
365
  },
213
366
  onContinued: (question): void => {
214
367
  // The foreground wait ended, but the question is still answerable: the
215
368
  // phone is told which state it is in instead of losing the question.
216
369
  this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload('continued', question))
217
370
  },
371
+ onDeadline: (question): void => {
372
+ // The host moved its deadline. Re-publishing the open state under the same
373
+ // call id updates the card the phone already holds instead of opening a
374
+ // second one.
375
+ this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload('open', question))
376
+ },
218
377
  })
219
378
  if (claim === undefined) return await next()
220
- const delivered = this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload('open', claim))
379
+ if (mode === 'offline') return await this.#holdOfflineClaim(sessionId, callId, claim)
380
+ // The host's own first wait frame is folded into this same frame: a phone is
381
+ // handed the question and how long it has together, rather than a card that a
382
+ // second update then races. A claim with no frame publishes no deadline,
383
+ // which is exactly the payload from before this channel existed.
384
+ const expiresAt = await claim.deadline
385
+ // The host's own lifetime can end while the first wait frame is still being
386
+ // awaited — its signal aborts, so the claim is expired or already continued.
387
+ // Publishing now would hand the phone a card nobody can retract, so that case
388
+ // goes straight to the claim's own outcome: the host's reason, or its answer.
389
+ if (this.#options.questions.stateOf(callId) !== 'open') return await claim.answer
390
+ const delivered = this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload('open', expiresAt === undefined ? claim : { ...claim, expiresAt }))
221
391
  // A client that cannot receive this is not going to receive it later: the claim
222
392
  // must not be left holding the host's ask with no card anywhere. A client that
223
393
  // *can* receive it but was reconnecting is a different case — it is handed the
224
394
  // live claims by `onDeclare` when it comes back.
225
395
  if (delivered === 0) this.#options.questions.withdraw([callId])
396
+ // Same rule as the approval above: a question this bridge could not hand to
397
+ // a connected phone is withdrawn at once, so a notification would announce
398
+ // something already gone.
399
+ else {
400
+ this.#options.push?.notify('question', sessionId)
401
+ // Only the first question's header and at most two option labels reach that
402
+ // session's card: they are the choices the App can offer (§29.7: the card has
403
+ // no controls of its own). The questions themselves stay on the wire, exactly
404
+ // as the alert channel keeps them out of its body.
405
+ const first = request.questions[0]
406
+ this.#options.liveActivity?.noteQuestion(sessionId, {
407
+ ...(first?.header === undefined ? {} : { header: first.header }),
408
+ ...(first?.options === undefined ? {} : { optionLabels: first.options.map(option => option.label) }),
409
+ })
410
+ }
226
411
  return await claim.answer
227
412
  }
228
413
 
229
414
  /** Close every connection and withdraw every question. Idempotent. */
230
415
  dispose(): void {
416
+ // Unloading is not a phone going away: nothing can come back for these
417
+ // claims, so every window is dropped and the release happens right here — the
418
+ // offline ones through their own entry, so this route also starts the host's
419
+ // chain at most once.
420
+ this.#releaseOfflineClaims('the bridge unloaded')
421
+ this.#cancelQuestionRelease()
231
422
  for (const connection of [...this.#connections]) {
232
423
  this.#connections.delete(connection)
233
424
  connection.dispose()
@@ -235,4 +426,205 @@ export class BridgeHub {
235
426
  this.#options.approvals.abandonAll()
236
427
  this.#options.questions.withdrawAll()
237
428
  }
429
+
430
+ /**
431
+ * Arm the one release of the user questions no paired device can answer.
432
+ *
433
+ * A second departure while a window is already running must not extend it, so
434
+ * an armed timer is left alone: every claim it covers is released at the one
435
+ * instant it was scheduled for.
436
+ */
437
+ #armQuestionRelease(): void {
438
+ if (this.#questionReleaseTimer !== undefined) return
439
+ const timer = setTimeout(() => {
440
+ this.#questionReleaseTimer = undefined
441
+ // Exactly what an immediate release does, approvals included: whatever is
442
+ // still held when nobody is paired goes back to the host's own answerers.
443
+ this.#abandonApprovals()
444
+ this.#releaseQuestions()
445
+ }, QUESTION_CLAIM_GRACE_MS)
446
+ // A held question must never keep the host process alive, exactly like the
447
+ // deadline timer one claim arms.
448
+ timer.unref?.()
449
+ this.#questionReleaseTimer = timer
450
+ }
451
+
452
+ /** Drop the pending window, if there is one. The claims it would release stay held. */
453
+ #cancelQuestionRelease(): void {
454
+ if (this.#questionReleaseTimer === undefined) return
455
+ clearTimeout(this.#questionReleaseTimer)
456
+ this.#questionReleaseTimer = undefined
457
+ }
458
+
459
+ /**
460
+ * Which path a user question takes right now (§11.3).
461
+ *
462
+ * The one entry, read twice: when a question arrives, and again when a paired
463
+ * connection finishes its hello while an offline claim is still held. Both
464
+ * moments ask the same thing — can a device that is reachable right now receive
465
+ * a question card — and answering it in two places is how two answers drift
466
+ * apart.
467
+ * @returns `online` for the ordinary claim-and-broadcast path, `offline` for a
468
+ * claim held for a phone reached by notification, and `nobody` when the question
469
+ * has to go straight to the next answerer.
470
+ */
471
+ #questionMode(): QuestionMode {
472
+ for (const connection of this.#connections) {
473
+ if (connection.paired && connection.declares(CAP_QUESTIONS)) return 'online'
474
+ }
475
+ // A paired connection is on the wire and none of them declared the channel: no
476
+ // one can be shown a card, and a claim held for the phone that was never there
477
+ // would make the agent wait out a window for a decision nobody can give.
478
+ if (this.pairedClients > 0) return 'nobody'
479
+ // No key, no sender: an alert that cannot be sent is not a delivery, so the
480
+ // question is not claimed for a phone that would never learn it exists.
481
+ if (this.#options.push?.enabled !== true) return 'nobody'
482
+ return this.#options.roster.pushTargets().length > 0 ? 'offline' : 'nobody'
483
+ }
484
+
485
+ /**
486
+ * Hold one question for a phone that is not on the wire (§32).
487
+ *
488
+ * No socket is paired, so this claim's own first frame would reach nobody: the
489
+ * notification IS its delivery, and it is sent whether or not a broadcast would
490
+ * have landed. Inside the window the question exists only on the phone's side;
491
+ * the phone that comes back is handed the card by the replay in `onDeclare`,
492
+ * and the phone that answers settles it through the ordinary path.
493
+ * @param sessionId - the session that asked.
494
+ * @param callId - the wire id the phone will answer under.
495
+ * @param claim - the claim this bridge just opened.
496
+ * @returns the phone's answer, or whatever the next answerer says.
497
+ */
498
+ async #holdOfflineClaim(sessionId: string, callId: string, claim: ClaimedQuestion): Promise<QuestionAnswer> {
499
+ this.#armOfflineClaim(callId)
500
+ // The report is the only way this bridge learns that the phone it claimed for
501
+ // is gone for good: a frame would have carried that fact, an alert does not.
502
+ this.#options.push?.notify('question', sessionId, (report) => { this.#onQuestionPushed(callId, report) })
503
+ try {
504
+ return await claim.answer
505
+ } finally {
506
+ // Every path that ends this claim — answered, delegated, expired by the host
507
+ // — drops its window here, so no timer outlives the question it was armed for.
508
+ this.#cancelOfflineClaim(callId)
509
+ }
510
+ }
511
+
512
+ /**
513
+ * Read one alert's delivery report (§32.5).
514
+ *
515
+ * Three APNs answers are final about a registration: 410 with `Unregistered`, or
516
+ * `Unregistered`/`BadDeviceToken` on any status. The device is cleaned off the
517
+ * roster, and the claim is kept only while some other registered device is still
518
+ * there to be told; when the last one is gone the question cannot reach a phone
519
+ * at all, so it goes back to the host's chain now instead of at the end of a
520
+ * window nobody is left to use.
521
+ * @param callId - the offline claim this notification was about.
522
+ * @param report - how the announcement ended.
523
+ */
524
+ #onQuestionPushed(callId: string, report: PushDeliveryReport): void {
525
+ const dead = report.failures.filter(failure => isDeadPushToken(failure)).map(failure => failure.deviceToken)
526
+ if (dead.length === 0) return
527
+ // The roster still lists these rows — the cleanup is a file write — so they are
528
+ // subtracted here rather than waited out: a claim decision may not block on a disk.
529
+ const survivors = this.#options.roster.pushTargets().filter(({ push }) => !dead.includes(push.deviceToken))
530
+ void this.#forgetDeadTokens(dead)
531
+ if (survivors.length > 0) return
532
+ this.#releaseOfflineClaim(callId, 'APNs refused every device token on the roster')
533
+ }
534
+
535
+ /** Drop each dead registration from the roster, then let the watchers settle. */
536
+ async #forgetDeadTokens(tokens: readonly string[]): Promise<void> {
537
+ try {
538
+ let dropped = false
539
+ for (const token of tokens) dropped = (await this.#options.roster.removePush(token)) || dropped
540
+ // A row that lost the card tokens of its install may have lost its last
541
+ // watcher with them, and a watcher is a follow stream this bridge keeps open.
542
+ if (dropped) this.#options.onPushRegistered?.()
543
+ } catch (error) {
544
+ this.#options.log(`a dead push registration could not be cleaned up: ${String(error)}`)
545
+ }
546
+ }
547
+
548
+ /**
549
+ * End every offline claim the wire has just made unreachable (§11.3).
550
+ *
551
+ * A hello that leaves no paired connection able to take a card — the client
552
+ * written before `questions.v1` going online — is the same fact the claim point
553
+ * reads, so it releases the claim at once instead of at the end of its window.
554
+ */
555
+ #reviewOfflineClaims(): void {
556
+ if (this.#offlineClaims.size === 0) return
557
+ if (this.#questionMode() === 'offline') return
558
+ this.#releaseOfflineClaims('no paired connection on the wire can receive a question')
559
+ }
560
+
561
+ /**
562
+ * Arm the window that holds one offline claim.
563
+ *
564
+ * Deliberately a second timer beside {@link #armQuestionRelease}, never the same
565
+ * one: that window is the reconnect budget of a phone that just left, this one is
566
+ * the whole lifetime of a claim no phone ever had, and one claim can be governed
567
+ * by both in turn. Whichever is due first releases it, and the release is
568
+ * idempotent, so the later one finds no claim.
569
+ * @param callId - the claim to hold.
570
+ */
571
+ #armOfflineClaim(callId: string): void {
572
+ if (this.#offlineClaims.has(callId)) return
573
+ const ttl = this.#options.offlineClaimTtlMs ?? OFFLINE_QUESTION_CLAIM_TTL_MS
574
+ const timer = setTimeout(() => {
575
+ this.#releaseOfflineClaim(callId, 'the offline claim window ended')
576
+ }, Math.max(0, ttl))
577
+ // A question held for a phone must never keep the host process alive.
578
+ timer.unref?.()
579
+ this.#offlineClaims.set(callId, timer)
580
+ }
581
+
582
+ /** Drop one claim's window. The claim itself keeps whatever state it has. */
583
+ #cancelOfflineClaim(callId: string): void {
584
+ const timer = this.#offlineClaims.get(callId)
585
+ if (timer === undefined) return
586
+ clearTimeout(timer)
587
+ this.#offlineClaims.delete(callId)
588
+ }
589
+
590
+ /** Drop every offline window: a phone is on the wire for those claims now, or they are about to be released. */
591
+ #cancelOfflineClaims(): void {
592
+ for (const timer of this.#offlineClaims.values()) clearTimeout(timer)
593
+ this.#offlineClaims.clear()
594
+ }
595
+
596
+ /**
597
+ * Release one offline claim back to the host's own chain.
598
+ *
599
+ * The one entry every route uses — the window ending, a roster whose tokens are
600
+ * all dead, a hello that left nobody able to receive, the bridge unloading — so
601
+ * "the host's chain is started at most once" is a property of this entry rather
602
+ * than of its callers: `withdraw` deletes the claim before it delegates, and the
603
+ * chain a claim starts is memoized, so a second route releases nothing and starts
604
+ * nothing, and no notification is sent for a question that already left.
605
+ * @param callId - the claim to release.
606
+ * @param reason - why, logged once when something really was released.
607
+ */
608
+ #releaseOfflineClaim(callId: string, reason: string): void {
609
+ this.#cancelOfflineClaim(callId)
610
+ const released = this.#options.questions.withdraw([callId])
611
+ if (released > 0) this.#options.log(`an offline-claimed user question was released: ${reason}`)
612
+ }
613
+
614
+ /** Release every offline claim through {@link #releaseOfflineClaim}. */
615
+ #releaseOfflineClaims(reason: string): void {
616
+ for (const callId of [...this.#offlineClaims.keys()]) this.#releaseOfflineClaim(callId, reason)
617
+ }
618
+
619
+ /** Abandon every approval: no paired device is left to answer one. */
620
+ #abandonApprovals(): void {
621
+ const withdrawn = this.#options.approvals.abandonAll()
622
+ if (withdrawn > 0) this.#options.log(`${withdrawn} approval question(s) withdrew: no paired device is connected`)
623
+ }
624
+
625
+ /** Release every user question to the next answerer. */
626
+ #releaseQuestions(): void {
627
+ const released = this.#options.questions.withdrawAll()
628
+ if (released > 0) this.#options.log(`${released} user question(s) released: no paired device is connected`)
629
+ }
238
630
  }