@linxin666/dsh-remote-bridge 0.4.9 → 0.4.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +28 -4
  3. package/README.zh.md +27 -4
  4. package/lib/client.js +511 -9
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +8671 -148
  7. package/lib/types/client/UiPresentRow.d.ts +13 -0
  8. package/lib/types/client/index.d.ts +4 -0
  9. package/lib/types/client/locales.d.ts +15 -2
  10. package/lib/types/client/toolview-slot.d.ts +68 -0
  11. package/lib/types/client/ui-card.d.ts +160 -0
  12. package/lib/types/core/connection.d.ts +38 -0
  13. package/lib/types/core/devices.d.ts +4 -0
  14. package/lib/types/core/extension.d.ts +13 -0
  15. package/lib/types/core/hub.d.ts +64 -0
  16. package/lib/types/core/protocol.d.ts +71 -7
  17. package/lib/types/core/push.d.ts +10 -2
  18. package/lib/types/core/turn-end-quiet.d.ts +135 -0
  19. package/lib/types/core/ui.d.ts +238 -0
  20. package/lib/types/host/ui-tools.d.ts +80 -0
  21. package/lib/types/host/watchers.d.ts +7 -0
  22. package/lib/types/index.d.ts +29 -1
  23. package/package.json +3 -2
  24. package/src/client/UiPresentRow.tsx +149 -0
  25. package/src/client/index.ts +11 -0
  26. package/src/client/locales.ts +22 -2
  27. package/src/client/toolview-slot.ts +84 -0
  28. package/src/client/ui-card.ts +368 -0
  29. package/src/client/ui-present.module.css +87 -0
  30. package/src/core/connection.ts +169 -6
  31. package/src/core/devices.ts +116 -2
  32. package/src/core/extension.ts +20 -0
  33. package/src/core/hub.ts +156 -1
  34. package/src/core/protocol.ts +78 -6
  35. package/src/core/push.ts +34 -3
  36. package/src/core/turn-end-quiet.ts +388 -0
  37. package/src/core/ui.ts +398 -0
  38. package/src/host/ui-tools.ts +233 -0
  39. package/src/host/watchers.ts +27 -3
  40. package/src/index.ts +70 -2
package/src/core/hub.ts CHANGED
@@ -23,6 +23,14 @@
23
23
  * because a blocking ask carries no call id and the phone still needs a handle
24
24
  * to answer with; and the claim outlives the last paired device by a grace
25
25
  * window, because a phone whose app the system suspended has refused nothing.
26
+ *
27
+ * A presented page (`ui.present`, protocol §35) is the second claim that takes a
28
+ * grace window, and it takes the same one: the tool call it blocks is the agent's
29
+ * own wait, the card is the only place its answer can come from, and a phone that
30
+ * was suspended has refused nothing either. It differs in one direction only —
31
+ * there is no "next answerer" to hand a card back to, so a window that runs out
32
+ * ends the tool call as a refusal (§35.5: the host side reads it as a timeout)
33
+ * rather than starting another answerer.
26
34
  * @module dsh-remote-bridge/core/hub
27
35
  */
28
36
 
@@ -30,10 +38,12 @@ import type { ApprovalOutcome } from '@deepseek-ai/dsh-user-approval'
30
38
  import type { PendingPromptView } from './approvals.ts'
31
39
  import type { BridgeConnectionOptions, BridgeTransport, ConnectionAuth } from './connection.ts'
32
40
  import { BridgeConnection } from './connection.ts'
33
- import { CAP_APPROVALS, CAP_QUESTIONS, TOPIC_APPROVAL_REQUEST, TOPIC_QUESTION_REQUEST } from './protocol.ts'
41
+ import { CAP_APPROVALS, CAP_QUESTIONS, CAP_UI, TOPIC_APPROVAL_REQUEST, TOPIC_QUESTION_REQUEST, TOPIC_UI_REQUEST } from './protocol.ts'
34
42
  import { questionPayload } from './questions.ts'
