@inflatable-cookie/longhorn 0.6.0 → 0.7.0

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 (133) hide show
  1. package/README.md +2 -2
  2. package/package.json +1 -7
  3. package/src/agent-control/generated/protocol.ts +228 -0
  4. package/src/agent-control/index.ts +1 -5
  5. package/src/agent-control/selection.ts +10 -8
  6. package/src/agent-control/shim.ts +149 -77
  7. package/src/bridge/generated/fields.ts +1 -1
  8. package/src/bridge/generated/protocol.ts +55 -4
  9. package/src/bridge/generated/variant-fields.ts +1 -1
  10. package/src/bridge/job.ts +49 -2
  11. package/src/bridge/runtime/connection.ts +11 -14
  12. package/src/bridge/stream/connection.ts +14 -23
  13. package/src/bridge/stream/tracker.ts +5 -0
  14. package/src/bridge/supervision.ts +102 -80
  15. package/src/bridge/validation/base.ts +7 -27
  16. package/src/bridge/validation/negotiation.ts +1 -6
  17. package/src/bridge/validation/operations.ts +2 -14
  18. package/src/commands/client.ts +16 -2
  19. package/src/commands/controller.ts +96 -58
  20. package/src/commands/generated/fields.ts +4 -4
  21. package/src/commands/generated/protocol.ts +24 -1
  22. package/src/commands/generated/variant-fields.ts +1 -1
  23. package/src/commands/keyboard.ts +4 -13
  24. package/src/commands/physical-code.ts +11 -0
  25. package/src/commands/ports.ts +2 -1
  26. package/src/commands/projectors.ts +52 -29
  27. package/src/commands/validation.ts +408 -188
  28. package/src/config/client.ts +3 -3
  29. package/src/config/generated/base.ts +22 -6
  30. package/src/config/generated/fields.ts +2 -1
  31. package/src/config/generated/label-template.ts +1 -1
  32. package/src/config/generated/labels.ts +1 -1
  33. package/src/config/generated/protocol.ts +1 -1
  34. package/src/config/generated/restore.ts +35 -12
  35. package/src/config/generated/variant-fields.ts +1 -1
  36. package/src/config/validation/commands.ts +11 -13
  37. package/src/config/validation/outcomes.ts +147 -46
  38. package/src/config/validation/primitives.ts +11 -39
  39. package/src/config/validation/projection.ts +44 -44
  40. package/src/core/connection.ts +124 -29
  41. package/src/core/controller-lifecycle.ts +144 -0
  42. package/src/core/generated/identifiers.ts +4 -0
  43. package/src/core/identifiers.ts +40 -0
  44. package/src/core/index.ts +10 -1
  45. package/src/core/json-value.ts +58 -0
  46. package/src/core/listeners.ts +35 -0
  47. package/src/core/record.ts +76 -0
  48. package/src/core/transport.ts +10 -1
  49. package/src/core/wire-copy.ts +1 -0
  50. package/src/history/client.ts +11 -7
  51. package/src/history/controller.ts +72 -74
  52. package/src/history/generated/fields.ts +2 -1
  53. package/src/history/generated/protocol.ts +8 -5
  54. package/src/history/generated/variant-fields.ts +1 -1
  55. package/src/history/ports.ts +7 -2
  56. package/src/history/validation.ts +15 -37
  57. package/src/history-tree/client.ts +15 -13
  58. package/src/history-tree/controller.ts +131 -90
  59. package/src/history-tree/generated/fields.ts +3 -1
  60. package/src/history-tree/generated/protocol.ts +43 -7
  61. package/src/history-tree/generated/variant-fields.ts +7 -1
  62. package/src/history-tree/ports.ts +9 -4
  63. package/src/history-tree/validation.ts +44 -35
  64. package/src/layout/generated/protocol.ts +2 -1
  65. package/src/layout/generated/variant-fields.ts +47 -0
  66. package/src/layout/index.ts +1 -1
  67. package/src/layout/ratio.ts +9 -2
  68. package/src/layout/validation.ts +88 -13
  69. package/src/licence/client.ts +11 -7
  70. package/src/licence/controller.ts +64 -43
  71. package/src/licence/generated/fields.ts +2 -1
  72. package/src/licence/generated/protocol.ts +8 -4
  73. package/src/licence/generated/variant-fields.ts +1 -1
  74. package/src/licence/key.ts +2 -6
  75. package/src/licence/ports.ts +7 -2
  76. package/src/licence/validation.ts +27 -20
  77. package/src/native-content/client.ts +32 -1
  78. package/src/native-content/generated/fields.ts +4 -4
  79. package/src/native-content/generated/protocol.ts +16 -5
  80. package/src/native-content/generated/variant-fields.ts +1 -1
  81. package/src/native-content/ports.ts +2 -1
  82. package/src/native-content/validation/base.ts +16 -46
  83. package/src/native-content/validation/messages.ts +3 -0
  84. package/src/notifications/client.ts +17 -39
  85. package/src/notifications/controller.ts +266 -165
  86. package/src/notifications/generated/fields.ts +2 -1
  87. package/src/notifications/generated/labels.ts +1 -1
  88. package/src/notifications/generated/protocol.ts +5 -1
  89. package/src/notifications/generated/variant-fields.ts +1 -1
  90. package/src/notifications/ports.ts +2 -1
  91. package/src/notifications/tone.ts +1 -1
  92. package/src/notifications/validation.ts +41 -51
  93. package/src/operation/bridge.ts +79 -19
  94. package/src/operation/client.ts +17 -45
  95. package/src/operation/controller.ts +38 -59
  96. package/src/operation/generated/fields.ts +2 -1
  97. package/src/operation/generated/labels.ts +1 -1
  98. package/src/operation/generated/protocol.ts +5 -1
  99. package/src/operation/generated/variant-fields.ts +1 -1
  100. package/src/operation/ports.ts +2 -1
  101. package/src/operation/validation.ts +48 -50
  102. package/src/settings/connection.ts +10 -14
  103. package/src/settings/generated/fields.ts +2 -1
  104. package/src/settings/generated/protocol.ts +5 -1
  105. package/src/settings/generated/variant-fields.ts +1 -1
  106. package/src/settings/validation/authority.ts +2 -2
  107. package/src/settings/validation/command.ts +5 -4
  108. package/src/settings/validation/primitives.ts +32 -67
  109. package/src/settings/validation/registry.ts +13 -11
  110. package/src/surface-transfer/generated/fields.ts +1 -1
  111. package/src/surface-transfer/generated/protocol.ts +3 -3
  112. package/src/surface-transfer/generated/variant-fields.ts +1 -1
  113. package/src/surface-transfer/validation.ts +76 -53
  114. package/src/surfaces/client.ts +26 -38
  115. package/src/surfaces/generated/fields.ts +1 -1
  116. package/src/surfaces/generated/protocol.ts +1 -1
  117. package/src/surfaces/generated/variant-fields.ts +1 -1
  118. package/src/surfaces/validation.ts +198 -61
  119. package/src/transfer/connection.ts +25 -39
  120. package/src/transfer/generated/fields.ts +2 -1
  121. package/src/transfer/generated/protocol.ts +9 -1
  122. package/src/transfer/generated/variant-fields.ts +1 -1
  123. package/src/transfer/index.ts +8 -1
  124. package/src/transfer/payload.ts +12 -9
  125. package/src/transfer/validation.ts +146 -60
  126. package/src/update/client.ts +43 -16
  127. package/src/update/controller.ts +187 -104
  128. package/src/update/generated/fields.ts +2 -1
  129. package/src/update/generated/protocol.ts +19 -7
  130. package/src/update/generated/variant-fields.ts +3 -2
  131. package/src/update/ports.ts +11 -7
  132. package/src/update/serialized.ts +8 -6
  133. package/src/update/validation.ts +18 -28
