@linxin666/dsh-remote-bridge 0.4.15 → 0.4.16

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.
package/src/core/hub.ts CHANGED
@@ -12,9 +12,7 @@
12
12
  * rather than the socket: with no paired connection on the wire but a device on
13
13
  * the roster that registered for pushes, the question is claimed for that phone
14
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.
15
+ * device that is reachable right now receive a question card".
18
16
  *
19
17
  * The claim on `user-questions/request` follows the same rules, with three
20
18
  * differences that belong to the host's own semantics: delegating is not a
@@ -24,6 +22,14 @@
24
22
  * to answer with; and the claim outlives the last paired device by a grace
25
23
  * window, because a phone whose app the system suspended has refused nothing.
26
24
  *
25
+ * Claiming is not swallowing any more. Both claims hand the same question to the
26
+ * host's own answerer chain the instant they exist, so the phone and the host's
27
+ * own panel hold one card each and the first answer settles it. Yielding is not
28
+ * delegating: the phone's card is only over once the other side really answered,
29
+ * which is why a question chain that rejects and an approval chain that falls
30
+ * through to its fail-closed `'unavailable'` end nothing here — the claim stays
31
+ * exactly as answerable as it was before the other surface existed.
32
+ *
27
33
  * A presented page (`ui_present`, protocol §35) is the second claim that takes a
28
34
  * grace window, and it takes the same one: the tool call it blocks is the agent's
29
35
  * own wait, the card is the only place its answer can come from, and a phone that
@@ -35,7 +41,7 @@
35
41
  */
36
42
 
37
43
  import type { ApprovalOutcome } from '@deepseek-ai/dsh-user-approval'
38
- import type { PendingPromptView } from './approvals.ts'
44
+ import type { ApprovalPrompt, PendingPromptView } from './approvals.ts'
39
45
  import type { BridgeConnectionOptions, BridgeTransport, ConnectionAuth } from './connection.ts'
40
46
  import { BridgeConnection } from './connection.ts'
41
47
  import { CAP_APPROVALS, CAP_QUESTIONS, CAP_UI, TOPIC_APPROVAL_REQUEST, TOPIC_QUESTION_REQUEST, TOPIC_UI_REQUEST } from './protocol.ts'
@@ -58,29 +64,61 @@ export interface ApprovalRequestLike {
58
64
  readonly signal?: AbortSignal
59
65
  }
60
66
 
67
+ /**
68
+ * The gateway this hub reads, plus the one predicate the bridge's structural face
69
+ * does not declare: whether a browser client that can answer these forwarded
70
+ * waterfalls is open right now (`ctx.typertGateway.hasLiveClient`).
71
+ *
72
+ * Optional on purpose. A host without the Web GUI never has one, a capture-only
73
+ * context implements only what the bridge calls, and absence reads as "no panel"
74
+ * — the state in which a notification has always been the delivery.
75
+ */
76
+ type PanelGateway = BridgeConnectionOptions['gateway'] & { readonly hasLiveClient?: () => boolean }
77
+
61
78
  /** The summary line a phone shows for one question. */
62
79
  export function approvalSummary(request: ApprovalRequestLike): string {
63
80
  return request.displayReason?.zh ?? request.displayReason?.en ?? request.toolName
64
81
  }
65
82
 
83
+ /**
84
+ * Whether an approval card is still the phone's to answer, or already over.
85
+ *
86
+ * A field of the payload rather than a second topic: a client written before it
87
+ * knows no such key, so it reads exactly the frame it always read and the
88
+ * question simply stays on screen until it is answered or refused.
89
+ */
90
+ export type ApprovalState = 'open' | 'settled'
91
+
66
92
  /** The `approval.request` payload one claim is published with. */
67
93
  export interface ApprovalRequestPayload {
68
94
  readonly sessionId: string
69
95
  readonly id: string
70
96
  readonly summary: string
71
97
  readonly toolName: string
98
+ /** Absent means `open`, which is what every frame published before this field carries. */
99
+ readonly state?: ApprovalState
72
100
  }
73
101
 
