@linxin666/dsh-remote-bridge 0.4.9 → 0.4.11

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
@@ -0,0 +1,87 @@
1
+ /* The `ui.present` transcript card: a header line, the page in a controlled
2
+ frame, and the one sentence telling the operator where an answer happens.
3
+ Colour comes only from the theme's semantic aliases; geometry and type resolve
4
+ through the scale below, so no element carries a one-off literal (KFL R4
5
+ centralizes the value, A3 keeps one spacing rhythm, H5 holds the card to two
6
+ type sizes: 13 for the header title and the page, 12 for state and notice). */
7
+
8
+ .card,
9
+ .row {
10
+ --card-space-1: 4px;
11
+ --card-space-2: 8px;
12
+ --card-space-3: 12px;
13
+ --card-title-size: 13px;
14
+ --card-title-line: 20px;
15
+ --card-state-size: 12px;
16
+ --card-state-line: 18px;
17
+ --card-radius: 8px;
18
+ --card-edge: 1px;
19
+ --card-default-height: 320px;
20
+ }
21
+
22
+ /* The header keeps one box across both states: the badge sits at the trailing
23
+ edge, so a title that grows or disappears never moves it. */
24
+ .card {
25
+ display: flex;
26
+ flex-direction: column;
27
+ gap: 0;
28
+ margin: var(--card-space-1) 0;
29
+ overflow: hidden;
30
+ border: var(--card-edge) solid var(--dsw-alias-border-l2);
31
+ border-radius: var(--card-radius);
32
+ background: var(--dsw-alias-bg-layer-1);
33
+ }
34
+
35
+ .head {
36
+ display: flex;
37
+ align-items: center;
38
+ gap: var(--card-space-2);
39
+ min-height: calc(var(--card-title-line) + var(--card-space-2) * 2);
40
+ padding: var(--card-space-2) var(--card-space-3);
41
+ border-bottom: var(--card-edge) solid var(--dsw-alias-border-l2);
42
+ }
43
+
44
+ .title {
45
+ flex: 1 1 auto;
46
+ min-width: 0;
47
+ overflow: hidden;
48
+ color: var(--dsw-alias-label-primary);
49
+ font-size: var(--card-title-size);
50
+ line-height: var(--card-title-line);
51
+ text-overflow: ellipsis;
52
+ white-space: nowrap;
53
+ }
54
+
55
+ .badge {
56
+ flex: 0 0 auto;
57
+ margin-inline-start: auto;
58
+ color: var(--dsw-alias-label-secondary);
59
+ font-size: var(--card-state-size);
60
+ line-height: var(--card-state-line);
61
+ }
62
+
63
+ /* The frame is a block of its own: its height is measured inside the sandboxed
64
+ document and applied here, and the presenter's suggestion only covers the
65
+ first paint. */
66
+ .frame {
67
+ display: block;
68
+ width: 100%;
69
+ min-height: var(--card-default-height);
70
+ border: 0;
71
+ background: transparent;
72
+ }
73
+
74
+ .notice {
75
+ margin: 0;
76
+ padding: var(--card-space-2) var(--card-space-3);
77
+ border-top: var(--card-edge) solid var(--dsw-alias-border-l2);
78
+ color: var(--dsw-alias-label-secondary);
79
+ font-size: var(--card-state-size);
80
+ line-height: var(--card-state-line);
81
+ }
82
+
83
+ /* The neutral line of a call that carries no page: the keyed entry owns this
84
+ row, so it keeps a plain sentence rather than leaving the cell blank. */
85
+ .row {
86
+ margin: var(--card-space-1) 0;
87
+ }
@@ -30,6 +30,9 @@ import type { PairingService } from './pairing.ts'
30
30
  import type { PushNotifier } from './push.ts'
31
31
  import { pushEventOfTurnEnd } from './push.ts'
32
32
  import type { ListedQuestion, QuestionAnswerItem, QuestionClaims, QuestionListPayload } from './questions.ts'