@@ -1,5 +1,5 @@
1
+ import { ControllerLifecycle } from "../core/controller-lifecycle.ts";
1
2
  import { isNewerNotificationSnapshot, NotificationClient } from "./client.ts";
2
- import type { NotificationSubscription } from "./client.ts";
3
3
  import { NOTIFICATION_PROTOCOL_VERSION } from "./generated/protocol.ts";
4
4
  import type {
5
5
  NotificationActionProjection,
@@ -21,6 +21,10 @@ export type NotificationControllerStatus =
21
21
  | { readonly kind: "loading" }
22
22
  | { readonly kind: "ready" }
23
23
  | { readonly kind: "failed"; readonly error: unknown };
24
+ export type NotificationPaginationStatus =
25
+ | { readonly kind: "idle" }
26
+ | { readonly kind: "loading" }
27
+ | { readonly kind: "failed"; readonly error: unknown };
24
28
  export type NotificationPendingKind = "markSeen" | "dismiss" | "action";
25
29
 
26
30
  export interface NotificationPendingCommand {
@@ -63,166 +67,188 @@ export interface NotificationControllerOptions {
63
67
  }
64
68
 
65
69
  export class NotificationController {
66
- readonly client: NotificationClient;
67
- readonly observers = new Set<() => void>();
68
- readonly pending = new Map<NotificationRequestId, NotificationPendingCommand>();
69
- readonly pageSize: number;
70
- readonly toastSelector: ((record: NotificationRecordProjection) => boolean) | undefined;
71
- readonly actionExecutor: NotificationActionExecutor | undefined;
72
- status: NotificationControllerStatus = { kind: "idle" };
73
- snapshot: NotificationSnapshot | undefined;
74
- records: Array<NotificationRecordProjection> = [];
75
- toasts: Array<NotificationToastProjection> = [];
76
- selectedNotificationId: NotificationId | undefined;
77
- commandRejection: NotificationCommandRejection | undefined;
78
- commandFailure: NotificationCommandFailure | undefined;
79
- subscription: NotificationSubscription | undefined;
80
- started = false;
81
- lifecycleRevision = 0;
82
- toastSequence = 0;
70
+ readonly #client: NotificationClient;
71
+ readonly #observers = new Set<() => void>();
72
+ readonly #pending = new Map<NotificationRequestId, NotificationPendingCommand>();
73
+ readonly #pageSize: number;
74
+ readonly #toastSelector: ((record: NotificationRecordProjection) => boolean) | undefined;
75
+ readonly #actionExecutor: NotificationActionExecutor | undefined;
76
+ #status: NotificationControllerStatus = { kind: "idle" };
77
+ #pagination: NotificationPaginationStatus = { kind: "idle" };
78
+ #snapshot: NotificationSnapshot | undefined;
79
+ #records: Array<NotificationRecordProjection> = [];
80
+ #toasts: Array<NotificationToastProjection> = [];
81
+ #selectedNotificationId: NotificationId | undefined;
82
+ #commandRejection: NotificationCommandRejection | undefined;
83
+ #commandFailure: NotificationCommandFailure | undefined;
84
+ readonly #lifecycle = new ControllerLifecycle();
85
+ #toastSequence = 0;
86
+ #pageLoad: Promise<void> | undefined;
83
87
 
84
88
  constructor(options: NotificationControllerOptions) {
85
- this.client = new NotificationClient(options.port);
86
- this.pageSize = options.pageSize ?? 100;
87
- this.toastSelector = options.toast?.select;
88
- this.actionExecutor = options.actions;
89
+ this.#client = new NotificationClient(options.port);
90
+ this.#pageSize = options.pageSize ?? 100;
91
+ this.#toastSelector = options.toast?.select;
92
+ this.#actionExecutor = options.actions;
89
93
  }
90
94
 
95
+ get status(): NotificationControllerStatus {
96
+ return { ...this.#status };
97
+ }
98
+ get pagination(): NotificationPaginationStatus {
99
+ return { ...this.#pagination };
100
+ }
101
+ get snapshot(): NotificationSnapshot | undefined {
102
+ return structuredClone(this.#snapshot);
103
+ }
104
+ get records(): ReadonlyArray<NotificationRecordProjection> {
105
+ return structuredClone(this.#records);
106
+ }
107
+ get toasts(): ReadonlyArray<NotificationToastProjection> {
108
+ return structuredClone(this.#toasts);
109
+ }
110
+ get selectedNotificationId(): NotificationId | undefined {
111
+ return this.#selectedNotificationId;
112
+ }
91
113
  get selected(): NotificationRecordProjection | undefined {
92
- return this.records.find((record) => record.notificationId === this.selectedNotificationId);
114
+ return structuredClone(
115
+ this.#records.find((record) => record.notificationId === this.#selectedNotificationId),
116
+ );
117
+ }
118
+ get commandRejection(): NotificationCommandRejection | undefined {
119
+ return structuredClone(this.#commandRejection);
120
+ }
121
+ get commandFailure(): NotificationCommandFailure | undefined {
122
+ return this.#commandFailure === undefined ? undefined : { ...this.#commandFailure };
93
123
  }
94
124
  get hasMore(): boolean {
95
- return this.snapshot?.page.hasMore ?? false;
125
+ return this.#snapshot?.page.hasMore ?? false;
96
126
  }
97
127
  get pendingCommands(): ReadonlyArray<NotificationPendingCommand> {
98
- return [...this.pending.values()];
128
+ return Array.from(this.#pending.values(), (pending) => ({ ...pending }));
99
129
  }
100
130
 
101
131
  observe(observer: () => void): () => void {
102
- this.observers.add(observer);
103
- return () => this.observers.delete(observer);
132
+ this.#observers.add(observer);
133
+ return () => this.#observers.delete(observer);
104
134
  }
105
135
 
106
- async start(): Promise<void> {
107
- if (this.started) {
108
- return;
109
- }
110
- this.started = true;
111
- const lifecycle = ++this.lifecycleRevision;
112
- this.setStatus({ kind: "loading" });
113
- const subscription = this.client.subscribe(
114
- (snapshot) => {
115
- if (this.isCurrent(lifecycle)) {
116
- this.install(snapshot);
117
- }
118
- },
119
- ({ error }) => {
120
- if (this.isCurrent(lifecycle)) {
121
- this.setStatus({ kind: "failed", error });
122
- }
136
+ start(): Promise<void> {
137
+ return this.#lifecycle.start({
138
+ loading: () => this.#setStatus({ kind: "loading" }),
139
+ connect: ({ isCurrent, reportFailure, watch }) => {
140
+ const subscription = this.#client.subscribe(
141
+ (snapshot) => {
142
+ if (isCurrent()) {
143
+ this.#install(snapshot);
144
+ }
145
+ },
146
+ reportFailure,
147
+ this.#pageSize,
148
+ );
149
+ return watch(subscription, () => this.#setStatus({ kind: "ready" }));
123
150
  },
124
- this.pageSize,
151
+ failed: (error) => this.#setStatus({ kind: "failed", error }),
152
+ });
153
+ }
154
+
155
+ /** Replaces the current subscription, including after a reported failure. */
156
+ restart(): Promise<void> {
157
+ return this.#lifecycle.restart(
158
+ this.status,
159
+ () => this.stop(),
160
+ () => this.start(),
125
161
  );
126
- this.subscription = subscription;
127
- try {
128
- await subscription.ready;
129
- if (this.isCurrent(lifecycle)) {
130
- this.setStatus({ kind: "ready" });
131
- }
132
- } catch (error) {
133
- if (this.isCurrent(lifecycle)) {
134
- this.setStatus({ kind: "failed", error });
135
- }
136
- }
137
162
  }
138
163
 
139
- async stop(): Promise<void> {
140
- this.started = false;
141
- this.lifecycleRevision += 1;
142
- const subscription = this.subscription;
143
- this.subscription = undefined;
144
- this.snapshot = undefined;
145
- this.records = [];
146
- this.toasts = [];
147
- this.selectedNotificationId = undefined;
148
- this.pending.clear();
149
- this.commandFailure = undefined;
150
- this.commandRejection = undefined;
151
- this.setStatus({ kind: "idle" });
152
- if (subscription !== undefined) {
153
- await subscription.dispose();
154
- }
164
+ stop(): Promise<void> {
165
+ return this.#lifecycle.stop(() => {
166
+ this.#snapshot = undefined;
167
+ this.#records = [];
168
+ this.#toasts = [];
169
+ this.#selectedNotificationId = undefined;
170
+ this.#pending.clear();
171
+ this.#pageLoad = undefined;
172
+ this.#pagination = { kind: "idle" };
173
+ this.#commandFailure = undefined;
174
+ this.#commandRejection = undefined;
175
+ this.#setStatus({ kind: "idle" });
176
+ });
155
177
  }
156
178
 
157
179
  select(notificationId: NotificationId | undefined): void {
158
180
  if (
159
181
  notificationId !== undefined &&
160
- !this.records.some((record) => record.notificationId === notificationId)
182
+ !this.#records.some((record) => record.notificationId === notificationId)
161
183
  ) {
162
184
  throw new NotificationControllerUnknownRecordError(notificationId);
163
185
  }
164
- this.selectedNotificationId = notificationId;
165
- this.notify();
186
+ this.#selectedNotificationId = notificationId;
187
+ this.#notify();
166
188
  }
167
189
 
168
190
  async loadMore(): Promise<void> {
169
- const current = this.requireSnapshot();
191
+ if (this.#pageLoad !== undefined) {
192
+ return this.#pageLoad;
193
+ }
194
+ const current = this.#requireSnapshot();
170
195
  if (!current.page.hasMore) {
171
196
  return;
172
197
  }
173
- const next = (await this.client.snapshot(this.records.length, this.pageSize)).snapshot;
174
- if (
175
- next.authority.authorityId !== current.authority.authorityId ||
176
- next.authority.authorityEpoch !== current.authority.authorityEpoch ||
177
- next.ledgerRevision !== current.ledgerRevision
178
- ) {
179
- this.install(next);
180
- return;
198
+ const lifecycle = this.#lifecycle.revision;
199
+ const load = this.#applyPage(current, this.#records.length, lifecycle);
200
+ this.#pageLoad = load;
201
+ this.#setPagination({ kind: "loading" });
202
+ try {
203
+ await load;
204
+ if (this.#pageLoad === load) {
205
+ this.#setPagination({ kind: "idle" });
206
+ }
207
+ } catch (error) {
208
+ // A load that a newer snapshot or a stop has abandoned no longer owns status.
209
+ if (this.#pageLoad === load) {
210
+ this.#setPagination({ kind: "failed", error });
211
+ }
212
+ throw error;
213
+ } finally {
214
+ if (this.#pageLoad === load) {
215
+ this.#pageLoad = undefined;
216
+ }
181
217
  }
182
- const known = new Set(this.records.map((record) => record.notificationId));
183
- this.records = [
184
- ...this.records,
185
- ...next.page.records.filter((record) => !known.has(record.notificationId)),
186
- ];
187
- this.snapshot = {
188
- ...current,
189
- page: { ...current.page, hasMore: next.page.hasMore, records: [...this.records] },
190
- };
191
- this.notify();
192
218
  }
193
219
 
194
220
  markSeen(notificationId: NotificationId): Promise<NotificationMutationResult> {
195
- return this.mutateRecord(notificationId, "markSeen");
221
+ return this.#mutateRecord(notificationId, "markSeen");
196
222
  }
197
223
  dismiss(notificationId: NotificationId): Promise<NotificationMutationResult> {
198
- return this.mutateRecord(notificationId, "dismiss");
224
+ return this.#mutateRecord(notificationId, "dismiss");
199
225
  }
200
226
 
201
227
  dismissToast(id: string): void {
202
- const next = this.toasts.filter((toast) => toast.id !== id);
203
- if (next.length === this.toasts.length) {
228
+ const next = this.#toasts.filter((toast) => toast.id !== id);
229
+ if (next.length === this.#toasts.length) {
204
230
  return;
205
231
  }
206
- this.toasts = next;
207
- this.notify();
232
+ this.#toasts = next;
233
+ this.#notify();
208
234
  }
209
235
 
210
236
  async invokeAction(notificationId: NotificationId, referenceId: string): Promise<void> {
211
- const record = this.requireRecord(notificationId);
237
+ const record = this.#requireRecord(notificationId);
212
238
  const action = record.draft.actions.find((candidate) => candidate.referenceId === referenceId);
213
239
  if (action === undefined) {
214
240
  throw new NotificationControllerUnknownActionError(notificationId, referenceId);
215
241
  }
216
- if (this.actionExecutor === undefined) {
242
+ if (this.#actionExecutor === undefined) {
217
243
  throw new NotificationControllerActionUnavailableError();
218
244
  }
219
245
  const pending = {
220
- requestId: this.client.nextRequestId(),
246
+ requestId: this.#client.nextRequestId(),
221
247
  notificationId,
222
248
  kind: "action" as const,
223
249
  };
224
- await this.runPending(pending, async () => {
225
- await this.actionExecutor?.admitAndExecute({
250
+ await this.#runPending(pending, async () => {
251
+ await this.#actionExecutor?.admitAndExecute({
226
252
  notificationId,
227
253
  sourceId: record.draft.sourceId,
228
254
  referenceId: action.referenceId,
@@ -231,96 +257,166 @@ export class NotificationController {
231
257
  }
232
258
 
233
259
  isPending(notificationId: NotificationId, kind: NotificationPendingKind): boolean {
234
- return [...this.pending.values()].some(
260
+ return [...this.#pending.values()].some(
235
261
  (item) => item.notificationId === notificationId && item.kind === kind,
236
262
  );
237
263
  }
238
264
 
239
- private async mutateRecord(
265
+ async #mutateRecord(
240
266
  notificationId: NotificationId,
241
267
  kind: "markSeen" | "dismiss",
242
268
  ): Promise<NotificationMutationResult> {
243
- const snapshot = this.requireSnapshot();
244
- this.requireRecord(notificationId);
269
+ const snapshot = this.#requireSnapshot();
270
+ this.#requireRecord(notificationId);
245
271
  const command = {
246
272
  kind,
247
- requestId: this.client.nextRequestId(),
273
+ requestId: this.#client.nextRequestId(),
248
274
  protocolVersion: NOTIFICATION_PROTOCOL_VERSION,
249
275
  authority: snapshot.authority,
250
276
  expectedLedgerRevision: snapshot.ledgerRevision,
251
277
  notificationId,
252
278
  } as const;
253
- return this.runPending({ requestId: command.requestId, notificationId, kind }, async () => {
254
- const result = await this.client.mutate(command);
255
- this.install(result.snapshot);
256
- if (result.status === "rejected") {
257
- this.commandRejection = {
258
- requestId: command.requestId,
259
- notificationId,
260
- kind,
261
- rejection: result.rejection,
262
- };
263
- }
264
- return result;
265
- });
279
+ return this.#runPending(
280
+ { requestId: command.requestId, notificationId, kind },
281
+ async (lifecycle) => {
282
+ const result = await this.#client.mutate(command);
283
+ if (!this.#lifecycle.isCurrent(lifecycle)) {
284
+ return result;
285
+ }
286
+ if (result.status === "rejected") {
287
+ this.#commandRejection = {
288
+ requestId: command.requestId,
289
+ notificationId,
290
+ kind,
291
+ rejection: structuredClone(result.rejection),
292
+ };
293
+ }
294
+ this.#install(result.snapshot);
295
+ return result;
296
+ },
297
+ );
266
298
  }
267
299
 
268
- private async runPending<Result>(
300
+ async #runPending<Result>(
269
301
  pending: NotificationPendingCommand,
270
- run: () => Promise<Result>,
302
+ run: (lifecycle: number) => Promise<Result>,
271
303
  ): Promise<Result> {
272
304
  if (this.isPending(pending.notificationId, pending.kind)) {
273
305
  throw new NotificationControllerCommandPendingError(pending.notificationId, pending.kind);
274
306
  }
275
- const lifecycle = this.lifecycleRevision;
276
- this.pending.set(pending.requestId, pending);
277
- this.commandFailure = undefined;
278
- this.commandRejection = undefined;
279
- this.notify();
307
+ const lifecycle = this.#lifecycle.revision;
308
+ this.#pending.set(pending.requestId, pending);
309
+ this.#commandFailure = undefined;
310
+ this.#commandRejection = undefined;
311
+ this.#notify();
280
312
  try {
281
- return await run();
313
+ return await run(lifecycle);
282
314
  } catch (error) {
283
- if (this.isCurrent(lifecycle)) {
284
- this.commandFailure = { ...pending, error };
315
+ if (this.#lifecycle.isCurrent(lifecycle)) {
316
+ this.#commandFailure = { ...pending, error };
285
317
  }
286
318
  throw error;
287
319
  } finally {
288
- if (this.isCurrent(lifecycle)) {
289
- this.pending.delete(pending.requestId);
290
- this.notify();
320
+ if (this.#lifecycle.isCurrent(lifecycle)) {
321
+ this.#pending.delete(pending.requestId);
322
+ this.#notify();
291
323
  }
292
324
  }
293
325
  }
294
326
 
295
- private install(candidate: NotificationSnapshot): void {
296
- if (!isNewerNotificationSnapshot(candidate, this.snapshot)) {
327
+ /**
328
+ * Applies one requested page only while the live state is still the basis it
329
+ * was asked against. A page is a slice, so when the ledger has moved past the
330
+ * basis it resyncs page zero instead of installing the slice as state.
331
+ */
332
+ async #applyPage(basis: NotificationSnapshot, offset: number, lifecycle: number): Promise<void> {
333
+ const response = (await this.#client.snapshot(offset, this.#pageSize)).snapshot;
334
+ const live = this.#pageFence(basis, offset, lifecycle);
335
+ if (live === undefined) {
336
+ return;
337
+ }
338
+ if (!isSameLedgerPosition(response, live)) {
339
+ await this.#resyncFirstPage(lifecycle);
297
340
  return;
298
341
  }
299
- const previous = this.snapshot;
300
- this.snapshot = candidate;
301
- this.records = [...candidate.page.records];
302
- if (previous !== undefined && this.toastSelector !== undefined) {
303
- const existing = new Set(this.toasts.map((toast) => toast.notificationId));
342
+ const known = new Set(this.#records.map((record) => record.notificationId));
343
+ this.#records = [
344
+ ...this.#records,
345
+ ...structuredClone(
346
+ response.page.records.filter((record) => !known.has(record.notificationId)),
347
+ ),
348
+ ];
349
+ this.#snapshot = {
350
+ ...live,
351
+ page: { ...live.page, hasMore: response.page.hasMore, records: [...this.#records] },
352
+ };
353
+ this.#notify();
354
+ }
355
+
356
+ /** The live snapshot, when a page requested at `offset` against `basis` may still apply. */
357
+ #pageFence(
358
+ basis: NotificationSnapshot,
359
+ offset: number,
360
+ lifecycle: number,
361
+ ): NotificationSnapshot | undefined {
362
+ const live = this.#snapshot;
363
+ if (
364
+ !this.#lifecycle.isCurrent(lifecycle) ||
365
+ live === undefined ||
366
+ this.#records.length !== offset
367
+ ) {
368
+ return undefined;
369
+ }
370
+ return isSameLedgerPosition(live, basis) ? live : undefined;
371
+ }
372
+
373
+ async #resyncFirstPage(lifecycle: number): Promise<void> {
374
+ const first = (await this.#client.snapshot(0, this.#pageSize)).snapshot;
375
+ if (this.#lifecycle.isCurrent(lifecycle)) {
376
+ this.#install(first);
377
+ }
378
+ }
379
+
380
+ #setPagination(pagination: NotificationPaginationStatus): void {
381
+ this.#pagination = pagination;
382
+ this.#notify();
383
+ }
384
+
385
+ #install(incoming: NotificationSnapshot): void {
386
+ if (!isNewerNotificationSnapshot(incoming, this.#snapshot)) {
387
+ return;
388
+ }
389
+ const candidate = structuredClone(incoming);
390
+ const previous = this.#snapshot;
391
+ this.#snapshot = candidate;
392
+ this.#records = [...candidate.page.records];
393
+ // A newer snapshot abandons any page request it was asked against, and clearing
394
+ // the load withdraws that request's right to set status. A failure recorded
395
+ // against the older state must not outlive the snapshot, even with no further pages.
396
+ this.#pageLoad = undefined;
397
+ this.#pagination = { kind: "idle" };
398
+ if (previous !== undefined && this.#toastSelector !== undefined) {
399
+ const existing = new Set(this.#toasts.map((toast) => toast.notificationId));
304
400
  const fresh = candidate.page.records.filter(
305
401
  (record) =>
306
402
  record.readState === "unseen" &&
307
403
  record.lastChangedLedgerRevision > previous.ledgerRevision &&
308
- this.toastSelector?.(record) === true &&
404
+ this.#toastSelector?.(structuredClone(record)) === true &&
309
405
  !existing.has(record.notificationId),
310
406
  );
311
- this.toasts = [...this.toasts, ...fresh.map((record) => this.projectToast(record))];
407
+ this.#toasts = [...this.#toasts, ...fresh.map((record) => this.#projectToast(record))];
312
408
  }
313
- const retained = new Set(this.records.map((record) => record.notificationId));
314
- this.toasts = this.toasts.filter((toast) => retained.has(toast.notificationId));
315
- if (this.selectedNotificationId !== undefined && !retained.has(this.selectedNotificationId)) {
316
- this.selectedNotificationId = undefined;
409
+ const retained = new Set(this.#records.map((record) => record.notificationId));
410
+ this.#toasts = this.#toasts.filter((toast) => retained.has(toast.notificationId));
411
+ if (this.#selectedNotificationId !== undefined && !retained.has(this.#selectedNotificationId)) {
412
+ this.#selectedNotificationId = undefined;
317
413
  }
318
- this.notify();
414
+ this.#notify();
319
415
  }
320
416
 
321
- private projectToast(record: NotificationRecordProjection): NotificationToastProjection {
417
+ #projectToast(record: NotificationRecordProjection): NotificationToastProjection {
322
418
  return {
323
- id: `notification-toast:${++this.toastSequence}`,
419
+ id: `notification-toast:${++this.#toastSequence}`,
324
420
  notificationId: record.notificationId,
325
421
  title: toastTitle(record.draft),
326
422
  description: record.draft.summary,
@@ -329,33 +425,38 @@ export class NotificationController {
329
425
  };
330
426
  }
331
427
 
332
- private requireSnapshot(): NotificationSnapshot {
333
- if (!this.started || this.snapshot === undefined) {
428
+ #requireSnapshot(): NotificationSnapshot {
429
+ if (!this.#lifecycle.active || this.#snapshot === undefined) {
334
430
  throw new NotificationControllerUnavailableError();
335
431
  }
336
- return this.snapshot;
432
+ return this.#snapshot;
337
433
  }
338
- private requireRecord(id: NotificationId): NotificationRecordProjection {
339
- const record = this.records.find((candidate) => candidate.notificationId === id);
434
+ #requireRecord(id: NotificationId): NotificationRecordProjection {
435
+ const record = this.#records.find((candidate) => candidate.notificationId === id);
340
436
  if (record === undefined) {
341
437
  throw new NotificationControllerUnknownRecordError(id);
342
438
  }
343
439
  return record;
344
440
  }
345
- private isCurrent(revision: number): boolean {
346
- return this.started && this.lifecycleRevision === revision;
347
- }
348
- private setStatus(status: NotificationControllerStatus): void {
349
- this.status = status;
350
- this.notify();
441
+ #setStatus(status: NotificationControllerStatus): void {
442
+ this.#status = status;
443
+ this.#notify();
351
444
  }
352
- private notify(): void {
353
- for (const observer of this.observers) {
445
+ #notify(): void {
446
+ for (const observer of this.#observers) {
354
447
  observer();
355
448
  }
356
449
  }
357
450
  }
358
451
 
452
+ function isSameLedgerPosition(a: NotificationSnapshot, b: NotificationSnapshot): boolean {
453
+ return (
454
+ a.authority.authorityId === b.authority.authorityId &&
455
+ a.authority.authorityEpoch === b.authority.authorityEpoch &&
456
+ a.ledgerRevision === b.ledgerRevision
457
+ );
458
+ }
459
+
359
460
  export class NotificationControllerUnavailableError extends Error {
360
461
  constructor() {
361
462
  super("notification controller is not ready");
@@ -1,4 +1,4 @@
1
- // @generated by `effigy generate:notifications`; do not edit.
1
+ // @generated by `effigy generate:bindings`; do not edit.
2
2
  // Allowed field names per protocol type, from the Rust structs.
3
3
  // A `record()` given one of these rejects unknown and missing keys —
4
4
  // contract 010's Boundary Validation Target.
@@ -16,4 +16,5 @@ export const NOTIFICATIONS_FIELDS = {
16
16
  "NotificationRemovalProjection": ["record", "reason"],
17
17
  "NotificationRejection": ["code", "detail", "refreshRequired"],
18
18
  "NotificationChangedEvent": ["protocolVersion", "requestId", "authority", "previousLedgerRevision", "committedLedgerRevision", "affectedNotificationIds", "kind"],
19
+ "NotificationHostError": ["code", "message", "retryable"],
19
20
  } as const;
@@ -1,4 +1,4 @@
1
- // @generated by `effigy generate:notifications`; do not edit.
1
+ // @generated by `effigy generate:bindings`; do not edit.
2
2
  // Wording lives in Rust, on the enum that owns it. A label edited here is
3
3
  // a label that disagrees with the native surface.
4
4
 
@@ -1,4 +1,4 @@
1
- // @generated by `effigy generate:notifications`; do not edit.
1
+ // @generated by `effigy generate:bindings`; do not edit.
2
2
  // Rust serde types are the wire authority. Executable actions are intentionally absent.
3
3
 
4
4
  export const NOTIFICATION_PROTOCOL_VERSION = 1 as const;
@@ -520,3 +520,7 @@ affectedNotificationIds: Array<NotificationId>,
520
520
  * Change source.
521
521
  */
522
522
  kind: NotificationChangedKind, };
523
+
524
+ export type NotificationHostErrorCode = "authorityUnavailable" | "authorityStateUnavailable" | "eventPublication";
525
+
526
+ export type NotificationHostError = { "code": NotificationHostErrorCode, "message": string, "retryable": boolean, };
@@ -1,4 +1,4 @@
1
- // @generated by `effigy generate:notifications`; do not edit.
1
+ // @generated by `effigy generate:bindings`; do not edit.
2
2
  // Allowed field names per tagged-union variant, from the Rust enums.
3
3
  // Keyed by type, then by discriminant. The discriminant itself is in
4
4
  // each list, because `exact()` compares every key.
@@ -1,3 +1,4 @@
1
+ import type { Unlisten } from "../core/transport.ts";
1
2
  import type {
2
3
  NotificationChangedEvent,
3
4
  NotificationMutationCommand,
@@ -7,7 +8,7 @@ import type {
7
8
  NotificationMutationResult,
8
9
  } from "./generated/protocol.ts";
9
10
 
10
- export type NotificationUnlisten = () => void | Promise<void>;
11
+ export type NotificationUnlisten = Unlisten;
11
12
 
12
13
  export interface NotificationPort {
13
14
  snapshot(query: NotificationSnapshotQuery): Promise<unknown>;
@@ -14,7 +14,7 @@ export type NotificationStatusTone = "info" | "success" | "warning" | "danger";
14
14
  * Lives here rather than in a projection tier because two places needed it —
15
15
  * `NotificationController.projectToast` and the Poodle projector — and a rule
16
16
  * stated twice is a rule that can drift. The cross-backend parity fixture
17
- * checks this one function, so a third copy would be unchecked. See card 171.
17
+ * checks this one function.
18
18
  *
19
19
  * The `error`/`critical` collapse is lossy and the tone cannot say so; a
20
20
  * surface that needs the distinction restores it in text, as the Rust toast