35
43
  import type { ClaimedQuestion, QuestionAnswer, UserQuestionRequestLike } from './questions.ts'
36
44
  import { isDeadPushToken, type PushDeliveryReport } from './push.ts'
45
+ import { uiPayload } from './ui.ts'
46
+ import type { JsonValue, UiCardView, UiPresentOutcome, UiRefusalReason } from './ui.ts'
37
47
 
38
48
  /**
39
49
  * The fields of an approval question this bridge reads. Structural on purpose:
@@ -88,6 +98,10 @@ function approvalPayload(prompt: PendingPromptView): ApprovalRequestPayload {
88
98
  */
89
99
  export const QUESTION_CLAIM_GRACE_MS = 60_000
90
100
 
101
+ // 同一个窗口也覆盖 §35 的整页卡:卡片同样只在「最后一次配对设备离开」时启动,只在
102
+ // 确有卡片被持有时启动,桥卸载时立即释放。窗口长度不新造旋钮——手机回来答题的时间
103
+ // 预算对提问与对卡片是同一件事,两处各写一个六万毫秒的常量只会让它们漂开。
104
+
91
105
  /**
92
106
  * How long a user question is held for a phone this bridge reached by
93
107
  * notification only, in milliseconds (§32.2).
@@ -128,6 +142,20 @@ export interface BridgeHubOptions extends BridgeConnectionOptions {
128
142
  readonly offlineClaimTtlMs?: number
129
143
  }
130
144
 
145
+ /**
146
+ * What one `ui.present` call ended as, with the count of connections that took
147
+ * the first frame.
148
+ *
149
+ * The count is here rather than in the card registry because it is a fact about
150
+ * delivery: the registry owns the claim, the hub owns the fan-out, and a client
151
+ * count read back out of the claim would be a second answer to the same question.
152
+ * It rides the tool result so the desktop can say how many screens the page
153
+ * reached (§35.10).
154
+ */
155
+ export type UiPresentReply =
156
+ | { readonly ok: true; readonly delivered: number; readonly type: string; readonly payload?: JsonValue }
157
+ | { readonly ok: false; readonly delivered: number; readonly reason: UiRefusalReason }
158
+
131
159
  /** The bridge's live connections plus the answerer it composes onto the approval chain. */
