@linxin666/dsh-remote-bridge 0.4.15 → 0.4.17

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. */
@@ -14,6 +14,7 @@ export const METHOD_SESSION_HISTORY_DEEP = 'session.history.deep'
14
14
  export const METHOD_SESSION_PROMPT = 'session.prompt'
15
15
  export const METHOD_SESSION_INTERRUPT = 'session.interrupt'
16
16
  export const METHOD_SESSION_ATTACHMENT = 'session.attachment'
17
+ export const METHOD_SESSION_ATTACHMENT_PATH = 'session.attachment.path'
17
18
  export const METHOD_SESSION_PERMISSIONS = 'session.permissions'
18
19
  export const METHOD_SESSION_SET_PERMISSION = 'session.setPermission'
19
20
  export const METHOD_SESSION_MODELS = 'session.models'
@@ -289,6 +290,19 @@ export const CAP_UI = 'ui.v1'
289
290
  * `ui.request` 说 `settled` 时结束),而不是按一次它信不过的应答清卡。
290
291
  */
291
292
  export const CAP_UI_LIST = 'ui.list.v1'
293
+ /**
294
+ * Capability a client declares in `hello`'s `cap` array to be told that this
295
+ * bridge can hand it the bytes of an image a session already offloaded.
296
+ *
297
+ * An announcement and nothing more, the same shape as
298
+ * {@link CAP_SESSION_DEEP_HISTORY}: `session.attachment.path` is open to every
299
+ * paired connection, because it is a pure read of one session's own durable
300
+ * transcript that costs no other client anything. Declaring the capability is how
301
+ * a client learns the method exists, and a client that does not declare it loses
302
+ * only that knowledge — it never sees a frame from this channel, because it never
303
+ * asks for one.
304
+ */
305
+ export const CAP_SESSION_ATTACHMENT_PATH = 'session.attachment.path.v1'
292
306
 
293
307
  /**
294
308
  * 宿主配了第二会合点时,在 `hello` 的 `capabilities` 里公告的能力名。
@@ -476,6 +490,7 @@ export const KNOWN_METHODS: ReadonlySet<string> = new Set([
476
490
  METHOD_SESSION_PROMPT,
477
491
  METHOD_SESSION_INTERRUPT,
478
492
  METHOD_SESSION_ATTACHMENT,
493
+ METHOD_SESSION_ATTACHMENT_PATH,
479
494
  METHOD_SESSION_PERMISSIONS,
480
495
  METHOD_SESSION_SET_PERMISSION,
481
496
  METHOD_SESSION_MODELS,
@@ -565,6 +580,23 @@ export const CODE_UI_LIST_UNAVAILABLE = 'ui-list-unavailable'
565
580
  * an unaddressable one, rather than reading it blind.
566
581
  */
567
582
  export const CODE_SESSION_NOT_FOLLOWABLE = 'session-not-followable'
583
+ /**
584
+ * 该路径不在这次会话自己的持久 transcript 里:白名单只有两处来源,客户端自选的路径
585
+ * 一律不在其中。`realpath()` 解析结果不再等于该字符串时也回这一码——那个路径已经
586
+ * 指向别处,就不再是这次会话点过的那个文件。
587
+ */
588
+ export const CODE_PATH_NOT_IN_SESSION = 'path-not-in-session'
589
+ /**
590
+ * 白名单里有这个路径,但它已经不是一个常规文件:文件被删了,或被换成了目录、设备或
591
+ * fifo。它与 {@link CODE_PATH_NOT_IN_SESSION} 是两个答案——「这次会话没点过它」与
592
+ * 「点过的那个文件不在了」。
593
+ */
594
+ export const CODE_ATTACHMENT_NOT_FOUND = 'not-found'
595
+ /**
596
+ * 文件确实在,但它的文件头魔数不是 png/jpeg/webp/gif 四种之一。扩展名不作数:`.png`
597
+ * 里装的不是 PNG 就回这一码,而一个叫 `.txt` 的 PNG 照常服务。
598
+ */
599
+ export const CODE_NOT_AN_IMAGE = 'not-an-image'
568
600
  export const CODE_SNAPSHOT_UNAVAILABLE = 'snapshot-unavailable'
569
601
  /**
570
602
  * This host composes no job registry, so it has no background jobs to publish.
@@ -606,6 +638,13 @@ export const PROTO = 1
606
638
  /**
607
639
  * Minor version this package speaks.
608
640
  *
641
+ * 22 当按路径取图落地(与协议 §18 的 `session.history.deep` 同例的一条读通道):
642
+ * 新增 {@link CAP_SESSION_ATTACHMENT_PATH} 一个能力名与
643
+ * {@link METHOD_SESSION_ATTACHMENT_PATH} 一个方法,客户端因此从线路上读到一种新的
644
+ * 应答体,所以 minor 抬一格。这个方法对每一条已配对连接都开放,能力名只公告:它决定
645
+ * 的是客户端要不要露出取图能力,不决定桥放不放行,理由与 {@link CAP_SESSION_DEEP_HISTORY}
646
+ * 逐字相同。`proto` 仍为 1,没有任何既有帧、既有方法或既有键改形状;不声明这个
647
+ * 名字的客户端一帧都不发,两边互不知情时线路逐字节不变。
609
648
  * 21 当可交互回复(协议 §35)落地:新增 {@link CAP_UI} 与 {@link CAP_UI_LIST}
610
649
  * 两个能力名、{@link TOPIC_UI_REQUEST} 一个主题、{@link METHOD_UI_EVENT} 与
611
650
  * {@link METHOD_UI_LIST} 两个方法,宿主半区还多一个模型工具 `ui_present`。客户端
@@ -717,7 +756,7 @@ export const PROTO = 1
717
756
  * declares the capability that plugin requires. No addition changed the major
718
757
  * version, a frozen field, or an existing method or topic name.
719
758
  */
720
- export const MINOR = 21
759
+ export const MINOR = 22
721
760
 
722
761
  /**
723
762
  * The capabilities this bridge itself serves, and the opening half of what
@@ -763,6 +802,7 @@ export const SERVED_CAPABILITIES: readonly string[] = [
763
802
  CAP_USAGE_STATS,
764
803
  CAP_UI,
765
804
  CAP_UI_LIST,
805
+ CAP_SESSION_ATTACHMENT_PATH,
766
806
  ]
767
807
  /** `server` field of the hello response. */
768
808
  export const SERVER_ID = 'dsh-remote-bridge'