33
+ import type { TurnEndQuietGate } from './turn-end-quiet.ts'
34
+ import { uiEventFits, uiEventOf } from './ui.ts'
35
+ import type { ListedCard, UiCards, UiListPayload } from './ui.ts'
33
36
  import {
34
37
  CAP_AGENTS,
35
38
  CAP_COMMANDS,
@@ -47,6 +50,8 @@ import {
47
50
  CAP_SESSION_SNAPSHOT_TRIM,
48
51
  CAP_SQUADS,
49
52
  CAP_SUBAGENT_THREAD,
53
+ CAP_UI,
54
+ CAP_UI_LIST,
50
55
  CAP_USAGE,
51
56
  CAP_USAGE_STATS,
52
57
  CAP_WORKSPACE,
@@ -63,6 +68,7 @@ import {
63
68
  CODE_SNAPSHOT_UNAVAILABLE,
64
69
  CODE_SQUADS_UNAVAILABLE,
65
70
  CODE_TOKEN_INVALID,
71
+ CODE_UI_LIST_UNAVAILABLE,
66
72
  CODE_UNKNOWN_METHOD,
67
73
  CODE_UNKNOWN_SESSION,
68
74
  CODE_UNPAIRED,
@@ -96,6 +102,8 @@ import {
96
102
  METHOD_SESSION_SNAPSHOT,
97
103
  METHOD_SESSION_TITLES,
98
104
  METHOD_SESSION_UNARCHIVE,
105
+ METHOD_UI_EVENT,
106
+ METHOD_UI_LIST,
99
107
  METHOD_SESSION_UNPIN,
100
108
  METHOD_SQUADS_LIST,
101
109
  METHOD_SQUADS_RUNS,
@@ -182,6 +190,11 @@ export interface BridgeConnectionOptions {
182
190
  readonly approvals: ApprovalRegistry
183
191
  /** Pending user questions: the claims this bridge holds and the answer path back to the host. */
184
192
  readonly questions: QuestionClaims
193
+ /**
194
+ * 整页卡(§35):`ui_present` 持有的每一张卡,`ui.event` 结算它们,`ui.list`
195
+ * 把它们念回去。与提问表平级、各自认领各自结算——两条通道互不改形状(§35.8)。
196
+ */
197
+ readonly ui: UiCards
185
198
  /** The host's background jobs: the read-only projection and the scopes this connection watches. */
186
199
  readonly jobs: JobRoster
187
200
  /** Process-local session metadata: live titles and the host's archive set. */
@@ -240,6 +253,15 @@ export interface BridgeConnectionOptions {
240
253
  * (§28.3, §29).
241
254
  */
242
255
  readonly liveActivity?: LiveActivityNotifier
256
+ /**
257
+ * The gate a finished turn is announced through (§28, §29).
258
+ *
259
+ * Absent is a bridge assembled without one — a suite, or an embedder — and then
260
+ * both channels report at the frame, exactly as they did before the gate
261
+ * existed. The mount always hands one, because it is the only assembly that can
262
+ * read the host's own answer.
263
+ */
264
+ readonly turnEndQuiet?: TurnEndQuietGate
243
265
  /**
244
266
  * Called after a registration changed the device table.
245
267
  *
@@ -257,6 +279,39 @@ export interface ConnectionAuth {
257
279
  readonly deviceId: string
258
280
  }
259
281
 
282
+ /**
283
+ * Whether one follow increment proves its session is working again.
284
+ *
285
+ * Deliberately narrow, and never "anything that is not a turn end": a parent's
286
+ * stream also carries a settled child's message (`source.kind` `subagent-settled`
287
+ * or `agent-message`, which the frames read as an agent actor), the usage count the
288
+ * host publishes as an assistant message finishes, and the catalog changes of the
289
+ * threads that session spawned. Reading any of those as a new turn would drop the
290
+ * turn end a waiting phone has not been told about yet — the one whose session is
291
+ * still busy with a running child, which is the case §28's gate exists for.
292
+ *
293
+ * One shared rule on purpose: this connection's own drain and the standing watchers
294
+ * both read it, so the two paths cannot disagree about what a new turn looks like.
295
+ * @param delta - one increment of a follow stream.
296
+ * @returns whether assistant work is streaming, or this session's own user wrote.
297
+ */
298
+ export function isTurnStartDelta(delta: { readonly kind: string; readonly actor?: { readonly kind?: string } }): boolean {
299
+ switch (delta.kind) {
300
+ case 'text':
301
+ case 'reasoning':
302
+ case 'tool-call':
303
+ case 'tool-result':
304
+ return true
305
+ case 'user-message':
306
+ // A message with no actor is not evidence: a durable log written before
307
+ // sources existed carries none, and guessing "human" there would drop a real
308
+ // announcement.
309
+ return delta.actor?.kind === 'human'
310
+ default:
311
+ return false
312
+ }
313
+ }
314
+
260
315
  /** The answer of a subscription's opening frame: a baseline, or why there is none. */
261
316
  type Opening = { readonly ok: true; readonly baseline: FollowBaseline } | { readonly ok: false; readonly code: string; readonly msg: string }
262
317
 
@@ -884,6 +939,16 @@ export class BridgeConnection {
884
939
  if (frame.m === METHOD_USAGE_STATS && !this.declares(CAP_USAGE_STATS)) {
885
940
  return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
886
941
  }
942
+ // 整页卡是 §35 的一条通道、一个能力:不宣告 `ui.v1` 的客户端看到的仍是它从前
943
+ // 看到的 `unknown-method`,本桥也不会替它把一条动作交给某个工具调用。
944
+ if (frame.m === METHOD_UI_EVENT && !this.declares(CAP_UI)) {
945
+ return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
946
+ }
947
+ // 对账读是它自己的能力,与 §24 同一判据:不宣告 `ui.list.v1` 的客户端读不到卡表,
948
+ // 本桥也不会替它翻一遍认领表。
949
+ if (frame.m === METHOD_UI_LIST && !this.declares(CAP_UI_LIST)) {
950
+ return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
951
+ }
887
952
  // Unconditional: a loopback Host buys nothing here. Without a device token
888
953
  // only the handshake and the two pairing steps run.
889
954
  if (!this.paired && !UNPAIRED_METHODS.has(frame.m)) return refusal(CODE_UNPAIRED, 'this connection is not paired')
@@ -911,6 +976,8 @@ export class BridgeConnection {
911
976
  case METHOD_APPROVAL_RESOLVE: return this.#approvalResolve(frame.p)
912
977
  case METHOD_QUESTION_ANSWER: return await this.#questionAnswer(frame.p)
913
978
  case METHOD_QUESTION_LIST: return this.#questionList(frame.p)
979
+ case METHOD_UI_EVENT: return this.#uiEvent(frame.p)
980
+ case METHOD_UI_LIST: return this.#uiList(frame.p)
914
981
  case METHOD_PUSH_REGISTER: return await this.#pushRegister(frame.p)
915
982
  case METHOD_USAGE_SESSION: return await this.#usageSession(frame.p)
916
983
  case METHOD_USAGE_BALANCE: return await this.#usageBalance(frame.p)
@@ -966,7 +1033,29 @@ export class BridgeConnection {
966
1033
  }
967
1034
  }
968
1035
 
969
- #hello(payload: Readonly<Record<string, unknown>>): DispatchOutcome { const proto = payload.proto
1036
+ /**
1037
+ * The capabilities this greeting advertises: the protocol's own, and every
1038
+ * capability a mounted extension currently requires a client to declare.
1039
+ *
1040
+ * Computed per greeting rather than held once, because a plugin may register
1041
+ * its table after this bridge was built — a name frozen at build time would
1042
+ * leave that surface invisible to every phone that ever connects. The
1043
+ * protocol's own names come first and keep their order, so a bridge with no
1044
+ * extension mounted advertises exactly the list it always did; extension
1045
+ * names follow in their registry's order. A name both halves know is listed
1046
+ * once.
1047
+ * @returns the served capabilities, one name each.
1048
+ */
1049
+ #servedCapabilities(): string[] {
1050
+ const capabilities = [...SERVED_CAPABILITIES]
1051
+ for (const capability of this.#options.extensions?.capabilities() ?? []) {
1052
+ if (!capabilities.includes(capability)) capabilities.push(capability)
1053
+ }
1054
+ return capabilities
1055
+ }
1056
+
1057
+ #hello(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
1058
+ const proto = payload.proto
970
1059
  if (proto !== PROTO) return refusal(CODE_PROTO_UNSUPPORTED, `this bridge speaks protocol ${PROTO}`)
971
1060
  this.#capabilities = capabilitiesOf(payload.cap)
972
1061
  // The frame form is decided where the frame is written, so the carrier is
@@ -981,7 +1070,7 @@ export class BridgeConnection {
981
1070
  proto: PROTO,
982
1071
  minor: MINOR,
983
1072
  server: SERVER_ID,
984
- capabilities: [...SERVED_CAPABILITIES],
1073
+ capabilities: this.#servedCapabilities(),
985
1074
  resume: 'snapshot',
986
1075
  auth: this.paired ? 'paired' : 'unpaired',
987
1076
  },
@@ -2073,6 +2162,61 @@ export class BridgeConnection {
2073
2162
  return { ok: true, r: answer }
2074
2163
  }
2075
2164
 
2165
+ /**
2166
+ * Answer one `ui.event`: the first action a user took inside a presented page
2167
+ * (§35.3).
2168
+ *
2169
+ * The event is carried and never interpreted — `type` is the presenter's own
2170
+ * closed set, so this bridge does not validate its value, refuse an unknown one
2171
+ * or rewrite it. A card this bridge never claimed, or one that was settled
2172
+ * elsewhere, is refused `ui-unknown`; a card whose own first event already
2173
+ * settled it is refused `ui-settled`, because a repeated tap and a nonexistent
2174
+ * card are two different answers. The payload is measured here rather than on the
2175
+ * client: a refusal on that side would leave the agent waiting for a card that
2176
+ * will never settle (§35.2's rule, one channel over).
2177
+ * @param payload - `{sessionId, callId, event:{type, payload?}}`.
2178
+ */
2179
+ #uiEvent(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
2180
+ const sessionId = stringArg(payload, 'sessionId')
2181
+ const callId = stringArg(payload, 'callId')
2182
+ const event = uiEventOf(payload.event)
2183
+ if (sessionId === undefined || callId === undefined || event === undefined) {
2184
+ return refusal(CODE_INVALID_ARGS, 'ui.event requires sessionId, callId and event of {type, payload?}')
2185
+ }
2186
+ if (!uiEventFits(event)) return refusal(CODE_INVALID_ARGS, 'ui.event payload is over the 8 KiB cap')
2187
+ const reply = this.#options.ui.settle(sessionId, callId, event)
2188
+ return reply.ok ? { ok: true, r: { ok: true } } : refusal(reply.code, reply.msg)
2189
+ }
2190
+
2191
+ /**
2192
+ * Answer one `ui.list`: the cards this bridge is still holding (§35.4).
2193
+ *
2194
+ * A pure read — it claims nothing, moves no deadline, triggers no settlement and
2195
+ * writes no host state — because its whole purpose is to let a client that was
2196
+ * disconnected reconcile the cards it already holds. `settled` never appears in
2197
+ * it: the list's definition is "still held", and a settled card is a notice the
2198
+ * host already sent, not a row.
2199
+ *
2200
+ * Only a COMPLETE list may retire a card on the client, so a registry this bridge
2201
+ * cannot read answers `ui-list-unavailable` rather than an empty list: an
2202
+ * unreadable set is not an empty one.
2203
+ * @param payload - must be the empty object: the held set is global, not scoped.
2204
+ */
2205
+ #uiList(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
2206
+ if (Object.keys(payload).length > 0) {
2207
+ return refusal(CODE_INVALID_ARGS, 'ui.list takes no arguments')
2208
+ }
2209
+ let cards: readonly ListedCard[]
2210
+ try {
2211
+ cards = this.#options.ui.listed()
2212
+ } catch (error) {
2213
+ this.#options.log(`ui.list could not read the held cards: ${failureText(error)}`)
2214
+ return refusal(CODE_UI_LIST_UNAVAILABLE, 'this bridge could not read the cards it is holding')
2215
+ }
2216
+ const answer: UiListPayload = { cards, complete: true }
2217
+ return { ok: true, r: answer }
2218
+ }
2219
+
2076
2220
  /**
2077
2221
  * The body of `push.register` (protocol §28.3).
2078
2222
  *
@@ -2441,10 +2585,11 @@ export class BridgeConnection {
2441
2585
  // know. The call returns before anything is sent and swallows its own
2442
2586
  // failures: the frame above is already gone, and a notification is not
2443
2587
  // worth a delayed or aborted stream (protocol §28.5).
2444
- if (delta.kind === 'turn-end') {
2445
- this.#options.push?.notify(pushEventOfTurnEnd(delta.reason), subscription.sessionId)
2446
- this.#options.liveActivity?.noteTurnEnd(subscription.sessionId, delta.reason)
2447
- }
2588
+ if (delta.kind === 'turn-end') this.#announceTurnEnd(subscription.sessionId, delta.reason)
2589
+ // Only an increment that proves this session's own work proves a new turn; a
2590
+ // settled child, a usage count and a catalog change all arrive here without
2591
+ // meaning the user prompted again.
2592
+ else if (isTurnStartDelta(delta)) this.#options.turnEndQuiet?.noteTurnStarted(subscription.sessionId)
2448
2593
  }
2449
2594
  } catch (error) {
2450
2595
  if (!subscription.controller.signal.aborted) {
@@ -2455,6 +2600,24 @@ export class BridgeConnection {
2455
2600
  }
2456
2601
  }
2457
2602
 
2603
+ /**
2604
+ * Hand one finished turn to the channel that announces it.
2605
+ *
2606
+ * The gate holds it until the session is quiet (§28, §29); a connection built
2607
+ * without one has no host answer to wait for and reports at the frame.
2608
+ * @param sessionId - the session the turn belonged to.
2609
+ * @param reason - the host's own reason for ending it.
2610
+ */
2611
+ #announceTurnEnd(sessionId: string, reason: string): void {
2612
+ const gate = this.#options.turnEndQuiet
2613
+ if (gate !== undefined) {
2614
+ gate.noteTurnEnd(sessionId, reason)
2615
+ return
2616
+ }
2617
+ this.#options.push?.notify(pushEventOfTurnEnd(reason), sessionId)
2618
+ this.#options.liveActivity?.noteTurnEnd(sessionId, reason)
2619
+ }
2620
+
2458
2621
  /** Await a subscription's opening frame under a bounded wait. */
2459
2622
  async #awaitOpening(subscription: Subscription): Promise<Opening> {
2460
2623
  let timer: NodeJS.Timeout | undefined
@@ -176,12 +176,34 @@ function isStoredDevice(value: unknown): value is StoredDevice {
176
176
  && typeof row.lastSeenAt === 'number'
177
177
  }
178
178
 
179
+ /**
180
+ * Which of several rows for one phone is the one that survives.
181
+ *
182
+ * The most recently seen row wins and a tie is settled by the later
183
+ * `createdAt`: a pairing refreshes `lastSeenAt` on the row that is actually on
184
+ * the wire, so that is the row holding the credential in use.
185
+ * @param rows - rows that share one fingerprint.
186
+ * @returns the row to keep, or undefined when there is none.
187
+ */
188
+ function survivorOf(rows: readonly StoredDevice[]): StoredDevice | undefined {
189
+ let survivor: StoredDevice | undefined
190
+ for (const row of rows) {
191
+ if (survivor === undefined || row.lastSeenAt > survivor.lastSeenAt
192
+ || (row.lastSeenAt === survivor.lastSeenAt && row.createdAt > survivor.createdAt)) survivor = row
193
+ }
194
+ return survivor
195
+ }
196
+
179
197
  /**
180
198
  * The persisted, revocable device roster.
181
199
  *
182
200
  * Revocation is a file edit: protocol v1 has no revoke method, so an operator
183
201
  * removes the row (or deletes the file) and restarts. The in-memory copy is
184
202
  * loaded once per process.
203
+ *
204
+ * One phone is one row. Pairing again replaces the credential on the row the
205
+ * phone already has instead of adding a second one, and a table that still
206
+ * carries duplicates is compacted when it is read.
185
207
  */
186
208
  export class DeviceRoster {
187
209
  readonly #file: string
@@ -242,12 +264,28 @@ export class DeviceRoster {
242
264
  if (!isP256Spki(pubKey)) return undefined
243
265
  const fingerprint = fingerprintOfSpki(pubKey)
244
266
  if (fingerprint === undefined) return undefined
267
+ // Pairing again is a new credential for a phone that is already here, not a
268
+ // second phone: the same public key is the same fingerprint, so the rows it
269
+ // already owns are settled first, the newest one kept and the rest dropped.
270
+ const sameDevice = [...this.#devices.values()].filter(row => row.fingerprint === fingerprint)
271
+ for (const row of sameDevice) this.#devices.delete(row.tokenHash)
272
+ const survivor = survivorOf(sameDevice)
245
273
  const now = this.#now()
246
274
  const deviceId = `dev_${randomBase64Url(DEVICE_ID_BYTES)}`
247
275
  const token = base64UrlEncode(randomBytes(DEVICE_TOKEN_BYTES))
248
- this.#devices.set(tokenHash(token), { deviceId, pubKey, fingerprint, createdAt: now, lastSeenAt: now, tokenHash: tokenHash(token) })
276
+ const hash = tokenHash(token)
277
+ if (survivor === undefined) {
278
+ this.#devices.set(hash, { deviceId, pubKey, fingerprint, createdAt: now, lastSeenAt: now, tokenHash: hash })
279
+ await this.#persist()
280
+ return { deviceId, deviceToken: token }
281
+ }
282
+ // The row keeps its id, its creation time and its registration; only the
283
+ // credential moves. The old map key went with the old token, so the token
284
+ // this phone was issued before the pairing no longer authenticates it.
285
+ const { tokenHash: _retired, ...kept } = survivor
286
+ this.#devices.set(hash, { ...kept, lastSeenAt: now, tokenHash: hash })
249
287
  await this.#persist()
250
- return { deviceId, deviceToken: token }
288
+ return { deviceId: kept.deviceId, deviceToken: token }
251
289
  }
252
290
 
253
291
  /** Record that a device just reconnected; the file is refreshed at most once per call. */
@@ -345,6 +383,78 @@ export class DeviceRoster {
345
383
  return targets
346
384
  }
347
385
 
386
+ /**
387
+ * Collapse what earlier enrollments left behind, in memory.
388
+ *
389
+ * Two rules, both saying one phone is one row. Rows are collapsed to one per
390
+ * fingerprint first, because a table written before `enroll` reused a row
391
+ * carries a row per pairing. Then an APNs token is kept on the row that
392
+ * registered it last: a token belongs to the app install, so every other row
393
+ * holding it is the same phone and would be a second delivery of the same
394
+ * event. A row that loses its registration keeps its identity and simply asks
395
+ * for no notification, exactly as {@link removePush} leaves it.
396
+ * @returns how many rows and registrations this pass retired.
397
+ */
398
+ #compact(): { readonly rows: number; readonly registrations: number } {
399
+ const phones = new Map<string, StoredDevice[]>()
400
+ for (const row of this.#devices.values()) {
401
+ const held = phones.get(row.fingerprint)
402
+ if (held === undefined) phones.set(row.fingerprint, [row])
403
+ else held.push(row)
404
+ }
405
+ let rows = 0
406
+ for (const held of phones.values()) {
407
+ if (held.length < 2) continue
408
+ const survivor = survivorOf(held)
409
+ if (survivor === undefined) continue
410
+ for (const row of held) {
411
+ if (row === survivor) continue
412
+ this.#devices.delete(row.tokenHash)
413
+ rows += 1
414
+ }
415
+ if (survivor.push !== undefined) continue
416
+ // A survivor that never registered takes the newest registration one of
417
+ // its dropped rows carried: same phone, same install, same tokens.
418
+ let newest: PushRegistration | undefined
419
+ for (const row of held) {
420
+ if (row === survivor || row.push === undefined) continue
421
+ if (newest === undefined || row.push.registeredAt > newest.registeredAt) newest = row.push
422
+ }
423
+ if (newest !== undefined) this.#devices.set(survivor.tokenHash, { ...survivor, push: newest })
424
+ }
425
+ const holders = new Map<string, StoredDevice[]>()
426
+ for (const row of this.#devices.values()) {
427
+ const token = row.push?.deviceToken
428
+ if (token === undefined) continue
429
+ const held = holders.get(token)
430
+ if (held === undefined) holders.set(token, [row])
431
+ else held.push(row)
432
+ }
433
+ let registrations = 0
434
+ for (const held of holders.values()) {
435
+ if (held.length < 2) continue
436
+ const keeper = held.reduce((best, row) => (row.push?.registeredAt ?? 0) > (best.push?.registeredAt ?? 0) ? row : best)
437
+ for (const row of held) {
438
+ if (row === keeper) continue
439
+ if (this.#retirePush(row.tokenHash)) registrations += 1
440
+ }
441
+ }
442
+ return { rows, registrations }
443
+ }
444
+
445
+ /**
446
+ * Drop one row's registration and keep its identity.
447
+ * @param hash - the map key of the row holding it.
448
+ * @returns whether the row carried a registration to drop.
449
+ */
450
+ #retirePush(hash: string): boolean {
451
+ const row = this.#devices.get(hash)
452
+ if (row === undefined || row.push === undefined) return false
453
+ const { push: _dropped, ...rest } = row
454
+ this.#devices.set(hash, rest)
455
+ return true
456
+ }
457
+
348
458
  async #read(): Promise<void> {
349
459
  let text: string
350
460
  try {
@@ -382,6 +492,10 @@ export class DeviceRoster {
382
492
  this.#devices.set(row.tokenHash, push === undefined ? rest : { ...rest, push })
383
493
  }
384
494
  this.#log(`device roster ${this.#file}: ${rows.length} paired device(s)`)
495
+ const compacted = this.#compact()
496
+ if (compacted.rows === 0 && compacted.registrations === 0) return
497
+ this.#log(`device roster ${this.#file}: compacted ${compacted.rows} duplicate row(s), retired ${compacted.registrations} stale registration(s)`)
498
+ await this.#persist()
385
499
  }
386
500
 
387
501
  /** Move a corrupt roster aside so the failure survives and the next write cannot erase it. */
@@ -157,6 +157,26 @@ export class RemoteBridgeRegistry {
157
157
  return this.#methods.has(method)
158
158
  }
159
159
 
160
+ /**
161
+ * The capabilities the registered tables require a client to declare.
162
+ *
163
+ * A table registered without a capability contributes none: nothing gates its
164
+ * methods, so there is nothing for a client to announce. A name stays listed
165
+ * while any registered method still requires it, so withdrawing one table
166
+ * withdraws its capability only when it was the last one holding it. Sorted,
167
+ * because this answer travels on the wire: one set must read the same way
168
+ * whatever order the plugins happened to mount in.
169
+ * @returns the distinct non-blank capabilities, ascending; empty when no
170
+ * extension is registered.
171
+ */
172
+ capabilities(): readonly string[] {
173
+ const names = new Set<string>()
174
+ for (const entry of this.#methods.values()) {
175
+ if (entry.capability !== undefined && entry.capability.trim() !== '') names.add(entry.capability)
176
+ }
177
+ return [...names].sort()
178
+ }
179
+
160
180
  /**
161
181
  * @param method - the method name a client asked for.
162
182
  * @param declares - whether the calling connection declared a capability.