74
102
  /**
75
103
  * The `approval.request` payload for one claim.
76
104
  *
77
- * The first broadcast and the replay of a still-open claim go through this one
78
- * function, so the card a phone was originally shown and the same card handed to
79
- * it again after a reconnect cannot drift apart.
105
+ * The first broadcast, the replay of a still-open claim and the notice that the
106
+ * host's own panel answered it all go through this one function, so the card a
107
+ * phone was originally shown and the same card handed to it again after a
108
+ * reconnect cannot drift apart. `state` is published only when it is not the
109
+ * default, so every frame that existed before it is byte for byte what it was.
80
110
  * @param prompt - the claim being published.
111
+ * @param state - `open` for a question a phone can answer, `settled` for the
112
+ * notice that the host's own panel answered it first.
81
113
  */
82
- function approvalPayload(prompt: PendingPromptView): ApprovalRequestPayload {
83
- return { sessionId: prompt.sessionId, id: prompt.id, summary: prompt.summary, toolName: prompt.toolName }
114
+ function approvalPayload(prompt: PendingPromptView, state: ApprovalState = 'open'): ApprovalRequestPayload {
115
+ return {
116
+ sessionId: prompt.sessionId,
117
+ id: prompt.id,
118
+ summary: prompt.summary,
119
+ toolName: prompt.toolName,
120
+ ...(state === 'open' ? {} : { state }),
121
+ }
84
122
  }
85
123
 
86
124
  /**
@@ -102,45 +140,16 @@ export const QUESTION_CLAIM_GRACE_MS = 60_000
102
140
  // 确有卡片被持有时启动,桥卸载时立即释放。窗口长度不新造旋钮——手机回来答题的时间
103
141
  // 预算对提问与对卡片是同一件事,两处各写一个六万毫秒的常量只会让它们漂开。
104
142
 
105
- /**
106
- * How long a user question is held for a phone this bridge reached by
107
- * notification only, in milliseconds (§32.2).
108
- *
109
- * Inside this window the question exists only on the phone's side: the alert is
110
- * out, no socket has it, and the host's own answerer chain has not been started.
111
- * When it runs out the claim is withdrawn and delegated, so the agent behind a
112
- * timed ask waits at most this long past its own deadline and the agent behind a
113
- * blocking ask (no call id, no deadline) waits at most this long in total — an
114
- * accepted cost, because the alternative is a question that vanished while the
115
- * phone was asleep. The window is the bridge's own constant and not the host's:
116
- * a deployment overrides it, the host never sees it.
117
- */
118
- export const OFFLINE_QUESTION_CLAIM_TTL_MS = 600_000
119
-
120
- // Those two windows are different timers and never one. QUESTION_CLAIM_GRACE_MS
121
- // is a grace on the way OUT: a phone was on the wire, it left, and the window is
122
- // that phone's reconnect budget before the held claim is delegated.
123
- // OFFLINE_QUESTION_CLAIM_TTL_MS is the whole lifetime of a claim that never had a
124
- // phone on the wire at all. One claim can be covered by both in turn — claimed for
125
- // the absent phone, handed to the phone that then declared the channel, left by
126
- // that phone again — and whichever is due first releases it. The release is
127
- // idempotent (the claim is deleted before it is delegated and the chain it starts
128
- // is memoized), so the later timer finds no claim and the host's own answerer is
129
- // started at most once.
130
-
131
143
  /** Which path a user question takes right now (§11.3). */
132
144
  type QuestionMode = 'online' | 'offline' | 'nobody'
133
145
 
134
- /** What the hub is built with: the bridge's shared options plus the windows it owns. */
135
- export interface BridgeHubOptions extends BridgeConnectionOptions {
136
- /**
137
- * The offline claim window, in milliseconds.
138
- *
139
- * Defaults to {@link OFFLINE_QUESTION_CLAIM_TTL_MS}; a deployment knob, and the
140
- * seam a suite uses to move the window instead of waiting it out.
141
- */
142
- readonly offlineClaimTtlMs?: number
143
- }
146
+ /**
147
+ * What the hub is built with: the bridge's shared options.
148
+ *
149
+ * A named type of its own so a suite can build a hub without the whole plugin,
150
+ * and so the options this class reads stay one declaration.
151
+ */
152
+ export interface BridgeHubOptions extends BridgeConnectionOptions {}
144
153
 
145
154
  /**
146
155
  * What one `ui_present` call ended as, with the count of connections that took
@@ -166,16 +175,6 @@ export class BridgeHub {
166
175
  * claim and there is never more than one of them.
167
176
  */
168
177
  #questionReleaseTimer: NodeJS.Timeout | undefined
169
- /**
170
- * The offline claims still waiting on a phone, by wire call id, each with the
171
- * timer that holds it for its window.
172
- *
173
- * A question leaves this table the moment the phone takes it over, answers it,
174
- * or the window releases it, so a call id in here is a question no reachable
175
- * device has been shown — which is exactly what {@link #reviewOfflineClaims}
176
- * withdraws when a hello makes that permanent.
177
- */
178
- readonly #offlineClaims = new Map<string, NodeJS.Timeout>()
179
178
  /**
180
179
  * 整页卡(§35)的那一个释放窗口。卡表是全局的,所以一个定时器覆盖每一张卡,
181
180
  * 同一时刻只可能有一个;它与 {@link #questionReleaseTimer} 各管各的通道。
@@ -210,7 +209,6 @@ export class BridgeHub {
210
209
  this.replayQuestions(fresh)
211
210
  this.replayApprovals(fresh)
212
211
  this.replayUi(fresh)
213
- this.#reviewOfflineClaims()
214
212
  },
215
213
  },
216
214
  transport,
@@ -269,10 +267,6 @@ export class BridgeHub {
269
267
  */
270
268
  replayQuestions(connection: BridgeConnection): void {
271
269
  if (!connection.paired || !connection.declares(CAP_QUESTIONS)) return
272
- // A phone that can take a card is on the wire: the windows that held these
273
- // claims for nobody are over. The claims themselves are handed over below
274
- // rather than released — they are this phone's to answer now.
275
- this.#cancelOfflineClaims()
276
270
  // The claim's own state, not `open` for every claim: a question whose
277
271
  // foreground wait the host already ended is `continued`, and replaying it as
278
272
  // open tells the phone to wait on an agent that has already moved on. The
@@ -344,9 +338,14 @@ export class BridgeHub {
344
338
 
345
339
  /**
346
340
  * The body of this plugin's `approval/request` listener.
341
+ *
342
+ * The claim yields the moment it exists: the host's own panel is offered the
343
+ * same question, so the phone and the panel hold one card each and the first
344
+ * answer decides. A panel that answers first ends the phone's claim and the phone
345
+ * is told; a phone that answers first leaves the panel's later answer ignored.
347
346
  * @param request - the pending question.
348
347
  * @param next - the rest of the answerer chain.
349
- * @returns a claimed decision, or whatever the next answerer says.
348
+ * @returns the first decision, or whatever the next answerer says.
350
349
  */
351
350
  async approve(request: ApprovalRequestLike, next: () => Promise<ApprovalOutcome>): Promise<ApprovalOutcome> {
352
351
  if (this.pairedClients === 0) return await next()
@@ -365,13 +364,19 @@ export class BridgeHub {
365
364
  // withdrawn claim stood for can no longer be answered by any phone, and a
366
365
  // notification about it would be a card with nothing behind it (§28.5).
367
366
  else {
368
- this.#options.push?.notify('approval', sessionId)
367
+ // A notification stands in for the host's own panel, so one is only sent
368
+ // while that panel is not on the wire (§28).
369
+ if (!this.#hasLiveClient()) this.#options.push?.notify('approval', sessionId)
369
370
  // The card is not a second answerer: it only says a tool is blocked, with
370
371
  // the fixed line and none of the tool's own reason text (§29).
371
372
  this.#options.liveActivity?.noteApproval(sessionId)
372
373
  }
374
+ // The panel is offered the same question from here on. It is offered after
375
+ // the card above rather than before it, so a decision that arrives at once
376
+ // still follows the open frame on the wire instead of preceding it.
377
+ const chain = this.#startApprovalChain(prompt, next)
373
378
  const answer = await prompt.answer
374
- return answer === undefined ? await next() : answer
379
+ return answer === undefined ? await chain : answer
375
380
  }
376
381
 
377
382
  /**
@@ -385,9 +390,11 @@ export class BridgeHub {
385
390
  * host's own when the ask is timed, and minted here when it is blocking and the
386
391
  * host assigned none — either way the phone answers the id it was shown. A claim
387
392
  * nobody received is withdrawn at once instead of holding the agent until the
388
- * host's deadline. For a timed ask the host's own remaining wait travels with
389
- * the first frame as `expiresAt`, and every later move of that deadline is
390
- * re-published under the same call id.
393
+ * host's deadline. The host's own answerer chain is entered the instant the
394
+ * claim exists, in every mode, so the host's panel shows the same question and
395
+ * the first answer settles both. For a timed ask the host's own remaining wait
396
+ * travels with the first frame as `expiresAt`, and every later move of that
397
+ * deadline is re-published under the same call id.
391
398
  * @param request - the pending question batch.
392
399
  * @param next - the rest of the answerer chain.
393
400
  * @returns the phone's answer, the host's own deadline outcome, or whatever the next answerer says.
@@ -401,7 +408,7 @@ export class BridgeHub {
401
408
  if (this.pairedClients === 0) await this.#options.roster.load()
402
409
  const mode = this.#questionMode()
403
410
  // Nobody reachable can be shown this question: it belongs to the next answerer,
404
- // exactly as it did before the offline window existed.
411
+ // exactly as every other case this bridge cannot deliver does.
405
412
  if (mode === 'nobody') return await next()
406
413
  // A blocking ask carries no `wait`: the host has no call id for it, but the
407
414
  // phone needs a handle to answer with, so one is minted in this bridge's own
@@ -436,6 +443,9 @@ export class BridgeHub {
436
443
  },
437
444
  })
438
445
  if (claim === undefined) return await next()
446
+ // Claiming is not swallowing: the panel is offered this question from this
447
+ // instant on, whatever mode claimed it, and the first answer settles both.
448
+ claim.startHostChain()
439
449
  if (mode === 'offline') return await this.#holdOfflineClaim(sessionId, callId, claim)
440
450
  // The host's own first wait frame is folded into this same frame: a phone is
441
451
  // handed the question and how long it has together, rather than a card that a
@@ -457,7 +467,9 @@ export class BridgeHub {
457
467
  // a connected phone is withdrawn at once, so a notification would announce
458
468
  // something already gone.
459
469
  else {
460
- this.#options.push?.notify('question', sessionId)
470
+ // The same substitution as the approval above: the alert is the delivery
471
+ // only while the host's own panel is not there to show the card.
472
+ if (!this.#hasLiveClient()) this.#options.push?.notify('question', sessionId)
461
473
  // Only the first question's header and at most two option labels reach that
462
474
  // session's card: they are the choices the App can offer (§29.7: the card has
463
475
  // no controls of its own). The questions themselves stay on the wire, exactly
@@ -523,10 +535,7 @@ export class BridgeHub {
523
535
  /** Close every connection and withdraw every question. Idempotent. */
524
536
  dispose(): void {
525
537
  // Unloading is not a phone going away: nothing can come back for these
526
- // claims, so every window is dropped and the release happens right here — the
527
- // offline ones through their own entry, so this route also starts the host's
528
- // chain at most once.
529
- this.#releaseOfflineClaims('the bridge unloaded')
538
+ // claims, so every window is dropped and the release happens right here.
530
539
  this.#cancelQuestionRelease()
531
540
  // 卸载不是「手机离开了」:这些卡再也等不到动作,所以窗口立刻作废,释放就在
532
541
  // 这里发生(§35.5「桥卸载立即释放」),不留定时器。
@@ -573,11 +582,8 @@ export class BridgeHub {
573
582
  /**
574
583
  * Which path a user question takes right now (§11.3).
575
584
  *
576
- * The one entry, read twice: when a question arrives, and again when a paired
577
- * connection finishes its hello while an offline claim is still held. Both
578
- * moments ask the same thing — can a device that is reachable right now receive
579
- * a question card — and answering it in two places is how two answers drift
580
- * apart.
585
+ * The one judgement behind both deliveries: can a device that is reachable
586
+ * right now receive a question card, or does the alert have to stand in for it.
581
587
  * @returns `online` for the ordinary claim-and-broadcast path, `offline` for a
582
588
  * claim held for a phone reached by notification, and `nobody` when the question
583
589
  * has to go straight to the next answerer.
@@ -604,30 +610,27 @@ export class BridgeHub {
604
610
  }
605
611
 
606
612
  /**
607
- * Hold one question for a phone that is not on the wire (§32).
613
+ * Claim one question for a phone that is not on the wire (§32).
608
614
  *
609
615
  * No socket is paired, so this claim's own first frame would reach nobody: the
610
- * notification IS its delivery, and it is sent whether or not a broadcast would
611
- * have landed. Inside the window the question exists only on the phone's side;
612
- * the phone that comes back is handed the card by the replay in `onDeclare`,
613
- * and the phone that answers settles it through the ordinary path.
616
+ * notification IS its delivery. Nothing is held on the phone's behalf any more —
617
+ * the host's own chain was offered the same question at claim time — so the
618
+ * claim lives exactly as long as any other: until the phone answers it, the
619
+ * host's deadline ends it, or this bridge unloads.
614
620
  * @param sessionId - the session that asked.
615
621
  * @param callId - the wire id the phone will answer under.
616
622
  * @param claim - the claim this bridge just opened.
617
623
  * @returns the phone's answer, or whatever the next answerer says.
618
624
  */
619
625
  async #holdOfflineClaim(sessionId: string, callId: string, claim: ClaimedQuestion): Promise<QuestionAnswer> {
620
- this.#armOfflineClaim(callId)
621
- // The report is the only way this bridge learns that the phone it claimed for
622
- // is gone for good: a frame would have carried that fact, an alert does not.
623
- this.#options.push?.notify('question', sessionId, (report) => { this.#onQuestionPushed(callId, report) })
624
- try {
625
- return await claim.answer
626
- } finally {
627
- // Every path that ends this claim — answered, delegated, expired by the host
628
- // — drops its window here, so no timer outlives the question it was armed for.
629
- this.#cancelOfflineClaim(callId)
626
+ // The same substitution the online path makes: with the panel on the wire it
627
+ // is the delivery and the phone is not rung.
628
+ if (!this.#hasLiveClient()) {
629
+ // The report is the only way this bridge learns that the phone it announced
630
+ // to is gone for good: a frame would have carried that fact, an alert does not.
631
+ this.#options.push?.notify('question', sessionId, (report) => { this.#onQuestionPushed(callId, report) })
630
632
  }
633
+ return await claim.answer
631
634
  }
632
635
 
633
636
  /**
@@ -636,9 +639,8 @@ export class BridgeHub {
636
639
  * Three APNs answers are final about a registration: 410 with `Unregistered`, or
637
640
  * `Unregistered`/`BadDeviceToken` on any status. The device is cleaned off the
638
641
  * roster, and the claim is kept only while some other registered device is still
639
- * there to be told; when the last one is gone the question cannot reach a phone
640
- * at all, so it goes back to the host's chain now instead of at the end of a
641
- * window nobody is left to use.
642
+ * there to be told; when the last one is gone the claim is given up, because no
643
+ * phone can be told this question exists.
642
644
  * @param callId - the offline claim this notification was about.
643
645
  * @param report - how the announcement ended.
644
646
  */
@@ -655,7 +657,7 @@ export class BridgeHub {
655
657
  const survivors = reachable.filter(({ push }) => !dead.includes(push.deviceToken))
656
658
  void this.#forgetDeadTokens(dead)
657
659
  if (survivors.length > 0) return
658
- this.#releaseOfflineClaim(callId, 'APNs refused every device token on the roster')
660
+ this.#releaseUnreachableClaim(callId, 'APNs refused every device token on the roster')
659
661
  }
660
662
 
661
663
  /** Drop each dead registration from the roster, then let the watchers settle. */
@@ -672,80 +674,77 @@ export class BridgeHub {
672
674
  }
673
675
 
674
676
  /**
675
- * End every offline claim the wire has just made unreachable (§11.3).
677
+ * Give up one claim no phone can be told about any more.
676
678
  *
677
- * A hello that leaves no paired connection able to take a card — the client
678
- * written before `questions.v1` going online — is the same fact the claim point
679
- * reads, so it releases the claim at once instead of at the end of its window.
679
+ * The one route for that fact — a roster whose every registered token APNs
680
+ * refuses — so nobody settles the question twice: `withdraw` deletes the claim
681
+ * before it hands the question to the chain that was started at claim time, and
682
+ * the chain is memoized, so a second route releases nothing and announces
683
+ * nothing.
684
+ * @param callId - the claim to release.
685
+ * @param reason - why, logged once when something really was released.
680
686
  */
681
- #reviewOfflineClaims(): void {
682
- if (this.#offlineClaims.size === 0) return
683
- if (this.#questionMode() === 'offline') return
684
- this.#releaseOfflineClaims('no paired connection on the wire can receive a question')
687
+ #releaseUnreachableClaim(callId: string, reason: string): void {
688
+ const released = this.#options.questions.withdraw([callId])
689
+ if (released > 0) this.#options.log(`an offline-claimed user question was released: ${reason}`)
690
+ }
691
+
692
+ /** Abandon every approval: no paired device is left to answer one. */
693
+ #abandonApprovals(): void {
694
+ const withdrawn = this.#options.approvals.abandonAll()
695
+ if (withdrawn > 0) this.#options.log(`${withdrawn} approval question(s) withdrew: no paired device is connected`)
685
696
  }
686
697
 
687
698
  /**
688
- * Arm the window that holds one offline claim.
699
+ * Hand one approval question to the host's own answerers.
689
700
  *
690
- * Deliberately a second timer beside {@link #armQuestionRelease}, never the same
691
- * one: that window is the reconnect budget of a phone that just left, this one is
692
- * the whole lifetime of a claim no phone ever had, and one claim can be governed
693
- * by both in turn. Whichever is due first releases it, and the release is
694
- * idempotent, so the later one finds no claim.
695
- * @param callId - the claim to hold.
701
+ * The chain is entered once, at claim time, so the panel is shown the same card
702
+ * the phone holds. Only a real decision ends the phone's claim: a rejection is
703
+ * not an answer, and neither is the fail-closed `'unavailable'` the chain returns
704
+ * when no panel took the question at all — the phone may still answer either way.
705
+ * @param prompt - the claim the chain is answering for.
706
+ * @param next - the rest of the answerer chain.
707
+ * @returns the chain's outcome, rejection included, for the caller that has to
708
+ * wait on it after the phone stopped being able to answer.
696
709
  */
697
- #armOfflineClaim(callId: string): void {
698
- if (this.#offlineClaims.has(callId)) return
699
- const ttl = this.#options.offlineClaimTtlMs ?? OFFLINE_QUESTION_CLAIM_TTL_MS
700
- const timer = setTimeout(() => {
701
- this.#releaseOfflineClaim(callId, 'the offline claim window ended')
702
- }, Math.max(0, ttl))
703
- // A question held for a phone must never keep the host process alive.
704
- timer.unref?.()
705
- this.#offlineClaims.set(callId, timer)
706
- }
707
-
708
- /** Drop one claim's window. The claim itself keeps whatever state it has. */
709
- #cancelOfflineClaim(callId: string): void {
710
- const timer = this.#offlineClaims.get(callId)
711
- if (timer === undefined) return
712
- clearTimeout(timer)
713
- this.#offlineClaims.delete(callId)
714
- }
715
-
716
- /** Drop every offline window: a phone is on the wire for those claims now, or they are about to be released. */
717
- #cancelOfflineClaims(): void {
718
- for (const timer of this.#offlineClaims.values()) clearTimeout(timer)
719
- this.#offlineClaims.clear()
710
+ #startApprovalChain(prompt: ApprovalPrompt, next: () => Promise<ApprovalOutcome>): Promise<ApprovalOutcome> {
711
+ let chain: Promise<ApprovalOutcome>
712
+ try {
713
+ chain = next()
714
+ } catch (error) {
715
+ chain = Promise.reject(error)
716
+ }
717
+ void chain.then(outcome => { this.#settleApprovalFromHost(prompt, outcome) }, () => undefined)
718
+ return chain
720
719
  }
721
720
 
722
721
  /**
723
- * Release one offline claim back to the host's own chain.
722
+ * End one claim on the decision the host's own panel gave.
724
723
  *
725
- * The one entry every route uses — the window ending, a roster whose tokens are
726
- * all dead, a hello that left nobody able to receive, the bridge unloading — so
727
- * "the host's chain is started at most once" is a property of this entry rather
728
- * than of its callers: `withdraw` deletes the claim before it delegates, and the
729
- * chain a claim starts is memoized, so a second route releases nothing and starts
730
- * nothing, and no notification is sent for a question that already left.
731
- * @param callId - the claim to release.
732
- * @param reason - why, logged once when something really was released.
724
+ * The release decides, not the outcome alone: a claim the phone already answered
725
+ * is not pending any more, so its answer stands and nothing is announced a second
726
+ * time. `'unavailable'` is the chain's fail-closed default rather than a decision
727
+ * — no panel took the question — and it leaves the claim exactly as it was.
728
+ * @param prompt - the claim the chain was started for.
729
+ * @param outcome - what the host's own answerers decided.
733
730
  */
734
- #releaseOfflineClaim(callId: string, reason: string): void {
735
- this.#cancelOfflineClaim(callId)
736
- const released = this.#options.questions.withdraw([callId])
737
- if (released > 0) this.#options.log(`an offline-claimed user question was released: ${reason}`)
738
- }
739
-
740
- /** Release every offline claim through {@link #releaseOfflineClaim}. */
741
- #releaseOfflineClaims(reason: string): void {
742
- for (const callId of [...this.#offlineClaims.keys()]) this.#releaseOfflineClaim(callId, reason)
731
+ #settleApprovalFromHost(prompt: ApprovalPrompt, outcome: ApprovalOutcome): void {
732
+ if (outcome === 'unavailable') return
733
+ if (!this.#options.approvals.releaseToHost(prompt.id)) return
734
+ this.broadcast(TOPIC_APPROVAL_REQUEST, approvalPayload(prompt, 'settled'))
743
735
  }
744
736
 
745
- /** Abandon every approval: no paired device is left to answer one. */
746
- #abandonApprovals(): void {
747
- const withdrawn = this.#options.approvals.abandonAll()
748
- if (withdrawn > 0) this.#options.log(`${withdrawn} approval question(s) withdrew: no paired device is connected`)
737
+ /**
738
+ * @returns whether a browser client that can answer these waterfalls is on the wire.
739
+ *
740
+ * The gateway's own predicate, read through the bridge's structural face. A
741
+ * notification stands in for that panel, so it is only sent when the panel is not
742
+ * there; a host without the Web GUI — and a capture-only test context — answers
743
+ * `false`, which is the state in which the alert has always been the delivery.
744
+ */
745
+ #hasLiveClient(): boolean {
746
+ const gateway: PanelGateway = this.#options.gateway
747
+ return gateway.hasLiveClient?.() === true
749
748
  }
750
749
 
751
750
  /** Release every user question to the next answerer. */
@@ -64,16 +64,24 @@ export interface QuestionItem {
64
64
  readonly multiSelect?: boolean
65
65
  }
66
66
 
67
- /** One item of the answer batch. */
67
+ /**
68
+ * One item of the answer batch. `selected` is a mutable array because the host's
69
+ * own answer item declares it mutable, and a readonly array is not assignable to
70
+ * a mutable one - the host's `user-questions/request` handler is typed with its
71
+ * own answer type, so this mirror has to stay assignable to it.
72
+ */
68
73
  export interface QuestionAnswerItem {
69
74
  readonly id: string
70
- readonly selected: readonly string[]
75
+ readonly selected: string[]
71
76
  readonly custom?: string
72
77
  }
73
78
 
74
- /** The whole answer batch the host's ask is settled with. */
79
+ /**
80
+ * The whole answer batch the host's ask is settled with. `answers` is mutable for
81
+ * the same reason {@link QuestionAnswerItem} keeps `selected` mutable.
82
+ */
75
83
  export interface QuestionAnswer {
76
- readonly answers: readonly QuestionAnswerItem[]
84
+ readonly answers: QuestionAnswerItem[]
77
85
  }
78
86
 
79
87
  /**
@@ -192,6 +200,14 @@ export interface ClaimedQuestionView {
192
200
  export interface ClaimedQuestion extends ClaimedQuestionView {
193
201
  /** The host's ask: the phone's answer, or whatever the next answerer says. */
194
202
  readonly answer: Promise<QuestionAnswer>
203
+ /**
204
+ * Hand the same question to the host's own answerer chain, once.
205
+ *
206
+ * Called by the hub the instant a claim exists, in every mode: the phone is
207
+ * not the only surface any more, so the host's own panel shows the card too
208
+ * and the first answer settles it.
209
+ */
210
+ readonly startHostChain: () => void
195
211
  /**
196
212
  * Epoch milliseconds at which the host's own deadline falls, from the first
197
213
  * wait frame of this claim.
@@ -417,11 +433,11 @@ export class QuestionClaims {
417
433
  })
418
434
  const signal = input.signal
419
435
  const onAbort = (): void => { this.#expire(input.callId, signal?.reason) }
420
- // The rest of the answerer chain is the host's own UI, and it must keep
421
- // showing the question: claiming here used to swallow it. Started once, at
422
- // claim time, so both surfaces display it and the first answer settles it.
423
- // A rejection is not a verdict — the phone may still answer — so it is
424
- // remembered for a later withdraw instead of failing the claim now.
436
+ // The rest of the answerer chain is the host's own UI. Started once and
437
+ // memoized, because both paths that yield to it — the claim itself, and the
438
+ // withdraw that hands a question back — have to reach the same panel rather
439
+ // than open a second one. A rejection is not a verdict (the phone may still
440
+ // answer), so only the withdraw path turns one into this claim's failure.
425
441
  let nextStarted: Promise<QuestionAnswer> | undefined
426
442
  const startNext = (): Promise<QuestionAnswer> => {
427
443
  if (nextStarted === undefined) {
@@ -539,17 +555,27 @@ export class QuestionClaims {
539
555
  resolveDeadline(undefined)
540
556
  }
541
557
  }
558
+ /**
559
+ * Hand this claim to the host's own answerers, once.
560
+ *
561
+ * Both surfaces are shown the question and the first answer settles it: an
562
+ * answer from the chain ends the claim here, and an answer from the phone
563
+ * ends it in {@link answer} — which leaves the chain's later answer ignored
564
+ * instead of settling or broadcasting a second time.
565
+ */
566
+ const startHostChain = (): void => {
567
+ void startNext().then(answer => { this.#settleFromHost(input.callId, answer) }, () => undefined)
568
+ }
542
569
  this.#claims.set(input.callId, record)
543
- // The rest of the chain is NOT started here. A connected phone takes the
544
- // question on its own, and the host's own panel would otherwise stay open
545
- // after the phone answered it — the bridge has no way to close that panel.
546
- // A phone that is absent, or a claim that is withdrawn, still delegates.
570
+ // The chain itself is started by the hub through {@link startHostChain} the
571
+ // instant this claim exists, so the panel and the phone are shown the same
572
+ // question and whichever answers first settles both.
547
573
  if (signal?.aborted === true) onAbort()
548
574
  else signal?.addEventListener('abort', onAbort, { once: true })
549
575
  if (input.hosted) void trackWait()
550
576
  // A blocking ask carries no host deadline at all: nothing to follow, nothing to publish.
551
577
  else resolveDeadline(undefined)
552
- return { ...viewOf(record), answer, deadline }
578
+ return { ...viewOf(record), answer, deadline, startHostChain }
553
579
  }
554
580
 
555
581
  /**
@@ -662,6 +688,27 @@ export class QuestionClaims {
662
688
  }
663
689
  }
664
690
 
691
+ /**
692
+ * Settle one claim from the host's own answerer chain.
693
+ *
694
+ * Only a claim this bridge still holds can be ended this way: a phone that
695
+ * answered first deletes it, and the chain's late answer must not settle it a
696
+ * second time or announce a card that is already gone. A claim the host's own
697
+ * deadline turned into `continued` is left alone as well — its answer promise
698
+ * is that deadline, and the phone's late answer still has its own road.
699
+ * @param callId - the claim the host answered.
700
+ * @param answer - the host's own answer.
701
+ */
702
+ #settleFromHost(callId: string, answer: QuestionAnswer): void {
703
+ const record = this.#claims.get(callId)
704
+ if (record === undefined || record.state !== 'open') return
705
+ this.#claims.delete(callId)
706
+ record.detach()
707
+ record.stopWait()
708
+ record.notifySettled()
709
+ record.settle(answer)
710
+ }
711
+
665
712
  /**
666
713
  * Settle one open claim from the host's own cancellation lifetime.
667
714
  *