@linxin666/dsh-remote-bridge 0.4.8 → 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 (72) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +75 -18
  3. package/README.zh.md +74 -18
  4. package/lib/client.js +783 -260
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +15849 -2913
  7. package/lib/types/client/PairEntry.d.ts +2 -2
  8. package/lib/types/client/PairPanel.d.ts +10 -2
  9. package/lib/types/client/UiPresentRow.d.ts +13 -0
  10. package/lib/types/client/icons.d.ts +5 -13
  11. package/lib/types/client/index.d.ts +4 -0
  12. package/lib/types/client/locales.d.ts +24 -15
  13. package/lib/types/client/semantic.d.ts +9 -5
  14. package/lib/types/client/toolview-slot.d.ts +68 -0
  15. package/lib/types/client/ui-card.d.ts +160 -0
  16. package/lib/types/core/commands.d.ts +59 -0
  17. package/lib/types/core/connection.d.ts +106 -0
  18. package/lib/types/core/devices.d.ts +102 -2
  19. package/lib/types/core/extension.d.ts +13 -0
  20. package/lib/types/core/hub.d.ts +129 -15
  21. package/lib/types/core/liveactivity.d.ts +324 -0
  22. package/lib/types/core/protocol.d.ts +328 -5
  23. package/lib/types/core/push.d.ts +186 -0
  24. package/lib/types/core/questions.d.ts +61 -9
  25. package/lib/types/core/session-meta.d.ts +55 -1
  26. package/lib/types/core/squads.d.ts +130 -0
  27. package/lib/types/core/turn-end-quiet.d.ts +135 -0
  28. package/lib/types/core/ui.d.ts +238 -0
  29. package/lib/types/core/usage-stats.d.ts +160 -0
  30. package/lib/types/core/usage.d.ts +294 -0
  31. package/lib/types/host/apns.d.ts +151 -0
  32. package/lib/types/host/squads-ledger.d.ts +39 -0
  33. package/lib/types/host/squads.d.ts +77 -0
  34. package/lib/types/host/ui-tools.d.ts +80 -0
  35. package/lib/types/host/usage-stats.d.ts +75 -0
  36. package/lib/types/host/watchers.d.ts +95 -0
  37. package/lib/types/index.d.ts +47 -3
  38. package/package.json +15 -14
  39. package/src/client/PairEntry.tsx +58 -31
  40. package/src/client/PairPanel.tsx +181 -97
  41. package/src/client/UiPresentRow.tsx +149 -0
  42. package/src/client/icons.tsx +17 -60
  43. package/src/client/index.ts +11 -0
  44. package/src/client/locales.ts +36 -24
  45. package/src/client/panel.module.css +239 -186
  46. package/src/client/semantic.ts +10 -6
  47. package/src/client/toolview-slot.ts +84 -0
  48. package/src/client/ui-card.ts +368 -0
  49. package/src/client/ui-present.module.css +87 -0
  50. package/src/core/commands.ts +95 -0
  51. package/src/core/connection.ts +811 -12
  52. package/src/core/devices.ts +337 -5
  53. package/src/core/extension.ts +20 -0
  54. package/src/core/hub.ts +518 -43
  55. package/src/core/liveactivity.ts +833 -0
  56. package/src/core/protocol.ts +370 -5
  57. package/src/core/push.ts +385 -0
  58. package/src/core/questions.ts +81 -10
  59. package/src/core/session-meta.ts +73 -1
  60. package/src/core/squads.ts +345 -0
  61. package/src/core/turn-end-quiet.ts +388 -0
  62. package/src/core/ui.ts +398 -0
  63. package/src/core/usage-stats.ts +424 -0
  64. package/src/core/usage.ts +937 -0
  65. package/src/core/wire.ts +8 -0
  66. package/src/host/apns.ts +320 -0
  67. package/src/host/squads-ledger.ts +105 -0
  68. package/src/host/squads.ts +206 -0
  69. package/src/host/ui-tools.ts +233 -0
  70. package/src/host/usage-stats.ts +155 -0
  71. package/src/host/watchers.ts +296 -0
  72. package/src/index.ts +327 -10