132
160
  export class BridgeHub {
133
161
  readonly #options: BridgeHubOptions
@@ -148,6 +176,11 @@ export class BridgeHub {
148
176
  * withdraws when a hello makes that permanent.
149
177
  */
150
178
  readonly #offlineClaims = new Map<string, NodeJS.Timeout>()
179
+ /**
180
+ * 整页卡(§35)的那一个释放窗口。卡表是全局的,所以一个定时器覆盖每一张卡,
181
+ * 同一时刻只可能有一个;它与 {@link #questionReleaseTimer} 各管各的通道。
182
+ */
183
+ #uiReleaseTimer: NodeJS.Timeout | undefined
151
184
 
152
185
  constructor(options: BridgeHubOptions) {
153
186
  this.#options = options
@@ -176,6 +209,7 @@ export class BridgeHub {
176
209
  onDeclare: (fresh) => {
177
210
  this.replayQuestions(fresh)
178
211
  this.replayApprovals(fresh)
212
+ this.replayUi(fresh)
179
213
  this.#reviewOfflineClaims()
180
214
  },
181
215
  },
@@ -208,6 +242,9 @@ export class BridgeHub {
208
242
  // the host's chain decides and the question's own deadline still holds — but
209
243
  // only once the window in which the phone can come back for it has run out.
210
244
  if (this.#options.questions.size > 0) this.#armQuestionRelease()
245
+ // 一张已经被手机看到的整页卡拿同一个窗口(§35.5),理由与提问逐字相同:那条
246
+ // 工具调用唯一的答案通道就是这张卡,手机在系统挂起它的时候什么都没拒绝。
247
+ if (this.#options.ui.size > 0) this.#armUiRelease()
211
248
  }
212
249
 
213
250
  /**
@@ -269,6 +306,29 @@ export class BridgeHub {
269
306
  }
270
307
  }
271
308
 
309
+ /**
310
+ * Hand one freshly declared connection the cards this bridge still holds (§35.5).
311
+ *
312
+ * Without this, a presentation raised while the phone was reconnecting stays on
313
+ * the host with no page anywhere on the phone: the first `ui.request` was
314
+ * addressed to the clients that had already announced the channel. The replay
315
+ * emits a frame and nothing else — it claims no card and moves no deadline, so
316
+ * re-handing a page never lengthens how long the agent waits for it.
317
+ *
318
+ * A phone that can take a card is on the wire, so the window that held those
319
+ * cards for nobody is over: it is cancelled here rather than at attach, because
320
+ * only a connection that DECLARED the channel can actually receive one (§11.5's
321
+ * own judgement, which §35.5 reuses).
322
+ * @param connection - the connection that just declared its capabilities.
323
+ */
324
+ replayUi(connection: BridgeConnection): void {
325
+ if (!connection.paired || !connection.declares(CAP_UI)) return
326
+ this.#cancelUiRelease()
327
+ for (const held of this.#options.ui.listed()) {
328
+ connection.emit(TOPIC_UI_REQUEST, held.payload)
329
+ }
330
+ }
331
+
272
332
  /**
273
333
  * Publish one event to every paired device that announced a capability.
274
334
  * @returns how many connections actually took the frame.
@@ -411,6 +471,55 @@ export class BridgeHub {
411
471
  return await claim.answer
412
472
  }
413
473
 
474
+ /**
475
+ * Present one page to the clients that declared `ui.v1` and wait for the user's
476
+ * first action (§35).
477
+ *
478
+ * The body of the `ui.present` tool call. Claimed only while a paired
479
+ * connection that declared the channel is on the wire: with none, a page would
480
+ * reach nobody, so the call answers `unavailable` at once instead of holding the
481
+ * agent on a wait no screen can end (§35.6 — the same judgement as §11.3's claim
482
+ * exclusivity). A frame no connection took is not held either, for the same
483
+ * reason.
484
+ *
485
+ * The card is announced `open` here and announced `settled` from the claim's own
486
+ * notice, so both frames come out of one payload builder and the page a phone was
487
+ * originally handed cannot drift from the one it reads back out of `ui.list`.
488
+ * @param card - the page, under the host's own `ToolCallId`.
489
+ * @param signal - the tool call's cancellation lifetime.
490
+ * @returns the user's action, or the refusal that ended the wait.
491
+ */
492
+ async present(card: UiCardView, signal?: AbortSignal): Promise<UiPresentReply> {
493
+ if (signal?.aborted === true) return { ok: false, delivered: 0, reason: 'cancelled' }
494
+ if (!this.#uiReachable()) return { ok: false, delivered: 0, reason: 'unavailable' }
495
+ const claim = this.#options.ui.open({
496
+ ...card,
497
+ ...(signal === undefined ? {} : { signal }),
498
+ onSettled: (settled): void => {
499
+ // The one notice every ending path uses: the client's card is over, whichever
500
+ // side ended it — the user answering, the grace window, a cancelled turn.
501
+ this.broadcastTo(CAP_UI, TOPIC_UI_REQUEST, uiPayload('settled', settled))
502
+ },
503
+ })
504
+ if (claim === undefined) return { ok: false, delivered: 0, reason: 'unavailable' }
505
+ const delivered = this.broadcastTo(CAP_UI, TOPIC_UI_REQUEST, uiPayload('open', claim))
506
+ // A page nobody took is not kept: the agent must not wait for a card that no
507
+ // screen is holding, and the claim is withdrawn rather than left open.
508
+ if (delivered === 0) {
509
+ this.#options.ui.withdraw([card.callId], 'unavailable')
510
+ return { ok: false, delivered: 0, reason: 'unavailable' }
511
+ }
512
+ const outcome: UiPresentOutcome = await claim.outcome
513
+ return outcome.ok
514
+ ? {
515
+ ok: true,
516
+ delivered,
517
+ type: outcome.type,
518
+ ...(outcome.payload === undefined ? {} : { payload: outcome.payload }),
519
+ }
520
+ : { ok: false, delivered, reason: outcome.reason }
521
+ }
522
+
414
523
  /** Close every connection and withdraw every question. Idempotent. */
415
524
  dispose(): void {
416
525
  // Unloading is not a phone going away: nothing can come back for these
@@ -419,12 +528,17 @@ export class BridgeHub {
419
528
  // chain at most once.
420
529
  this.#releaseOfflineClaims('the bridge unloaded')
421
530
  this.#cancelQuestionRelease()
531
+ // 卸载不是「手机离开了」:这些卡再也等不到动作,所以窗口立刻作废,释放就在
532
+ // 这里发生(§35.5「桥卸载立即释放」),不留定时器。
533
+ this.#cancelUiRelease()
422
534
  for (const connection of [...this.#connections]) {
423
535
  this.#connections.delete(connection)
424
536
  connection.dispose()
425
537
  }
426
538
  this.#options.approvals.abandonAll()
427
539
  this.#options.questions.withdrawAll()
540
+ const cards = this.#options.ui.withdrawAll()
541
+ if (cards > 0) this.#options.log(`${cards} presented page(s) released: the bridge unloaded`)
428
542
  }
429
543
 
430
544
  /**
@@ -627,4 +741,45 @@ export class BridgeHub {
627
741
  const released = this.#options.questions.withdrawAll()
628
742
  if (released > 0) this.#options.log(`${released} user question(s) released: no paired device is connected`)
629
743
  }
744
+
745
+ /**
746
+ * @returns whether a reachable right now connection can be shown a page (§35.6).
747
+ *
748
+ * The one predicate `ui.present` reads before it claims anything, and the reason
749
+ * a call with nobody on the wire answers `unavailable` without holding the agent:
750
+ * announcing a capability is the whole of what makes a client able to receive one.
751
+ */
752
+ #uiReachable(): boolean {
753
+ for (const connection of this.#connections) {
754
+ if (connection.paired && connection.declares(CAP_UI)) return true
755
+ }
756
+ return false
757
+ }
758
+
759
+ /**
760
+ * Arm the one release of the presented pages no paired device can answer.
761
+ *
762
+ * The same shape as {@link #armQuestionRelease} and the same window: a second
763
+ * departure while a window is already running must not extend it, so an armed
764
+ * timer is left alone. Its expiry ends those tool calls as a refusal, which is
765
+ * what §35.5 calls the host side reading the release as a timeout.
766
+ */
767
+ #armUiRelease(): void {
768
+ if (this.#uiReleaseTimer !== undefined) return
769
+ const timer = setTimeout(() => {
770
+ this.#uiReleaseTimer = undefined
771
+ const released = this.#options.ui.withdrawAll()
772
+ if (released > 0) this.#options.log(`${released} presented page(s) released: the grace window ended`)
773
+ }, QUESTION_CLAIM_GRACE_MS)
774
+ // A held page must never keep the host process alive.
775
+ timer.unref?.()
776
+ this.#uiReleaseTimer = timer
777
+ }
778
+
779
+ /** Drop the pending card window, if there is one. The cards it would release stay held. */
780
+ #cancelUiRelease(): void {
781
+ if (this.#uiReleaseTimer === undefined) return
782
+ clearTimeout(this.#uiReleaseTimer)
783
+ this.#uiReleaseTimer = undefined
784
+ }
630
785
  }
@@ -44,12 +44,17 @@ export const METHOD_PUSH_REGISTER = 'push.register'
44
44
  export const METHOD_USAGE_SESSION = 'usage.session'
45
45
  export const METHOD_USAGE_BALANCE = 'usage.balance'
46
46
  export const METHOD_USAGE_STATS = 'usage.stats'
47
+ // 协议 §35 追加的两个方法:一条卡上的动作回来,以及一张全局卡表的对账读。
48
+ export const METHOD_UI_EVENT = 'ui.event'
49
+ export const METHOD_UI_LIST = 'ui.list'
47
50
 
48
51
  /** Server-pushed topics of protocol v1. */
49
52
  export const TOPIC_SESSION_DELTA = 'session.delta'
50
53
  export const TOPIC_APPROVAL_REQUEST = 'approval.request'
51
54
  export const TOPIC_QUESTION_REQUEST = 'question.request'
52
55
  export const TOPIC_JOBS_CHANGED = 'jobs.changed'
56
+ // §35.2 追加的主题:一块整页自包含文档,以及它自己的结算通知。
57
+ export const TOPIC_UI_REQUEST = 'ui.request'
53
58
 
54
59
  /**
55
60
  * Capability a client declares in `hello`'s `cap` array to ask for a trimmed
@@ -249,6 +254,32 @@ export const CAP_USAGE = 'usage.v1'
249
254
  */
250
255
  export const CAP_USAGE_STATS = 'usage.stats.v1'
251
256
 
257
+ /**
258
+ * 客户端在 `hello` 的 `cap` 数组里宣告它要渲染整页卡并回答它(协议 §35)。
259
+ *
260
+ * 宣告它是 `ui.request` 与 `ui.event` 进入这个客户端协议的唯一前提:不宣告的
261
+ * 客户端——包括这个通道出现之前写下的每一个客户端——收不到任何一帧整页卡,它的
262
+ * `ui.event` 回 `unknown-method`,其余逐字节不变。它是**公告不是协商**(§13.1、
263
+ * §24.1 同一判据):宿主公告同名项、客户端声明,双向缺一即当作这个能力不存在,
264
+ * 且不得把「宿主没这个能力」渲染成「这张卡不存在」或任何错误态。
265
+ *
266
+ * 宿主半区只有真实现了 `ui.present` 这一半的桥才把自己列进
267
+ * {@link SERVED_CAPABILITIES},所以一个客户端读到这个名字,就能断定 `ui.request`
268
+ * 会出现、`ui.event` 会被接受。
269
+ */
270
+ export const CAP_UI = 'ui.v1'
271
+
272
+ /**
273
+ * 客户端在 `hello` 的 `cap` 数组里宣告它要按 §24.3 的四条件对账自己手上的整页卡
274
+ * (协议 §35.4)。
275
+ *
276
+ * 与 {@link CAP_QUESTION_LIST} 同一形状:`ui.list` 本身是只读的、对每条配对连接
277
+ * 都开放,这个名字买到的是「这条连接会不会被答」之外的另一种确定性——一条老桥
278
+ * 回 `unknown-method`,于是没有这个名字的客户端就保留它原有的退休规则(卡片只在
279
+ * `ui.request` 说 `settled` 时结束),而不是按一次它信不过的应答清卡。
280
+ */
281
+ export const CAP_UI_LIST = 'ui.list.v1'
282
+
252
283
  /**
253
284
  * Capability a client declares in `hello`'s `cap` array to be answered with
254
285
  * byte-level increments instead of the whole roster or the whole board.
@@ -450,6 +481,8 @@ export const KNOWN_METHODS: ReadonlySet<string> = new Set([
450
481
  METHOD_USAGE_SESSION,
451
482
  METHOD_USAGE_BALANCE,
452
483
  METHOD_USAGE_STATS,
484
+ METHOD_UI_EVENT,
485
+ METHOD_UI_LIST,
453
486
  ])
454
487
 
455
488
  /** Refusal codes the bridge itself raises (DSH failures cross as their own code). */
@@ -482,6 +515,23 @@ export const CODE_QUESTION_UNKNOWN = 'question-unknown'
482
515
  * not a complete one — it is a bridge that cannot answer this question today.
483
516
  */
484
517
  export const CODE_QUESTION_LIST_UNAVAILABLE = 'question-list-unavailable'
518
+ /**
519
+ * 本桥不认领这个 `callId`:它从没呈现过这张卡,或者这张卡已被别处结算(宽限窗口
520
+ * 到期、回合被取消、桥卸载)。客户端码表保持开放:除本码之外的未知码不得被读成
521
+ * 「卡已消失」(§11.3 同一句)。
522
+ */
523
+ export const CODE_UI_UNKNOWN = 'ui-unknown'
524
+ /**
525
+ * 这张卡已经被用户自己的第一条动作结算过(§35.3)。它与 {@link CODE_UI_UNKNOWN}
526
+ * 是两个答案:重复的一次点击是「已经做完了」,不是「这张卡不存在」。
527
+ */
528
+ export const CODE_UI_SETTLED = 'ui-settled'
529
+ /**
530
+ * 本桥读不出自己持有的卡,所以它说不了哪些还活着。答案故意不是一张空表:客户端
531
+ * 只会按 COMPLETE 的列表退休卡片,一次失败的读不是一张完整的空表,而是这台桥今天
532
+ * 答不了这一问(与 {@link CODE_QUESTION_LIST_UNAVAILABLE} 同一句)。
533
+ */
534
+ export const CODE_UI_LIST_UNAVAILABLE = 'ui-list-unavailable'
485
535
  /**
486
536
  * The named session is a delegated child whose durable parent is not a session
487
537
  * this connection may read. The bridge follows an addressable child and refuses
@@ -529,6 +579,13 @@ export const PROTO = 1
529
579
  /**
530
580
  * Minor version this package speaks.
531
581
  *
582
+ * 21 当可交互回复(协议 §35)落地:新增 {@link CAP_UI} 与 {@link CAP_UI_LIST}
583
+ * 两个能力名、{@link TOPIC_UI_REQUEST} 一个主题、{@link METHOD_UI_EVENT} 与
584
+ * {@link METHOD_UI_LIST} 两个方法,宿主半区还多一个模型工具 `ui.present`。客户端
585
+ * 因此从线路上读到两项新能力名、一种新主题与两种新应答体,所以 minor 抬一格;
586
+ * `proto` 仍为 1,没有任何既有帧、既有方法或既有键改形状。工具结果是**新增**的:
587
+ * 老会话、老 prompt、老回合都不受影响,工具名进入宿主工具表之后只有新回合才可能
588
+ * 被调用。
532
589
  * 20 when the usage stats channel shipped: behind {@link CAP_USAGE_STATS} a
533
590
  * client may call {@link METHOD_USAGE_STATS} and read the host's own usage
534
591
  * ledger — today, this month and one row per local day — and behind the same
@@ -633,14 +690,27 @@ export const PROTO = 1
633
690
  * declares the capability that plugin requires. No addition changed the major
634
691
  * version, a frozen field, or an existing method or topic name.
635
692
  */
636
- export const MINOR = 20
693
+ export const MINOR = 21
637
694
 
638
695
  /**
639
- * The capabilities this bridge itself serves, as `hello` advertises them.
640
- *
641
- * A capability a mounted plugin adds is not listed here: the bridge cannot know
642
- * what it is not the author of. A client learns such a capability from the
643
- * plugin's own documentation, exactly as it did before this list existed.
696
+ * The capabilities this bridge itself serves, and the opening half of what
697
+ * `hello` advertises.
698
+ *
699
+ * A capability a mounted plugin adds is not listed here — the bridge is not its
700
+ * author and names none of them — but `hello` advertises it all the same: the
701
+ * answer is this list plus every capability the extension registry currently
702
+ * requires a client to declare (`RemoteBridgeRegistry.capabilities`), computed
703
+ * on each greeting so a plugin mounted after this bridge was built is visible
704
+ * to the next phone. A name both halves carry is listed once, and this list
705
+ * keeps its order at the front, so a bridge with no extension mounted answers
706
+ * byte for byte the list it always did. Extension names never move
707
+ * {@link MINOR}: that number describes this protocol, and a plugin's own names
708
+ * are the plugin's.
709
+ *
710
+ * A capability whose whole switch is a declaration — no method, no answer, no
711
+ * field behind it, such as {@link CAP_APPROVALS} — stays out of this list for
712
+ * the reason it always did: advertising it would claim a handshake change
713
+ * without one.
644
714
  */
645
715
  export const SERVED_CAPABILITIES: readonly string[] = [
646
716
  CAP_SESSION_SNAPSHOT_TRIM,
@@ -664,6 +734,8 @@ export const SERVED_CAPABILITIES: readonly string[] = [
664
734
  CAP_PUSH,
665
735
  CAP_USAGE,
666
736
  CAP_USAGE_STATS,
737
+ CAP_UI,
738
+ CAP_UI_LIST,
667
739
  ]
668
740
  /** `server` field of the hello response. */
669
741
  export const SERVER_ID = 'dsh-remote-bridge'
package/src/core/push.ts CHANGED
@@ -16,7 +16,9 @@
16
16
  * screen, which is the last place session content should be;
17
17
  * - the same `(sessionId, event)` inside {@link PUSH_DEDUPE_MS} is one
18
18
  * notification, because two phones following one session both see the same
19
- * turn end and the user has one lock screen;
19
+ * turn end and the user has one lock screen, and one APNs token is one
20
+ * delivery, because a token belongs to the app install rather than to one
21
+ * pairing, so the rows that share it are still that one phone;
20
22
  * - a failed delivery is logged and dropped. Nothing here is awaited by the
21
23
  * delta path, so a broken APNs connection cannot delay, reorder or suppress a
22
24
  * frame that a connected phone is waiting for.
@@ -129,7 +131,13 @@ export interface PushLabels {
129
131
  }
130
132
 
131
133
  export interface PushNotifierOptions {
132
- /** The devices that asked to be notified, read per event. */
134
+ /**
135
+ * The devices that asked to be notified, read per event.
136
+ *
137
+ * The list may carry several rows holding the same `deviceToken`: a phone that
138
+ * pairs again owns more than one roster row, and a token outlives any one
139
+ * pairing. Converging them is this module's job, not the caller's.
140
+ */
133
141
  readonly targets: () => readonly PushAddress[]
134
142
  /** The sender; absent is a bridge with no signing key, and then nothing happens. */
135
143
  readonly sender?: PushSender
@@ -177,6 +185,26 @@ export function pushEventOfTurnEnd(reason: string): PushEvent {
177
185
  return reason === 'completed' ? 'turn-end' : 'turn-error'
178
186
  }
179
187
 
188
+ /**
189
+ * One address per APNs token, the first row winning.
190
+ *
191
+ * A token is minted by the app install rather than by a pairing, so every row
192
+ * holding the same token is the same phone: two rows are one lock screen, and
193
+ * sending to both shows one event twice.
194
+ * @param targets - every row the roster reported as a notification target.
195
+ * @returns one address per token, in roster order.
196
+ */
197
+ function perToken(targets: readonly PushAddress[]): PushAddress[] {
198
+ const seen = new Set<string>()
199
+ const kept: PushAddress[] = []
200
+ for (const target of targets) {
201
+ if (seen.has(target.deviceToken)) continue
202
+ seen.add(target.deviceToken)
203
+ kept.push(target)
204
+ }
205
+ return kept
206
+ }
207
+
180
208
  /**
181
209
  * The bridge's outbound notification path.
182
210
  *
@@ -265,7 +293,10 @@ export class PushNotifier {
265
293
  #announce(event: PushEvent, sessionId: string, onReport?: (report: PushDeliveryReport) => void): void {
266
294
  const sender = this.#options.sender
267
295
  if (sender === undefined) return
268
- const targets = this.#options.targets()
296
+ // One token is one app install is one lock screen, so the rows converge before
297
+ // anything is sent: the roster may hold the same phone twice without the
298
+ // phone being told twice.
299
+ const targets = perToken(this.#options.targets())
269
300
  if (targets.length === 0) return
270
301
  const now = this.#now()
271
302
  if (!this.#admit(event, sessionId, now)) return