@@ -0,0 +1,385 @@
1
+ /**
2
+ * What this bridge tells a phone that is not listening.
3
+ *
4
+ * Every fact a phone needs already has a read on the wire — a roster, a
5
+ * baseline, a question list — and a notification is not one of them. It is the
6
+ * `turn ended` or `something is waiting` event, delivered by APNs to a device
7
+ * whose socket is closed, and nothing else: this module deliberately holds no
8
+ * session state, publishes no topic, and answers no method. A client that acts
9
+ * on a notification still has to read the fact behind it (protocol §28).
10
+ *
11
+ * Three rules live here, so the sender beside it cannot disagree about them:
12
+ *
13
+ * - the payload carries a session's NAME, its workspace's short name, the state
14
+ * and one deep link. Never a message, a tool output, a file name or a
15
+ * question's body — a notification crosses Apple's servers and sits on a lock
16
+ * screen, which is the last place session content should be;
17
+ * - the same `(sessionId, event)` inside {@link PUSH_DEDUPE_MS} is one
18
+ * notification, because two phones following one session both see the same
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;
22
+ * - a failed delivery is logged and dropped. Nothing here is awaited by the
23
+ * delta path, so a broken APNs connection cannot delay, reorder or suppress a
24
+ * frame that a connected phone is waiting for.
25
+ * @module dsh-remote-bridge/core/push
26
+ */
27
+
28
+ import { basename } from 'node:path'
29
+
30
+ /** One thing a notification can be about. */
31
+ export type PushEvent = 'turn-end' | 'turn-error' | 'question' | 'approval'
32
+
33
+ /** Window inside which the same `(sessionId, event)` is one notification. */
34
+ export const PUSH_DEDUPE_MS = 30_000
35
+ /** Shortest gap between two notifications about the same session. */
36
+ export const PUSH_SESSION_INTERVAL_MS = 10_000
37
+ /** Most notifications this bridge sends in any rolling minute. */
38
+ export const PUSH_GLOBAL_PER_MINUTE = 30
39
+ /** Sessions whose workspace short name is remembered for the payload. */
40
+ export const PUSH_WORKSPACE_LIMIT = 512
41
+ /** The only deep-link form this channel emits. */
42
+ export const PUSH_DEEP_LINK_PREFIX = 'whale://session/'
43
+
44
+ /**
45
+ * The status line each event carries.
46
+ *
47
+ * Fixed strings on purpose: a body built out of host text would be session
48
+ * content wearing a notification's clothes, and the whole point of this channel
49
+ * is that it carries none.
50
+ */
51
+ const PUSH_BODY: Readonly<Record<PushEvent, string>> = {
52
+ 'turn-end': '回合结束',
53
+ 'turn-error': '回合异常结束',
54
+ question: '有待回答的问题',
55
+ approval: '有待确认的审批',
56
+ }
57
+
58
+ /** One device a notification can be addressed to. */
59
+ export interface PushAddress {
60
+ readonly deviceToken: string
61
+ readonly environment: 'sandbox' | 'production'
62
+ readonly bundle: string
63
+ readonly locale?: string
64
+ }
65
+
66
+ /** The request body one APNs delivery carries (protocol §28.4). */
67
+ export interface PushNotification {
68
+ readonly aps: {
69
+ readonly alert: { readonly title: string; readonly body: string }
70
+ readonly sound: 'default'
71
+ }
72
+ /** Workspace short name; absent when this bridge cannot resolve one. */
73
+ readonly w?: string
74
+ readonly s: string
75
+ readonly st: PushEvent
76
+ readonly url: string
77
+ }
78
+
79
+ /** What one delivery attempt reported. */
80
+ export interface PushSendResult {
81
+ readonly ok: boolean
82
+ /** The status APNs answered, when it answered at all. */
83
+ readonly status?: number
84
+ /** The reason APNs named, or this bridge's own note. */
85
+ readonly reason?: string
86
+ }
87
+
88
+ /** One delivery a sender refused, in the words the bridge needs to read it. */
89
+ export interface PushDeliveryFailure {
90
+ /** The registration APNs refused: the roster row holding it is a device that no longer exists. */
91
+ readonly deviceToken: string
92
+ /** The status APNs answered, when it answered at all. */
93
+ readonly status?: number
94
+ /** The reason APNs named, or this bridge's own note. */
95
+ readonly reason?: string
96
+ }
97
+
98
+ /** What one {@link PushNotifier.notify} ended up doing, once every attempt settled. */
99
+ export interface PushDeliveryReport {
100
+ /** How many devices took the notification. */
101
+ readonly delivered: number
102
+ /** Every attempt that did not land, in target order. */
103
+ readonly failures: readonly PushDeliveryFailure[]
104
+ }
105
+
106
+ /**
107
+ * @param failure - one refused delivery.
108
+ * @returns whether the registration behind it is dead for good.
109
+ *
110
+ * APNs says a token will never work again in three ways: 410 with
111
+ * `Unregistered`, and 400 with `Unregistered` or `BadDeviceToken`. All three are
112
+ * final facts about the registration — the app was removed, or this token belongs
113
+ * to another environment or bundle — so it is cleaned up instead of retried, and
114
+ * a claim held for it is a claim held for a phone that cannot come back.
115
+ */
116
+ export function isDeadPushToken(failure: PushDeliveryFailure): boolean {
117
+ const reason = failure.reason ?? ''
118
+ if (reason === 'Unregistered' || reason === 'BadDeviceToken') return true
119
+ return failure.status === 410
120
+ }
121
+
122
+ /** Whatever actually reaches a device; the APNs client implements this. */
123
+ export interface PushSender {
124
+ send(target: PushAddress, notification: PushNotification): Promise<PushSendResult>
125
+ }
126
+
127
+ /** What the payload builder may say about one session. */
128
+ export interface PushLabels {
129
+ readonly title?: string
130
+ readonly workspace?: string
131
+ }
132
+
133
+ export interface PushNotifierOptions {
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
+ */
141
+ readonly targets: () => readonly PushAddress[]
142
+ /** The sender; absent is a bridge with no signing key, and then nothing happens. */
143
+ readonly sender?: PushSender
144
+ /** The session's own title (§26's source), read per event. */
145
+ readonly titles?: (sessionId: string) => string | undefined
146
+ readonly now?: () => number
147
+ readonly log?: (message: string) => void
148
+ readonly dedupeMs?: number
149
+ readonly sessionIntervalMs?: number
150
+ readonly globalPerMinute?: number
151
+ }
152
+
153
+ /**
154
+ * The notification the channel sends for one event (protocol §28.4).
155
+ *
156
+ * Pure, and exported so the shape can be asserted without a sender: the keys
157
+ * are the contract, and the absence of any body text is the property that
158
+ * matters most.
159
+ * @param event - what happened.
160
+ * @param sessionId - the session it happened to.
161
+ * @param labels - the name and workspace short name, when the bridge holds them.
162
+ * @returns the exact payload an APNs delivery carries.
163
+ */
164
+ export function buildPushNotification(event: PushEvent, sessionId: string, labels: PushLabels = {}): PushNotification {
165
+ const named = labels.title !== undefined && labels.title !== ''
166
+ return {
167
+ aps: {
168
+ alert: { title: named ? labels.title as string : PUSH_BODY[event], body: PUSH_BODY[event] },
169
+ sound: 'default',
170
+ },
171
+ ...(labels.workspace === undefined || labels.workspace === '' ? {} : { w: labels.workspace }),
172
+ s: sessionId,
173
+ st: event,
174
+ url: `${PUSH_DEEP_LINK_PREFIX}${sessionId}`,
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Which event one `turn-end` delta is.
180
+ * @param reason - the host's own reason for ending the turn.
181
+ * @returns the normal end for `completed`, the abnormal one for every other
182
+ * value — including `unknown`, which is what an unreadable reason reports.
183
+ */
184
+ export function pushEventOfTurnEnd(reason: string): PushEvent {
185
+ return reason === 'completed' ? 'turn-end' : 'turn-error'
186
+ }
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
+
208
+ /**
209
+ * The bridge's outbound notification path.
210
+ *
211
+ * Deliberately inert when no sender is configured: {@link enabled} is false, no
212
+ * target is ever read and no clock is ever consulted, so an unconfigured bridge
213
+ * behaves — byte for byte, frame for frame — exactly as it did before this
214
+ * channel existed.
215
+ */
216
+ export class PushNotifier {
217
+ readonly #options: PushNotifierOptions
218
+ readonly #now: () => number
219
+ readonly #log: (message: string) => void
220
+ /** Last send per `(sessionId, event)`. */
221
+ readonly #dedupe = new Map<string, number>()
222
+ /** Last send per session, whatever the event. */
223
+ readonly #sessions = new Map<string, number>()
224
+ /** Send timestamps inside the rolling minute. */
225
+ #recent: number[] = []
226
+ /** Session id to workspace short name, as the roster rows this bridge served reported it. */
227
+ readonly #workspaces = new Map<string, string>()
228
+
229
+ constructor(options: PushNotifierOptions) {
230
+ this.#options = options
231
+ this.#now = options.now ?? (() => Date.now())
232
+ this.#log = options.log ?? (() => undefined)
233
+ }
234
+
235
+ /** @returns whether this bridge will actually deliver anything. */
236
+ get enabled(): boolean {
237
+ return this.#options.sender !== undefined
238
+ }
239
+
240
+ /**
241
+ * Remember the workspace each session belongs to, from a roster this bridge
242
+ * just served.
243
+ *
244
+ * A notification's `w` is the only label the bridge cannot read from the
245
+ * title service, and asking the host for a roster on every turn end would put
246
+ * a gateway call on the notification path. The rows are already in hand when a
247
+ * phone lists them, so the short name is picked up there and kept bounded; a
248
+ * session never listed simply gets a payload without `w`.
249
+ * @param rows - the roster rows that were just built for a client.
250
+ */
251
+ noteSessions(rows: readonly { readonly id: string; readonly cwd?: string }[]): void {
252
+ if (!this.enabled) return
253
+ for (const row of rows) {
254
+ if (row.cwd === undefined || row.cwd === '') continue
255
+ const short = basename(row.cwd)
256
+ if (short === '') continue
257
+ this.#workspaces.delete(row.id)
258
+ this.#workspaces.set(row.id, short)
259
+ }
260
+ while (this.#workspaces.size > PUSH_WORKSPACE_LIMIT) {
261
+ const oldest = this.#workspaces.keys().next()
262
+ if (oldest.done === true) break
263
+ this.#workspaces.delete(oldest.value)
264
+ }
265
+ }
266
+
267
+ /**
268
+ * Announce one event to every registered device.
269
+ *
270
+ * Returns before anything is sent: delivery starts on a fresh microtask, so a
271
+ * caller on the delta path never awaits an APNs round trip and a sender that
272
+ * throws cannot reach it.
273
+ * @param event - what happened.
274
+ * @param sessionId - the session it happened to.
275
+ * @param onReport - receives how the announcement ended, once every attempt has
276
+ * settled. A caller that held something for a phone — an offline claim (§32) —
277
+ * needs to know whether any phone was actually told, and may not block the
278
+ * caller's own path on an APNs round trip to find out. Not called when nothing
279
+ * was attempted: no sender, no target, or a rate limit that dropped this event.
280
+ */
281
+ notify(event: PushEvent, sessionId: string, onReport?: (report: PushDeliveryReport) => void): void {
282
+ if (this.#options.sender === undefined) return
283
+ try {
284
+ this.#announce(event, sessionId, onReport)
285
+ } catch (error) {
286
+ // The caller is a frame path — a delta broadcast or a claim — and a
287
+ // notification that cannot even be built must not end a follow stream.
288
+ this.#log(`push ${event} for ${sessionId} could not be prepared: ${String(error)}`)
289
+ }
290
+ }
291
+
292
+ /** Build and start one event's deliveries. */
293
+ #announce(event: PushEvent, sessionId: string, onReport?: (report: PushDeliveryReport) => void): void {
294
+ const sender = this.#options.sender
295
+ if (sender === undefined) return
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())
300
+ if (targets.length === 0) return
301
+ const now = this.#now()
302
+ if (!this.#admit(event, sessionId, now)) return
303
+ const notification = buildPushNotification(event, sessionId, this.#labelsOf(sessionId))
304
+ const failures: PushDeliveryFailure[] = []
305
+ let delivered = 0
306
+ let pending = targets.length
307
+ // One report per announcement, after the last attempt settled: a half-read
308
+ // count is worse than none, because the caller acts on it.
309
+ const settleOne = (failure: PushDeliveryFailure | undefined): void => {
310
+ if (failure === undefined) delivered += 1
311
+ else failures.push(failure)
312
+ pending -= 1
313
+ if (pending > 0 || onReport === undefined) return
314
+ try {
315
+ onReport({ delivered, failures })
316
+ } catch (error) {
317
+ this.#log(`push ${event} for ${sessionId} could not be reported: ${String(error)}`)
318
+ }
319
+ }
320
+ for (const target of targets) {
321
+ void Promise.resolve()
322
+ .then(async () => await sender.send(target, notification))
323
+ .then((result) => {
324
+ if (result.ok) {
325
+ settleOne(undefined)
326
+ return
327
+ }
328
+ this.#log(`push ${event} for ${sessionId} was not delivered (${result.status ?? '-'} ${result.reason ?? 'no reason'})`)
329
+ settleOne({
330
+ deviceToken: target.deviceToken,
331
+ ...(result.status === undefined ? {} : { status: result.status }),
332
+ ...(result.reason === undefined ? {} : { reason: result.reason }),
333
+ })
334
+ })
335
+ .catch((error: unknown) => {
336
+ this.#log(`push ${event} for ${sessionId} failed: ${String(error)}`)
337
+ settleOne({ deviceToken: target.deviceToken })
338
+ })
339
+ }
340
+ }
341
+
342
+ /** @returns whether this event may be sent now; records the send when it may. */
343
+ #admit(event: PushEvent, sessionId: string, now: number): boolean {
344
+ const dedupeMs = this.#options.dedupeMs ?? PUSH_DEDUPE_MS
345
+ const sessionMs = this.#options.sessionIntervalMs ?? PUSH_SESSION_INTERVAL_MS
346
+ const perMinute = this.#options.globalPerMinute ?? PUSH_GLOBAL_PER_MINUTE
347
+ this.#prune(now, dedupeMs)
348
+ const key = `${sessionId}|${event}`
349
+ const lastSame = this.#dedupe.get(key)
350
+ if (lastSame !== undefined && now - lastSame < dedupeMs) return false
351
+ const lastSession = this.#sessions.get(sessionId)
352
+ if (lastSession !== undefined && now - lastSession < sessionMs) return false
353
+ this.#recent = this.#recent.filter(at => now - at < 60_000)
354
+ if (this.#recent.length >= perMinute) return false
355
+ this.#dedupe.set(key, now)
356
+ this.#sessions.set(sessionId, now)
357
+ this.#recent.push(now)
358
+ return true
359
+ }
360
+
361
+ /** Forget entries that can no longer suppress anything. */
362
+ #prune(now: number, dedupeMs: number): void {
363
+ if (this.#dedupe.size > 256) {
364
+ for (const [key, at] of this.#dedupe) if (now - at >= dedupeMs) this.#dedupe.delete(key)
365
+ }
366
+ if (this.#sessions.size > 256) {
367
+ const sessionMs = this.#options.sessionIntervalMs ?? PUSH_SESSION_INTERVAL_MS
368
+ for (const [id, at] of this.#sessions) if (now - at >= sessionMs) this.#sessions.delete(id)
369
+ }
370
+ }
371
+
372
+ #labelsOf(sessionId: string): PushLabels {
373
+ let title: string | undefined
374
+ try {
375
+ title = this.#options.titles?.(sessionId)
376
+ } catch {
377
+ title = undefined
378
+ }
379
+ const workspace = this.#workspaces.get(sessionId)
380
+ return {
381
+ ...(title === undefined || title === '' ? {} : { title }),
382
+ ...(workspace === undefined ? {} : { workspace }),
383
+ }
384
+ }
385
+ }
@@ -76,12 +76,73 @@ export interface QuestionAnswer {
76
76
  readonly answers: readonly QuestionAnswerItem[]
77
77
  }
78
78
 
79
+ /**
80
+ * The `question.request` payload for one claim, and the `payload` of every
81
+ * `question.list` entry.
82
+ *
83
+ * One function for both so the card a phone was handed and the card it reads back
84
+ * out of a list cannot drift apart: `expiresAt` appears only once the claim
85
+ * learned the host's own deadline, and a blocking ask publishes no such key at
86
+ * all rather than an empty or null one.
87
+ * @param state - whether the foreground ask still holds the question.
88
+ * @param question - the claim being published.
89
+ * @returns the frozen payload body.
90
+ */
91
+ export function questionPayload(state: QuestionState, question: ClaimedQuestionView): QuestionRequestPayload {
92
+ return {
93
+ sessionId: question.sessionId,
94
+ callId: question.callId,
95
+ state,
96
+ questions: question.questions,
97
+ ...(question.expiresAt === undefined ? {} : { expiresAt: question.expiresAt }),
98
+ }
99
+ }
100
+
101
+ /**
102
+ * The identity a client knows one question card by.
103
+ *
104
+ * The same `sessionId/callId` pair the phone already derives for its own card,
105
+ * so a list entry and the card it describes are compared as one name instead of
106
+ * two fields that could be recombined differently on each side.
107
+ * @param sessionId - the session that asked.
108
+ * @param callId - the wire call id the client answers with.
109
+ * @returns the card key.
110
+ */
111
+ export function questionKey(sessionId: string, callId: string): string {
112
+ return sessionId + '/' + callId
113
+ }
114
+
115
+ /** One question this bridge still holds, as `question.list` publishes it. */
116
+ export interface ListedQuestion {
117
+ /** {@link questionKey}: the card identity the client holds it under. */
118
+ readonly key: string
119
+ readonly sessionId: string
120
+ /** `open` or `continued`; a settled question is not held and never listed. */
121
+ readonly state: QuestionState
122
+ /** The `question.request` payload, byte for byte the shape that channel froze. */
123
+ readonly payload: QuestionRequestPayload
124
+ }
125
+
126
+ /**
127
+ * The body of one `question.list` answer.
128
+ *
129
+ * `complete` is what a client is allowed to act on: only a complete list may
130
+ * retire a card it does not carry, so a bridge that could answer only part of the
131
+ * set must say `false` rather than let the difference read as "the question is
132
+ * over".
133
+ */
134
+ export interface QuestionListPayload {
135
+ readonly questions: readonly ListedQuestion[]
136
+ readonly complete: boolean
137
+ }
138
+
79
139
  /** Whether a question still holds the foreground ask, or only its late reply. */
80
140
  /**
81
141
  * `open` while the ask is still waiting, `continued` once the host's foreground
82
142
  * wait ended but a late answer can still be steered in, and `settled` as the
83
- * one-way notice that the phone's card is over — the host's own UI answered it or
84
- * the last paired client left. `settled` is published, never held.
143
+ * one-way notice that the phone's card is over — the host's own UI answered it, or
144
+ * none was left to answer it once the claim's grace window ended. `settled` is
145
+ * published, never held.
85
146
  */
86
147
  export type QuestionState = 'open' | 'continued' | 'settled'
87
148
 
@@ -522,14 +583,23 @@ export class QuestionClaims {
522
583
  }
523
584
 
524
585
  /**
525
- * Every claim still waiting on an answer.
586
+ * Every question this bridge still holds, as `question.list` publishes it.
526
587
  *
527
- * A phone that connects after the question was raised never saw the original
528
- * broadcast, so it has to be handed the live claims again — otherwise the
529
- * question sits on the host with an answerable card nowhere.
588
+ * The claim registry IS the answer: a question leaves it the moment it is
589
+ * answered, settled by the host's own UI, withdrawn with the last paired phone
590
+ * or expired, so a card missing from this list is a card no one can answer any
591
+ * more. Both live states are listed — `continued` is still answerable through
592
+ * the host's late-answer path — and a settled question is never here, because
593
+ * it is never held.
594
+ * @returns one entry per held claim, in claim order.
530
595
  */
531
- openClaims(): readonly ClaimedQuestionView[] {
532
- return [...this.#claims.values()].map(viewOf)
596
+ listed(): readonly ListedQuestion[] {
597
+ return [...this.#claims.values()].map(record => ({
598
+ key: questionKey(record.sessionId, record.callId),
599
+ sessionId: record.sessionId,
600
+ state: record.state,
601
+ payload: questionPayload(record.state, viewOf(record)),
602
+ }))
533
603
  }
534
604
 
535
605
  /**
@@ -554,8 +624,9 @@ export class QuestionClaims {
554
624
 
555
625
  /**
556
626
  * Withdraw every claim, delegating each open question to the next answerer.
557
- * Called when the last paired phone goes away and when the bridge unloads: a
558
- * question nobody can answer must not hold the agent until its own deadline.
627
+ * Called when the last paired phone has been gone long enough that no grace
628
+ * window is still running, and when the bridge unloads: a question nobody can
629
+ * answer must not hold the agent until its own deadline.
559
630
  * @returns how many questions were still open.
560
631
  */
561
632
  withdrawAll(): number {
@@ -37,18 +37,59 @@ export interface ArchiveSetFace {
37
37
  readonly archivedSessionIds: readonly string[]
38
38
  }
39
39
 
40
+ /**
41
+ * One workspace registration, as far as `workspace.list` publishes it.
42
+ *
43
+ * The host's entity carries more — its `sessionIds` account above all — and the
44
+ * face deliberately does not declare it: a row this bridge publishes must not be
45
+ * able to carry an array that grows with the session count.
46
+ */
47
+ export interface WorkspaceFace {
48
+ readonly id: string
49
+ readonly path: string
50
+ readonly title: string
51
+ readonly createdAt?: string
52
+ readonly updatedAt?: string
53
+ }
54
+
55
+ /**
56
+ * The slice of `ctx.workspaceRegistry` `workspace.list` reads: the registry
57
+ * itself.
58
+ *
59
+ * Wider than {@link ArchiveSetFace} by the ordered projection and the pin set,
60
+ * because one method publishes all three: a client pins a session and reads
61
+ * both sets back in one frame. Every member is synchronous — `list()` answers a
62
+ * fresh array and both sets are getters over the durable registry — which is
63
+ * what lets the answer be built without awaiting anything.
64
+ */
65
+ export interface WorkspacesFace extends ArchiveSetFace {
66
+ list(): readonly WorkspaceFace[]
67
+ readonly pinnedSessionIds: readonly string[]
68
+ }
69
+
70
+ /** The body `workspace.list` answers. */
71
+ export interface WorkspaceListAnswer {
72
+ readonly workspaces: readonly WorkspaceFace[]
73
+ readonly archivedSessionIds: readonly string[]
74
+ readonly pinnedSessionIds: readonly string[]
75
+ }
76
+
40
77
  /**
41
78
  * The in-process services one metadata read may use.
42
79
  *
43
80
  * Every field is optional on purpose. The bridge does not require the title or
44
81
  * workspace plugins to be installed — the protocol's roster and title methods
45
82
  * stay answerable with them absent, and a field that is missing degrades one
46
- * key of one row instead of failing a method.
83
+ * key of one row instead of failing a method. `workspaces` is the member that
84
+ * breaks that rule on purpose: `workspace.list` exists only to publish the
85
+ * registry, so its absence is reported as a host without one rather than
86
+ * answered with an empty list.
47
87
  */
48
88
  export interface SessionMetaFaces {
49
89
  readonly sessions?: SessionStoreFace | undefined
50
90
  readonly titles?: SessionTitleFace | undefined
51
91
  readonly archive?: ArchiveSetFace | undefined
92
+ readonly workspaces?: WorkspacesFace | undefined
52
93
  }
53
94
 
54
95
  /** Largest id batch one `session.titles` call accepts. */
@@ -150,6 +191,37 @@ export class SessionMeta {
150
191
  }
151
192
  }
152
193
 
194
+ /**
195
+ * The host's workspaces and its two registry-global session sets.
196
+ *
197
+ * One synchronous projection and nothing more: `list()` already answers a
198
+ * fresh array in registry order, and both sets are getters over the durable
199
+ * registry, so this read awaits nothing, opens no follow stream and touches no
200
+ * persistence. Workspaces are neither sorted nor filtered — the registry's own
201
+ * order is the display order — and a row carries exactly the fields protocol
202
+ * v1 names, `sessionIds` never among them.
203
+ *
204
+ * An unmounted registry answers undefined instead of an empty list: "this host
205
+ * has no workspaces" and "this host has no registry to ask" are two different
206
+ * facts, and only the caller can say which one it must report.
207
+ * @returns the answer, or undefined when this host composes no workspace registry.
208
+ */
209
+ workspaceList(): WorkspaceListAnswer | undefined {
210
+ const registry = this.#faces().workspaces
211
+ if (registry === undefined) return undefined
212
+ return {
213
+ workspaces: registry.list().map(workspace => ({
214
+ id: workspace.id,
215
+ path: workspace.path,
216
+ title: workspace.title,
217
+ ...(workspace.createdAt === undefined ? {} : { createdAt: workspace.createdAt }),
218
+ ...(workspace.updatedAt === undefined ? {} : { updatedAt: workspace.updatedAt }),
219
+ })),
220
+ archivedSessionIds: [...registry.archivedSessionIds],
221
+ pinnedSessionIds: [...registry.pinnedSessionIds],
222
+ }
223
+ }
224
+
153
225
  /** Resolve one title through the host services, degrading to `""` on any failure. */
154
226
  #resolve(id: string): string {
155
227
  try {