@inflatable-cookie/longhorn 0.5.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 (167) 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/inject.ts +4 -1
  6. package/src/agent-control/selection.ts +42 -25
  7. package/src/agent-control/shim.ts +428 -198
  8. package/src/bridge/direct.ts +1 -1
  9. package/src/bridge/generated/fields.ts +4 -3
  10. package/src/bridge/generated/protocol.ts +62 -7
  11. package/src/bridge/generated/variant-fields.ts +1 -1
  12. package/src/bridge/job.ts +49 -12
  13. package/src/bridge/loopback.ts +7 -25
  14. package/src/bridge/operation.ts +13 -43
  15. package/src/bridge/router.ts +10 -23
  16. package/src/bridge/runtime/connection.ts +78 -109
  17. package/src/bridge/runtime/policy.ts +8 -28
  18. package/src/bridge/runtime/retry.ts +6 -18
  19. package/src/bridge/session.ts +4 -14
  20. package/src/bridge/stream/connection.ts +24 -55
  21. package/src/bridge/stream/source.ts +2 -6
  22. package/src/bridge/stream/tracker.ts +12 -12
  23. package/src/bridge/supervision.ts +104 -97
  24. package/src/bridge/validation/base.ts +21 -63
  25. package/src/bridge/validation/jobs.ts +11 -25
  26. package/src/bridge/validation/negotiation.ts +28 -43
  27. package/src/bridge/validation/operations.ts +29 -65
  28. package/src/bridge/validation/streams.ts +3 -10
  29. package/src/commands/client.ts +37 -28
  30. package/src/commands/controller.ts +119 -96
  31. package/src/commands/generated/fields.ts +7 -6
  32. package/src/commands/generated/protocol.ts +28 -1
  33. package/src/commands/generated/variant-fields.ts +1 -1
  34. package/src/commands/keyboard.ts +94 -100
  35. package/src/commands/physical-code.ts +11 -0
  36. package/src/commands/ports.ts +8 -13
  37. package/src/commands/projectors.ts +100 -75
  38. package/src/commands/validation.ts +434 -241
  39. package/src/config/client.ts +9 -22
  40. package/src/config/generated/base.ts +22 -6
  41. package/src/config/generated/fields.ts +4 -3
  42. package/src/config/generated/label-template.ts +1 -1
  43. package/src/config/generated/labels.ts +1 -1
  44. package/src/config/generated/protocol.ts +1 -1
  45. package/src/config/generated/restore.ts +35 -12
  46. package/src/config/generated/variant-fields.ts +1 -1
  47. package/src/config/names.ts +6 -12
  48. package/src/config/validation/commands.ts +11 -25
  49. package/src/config/validation/outcomes.ts +163 -70
  50. package/src/config/validation/primitives.ts +35 -80
  51. package/src/config/validation/projection.ts +100 -128
  52. package/src/core/connection.ts +187 -83
  53. package/src/core/controller-lifecycle.ts +144 -0
  54. package/src/core/generated/identifiers.ts +4 -0
  55. package/src/core/identifiers.ts +40 -0
  56. package/src/core/index.ts +10 -1
  57. package/src/core/json-value.ts +58 -0
  58. package/src/core/listeners.ts +35 -0
  59. package/src/core/record.ts +80 -0
  60. package/src/core/transport.ts +9 -11
  61. package/src/core/wire-copy.ts +7 -0
  62. package/src/history/client.ts +11 -13
  63. package/src/history/controller.ts +106 -108
  64. package/src/history/direct.ts +1 -3
  65. package/src/history/generated/fields.ts +4 -3
  66. package/src/history/generated/protocol.ts +8 -5
  67. package/src/history/generated/variant-fields.ts +1 -1
  68. package/src/history/ports.ts +7 -4
  69. package/src/history/serialized.ts +9 -13
  70. package/src/history/validation.ts +69 -75
  71. package/src/history-tree/client.ts +89 -11
  72. package/src/history-tree/controller.ts +380 -96
  73. package/src/history-tree/direct.ts +3 -1
  74. package/src/history-tree/generated/fields.ts +5 -3
  75. package/src/history-tree/generated/protocol.ts +43 -7
  76. package/src/history-tree/generated/variant-fields.ts +7 -1
  77. package/src/history-tree/ports.ts +12 -5
  78. package/src/history-tree/serialized.ts +39 -11
  79. package/src/history-tree/validation.ts +286 -78
  80. package/src/layout/generated/protocol.ts +4 -3
  81. package/src/layout/generated/variant-fields.ts +47 -0
  82. package/src/layout/index.ts +1 -1
  83. package/src/layout/ratio.ts +10 -9
  84. package/src/layout/validation.ts +98 -32
  85. package/src/layout/visibility.ts +1 -2
  86. package/src/licence/client.ts +48 -7
  87. package/src/licence/controller.ts +127 -70
  88. package/src/licence/direct.ts +3 -1
  89. package/src/licence/generated/fields.ts +4 -3
  90. package/src/licence/generated/key-conformance.json +28 -0
  91. package/src/licence/generated/protocol.ts +9 -5
  92. package/src/licence/generated/variant-fields.ts +1 -1
  93. package/src/licence/key.ts +42 -18
  94. package/src/licence/ports.ts +10 -3
  95. package/src/licence/serialized.ts +32 -9
  96. package/src/licence/validation.ts +134 -43
  97. package/src/native-content/client.ts +207 -234
  98. package/src/native-content/generated/fields.ts +6 -6
  99. package/src/native-content/generated/protocol.ts +16 -5
  100. package/src/native-content/generated/variant-fields.ts +1 -1
  101. package/src/native-content/ports.ts +11 -16
  102. package/src/native-content/serialized.ts +12 -19
  103. package/src/native-content/validation/base.ts +57 -80
  104. package/src/native-content/validation/messages.ts +24 -35
  105. package/src/native-content/validation/state.ts +31 -33
  106. package/src/notifications/client.ts +85 -51
  107. package/src/notifications/controller.ts +400 -145
  108. package/src/notifications/direct.ts +3 -1
  109. package/src/notifications/generated/fields.ts +4 -3
  110. package/src/notifications/generated/labels.ts +1 -1
  111. package/src/notifications/generated/protocol.ts +5 -1
  112. package/src/notifications/generated/variant-fields.ts +1 -1
  113. package/src/notifications/ports.ts +9 -4
  114. package/src/notifications/serialized.ts +11 -9
  115. package/src/notifications/tone.ts +1 -1
  116. package/src/notifications/validation.ts +165 -71
  117. package/src/operation/bridge.ts +187 -60
  118. package/src/operation/client.ts +48 -62
  119. package/src/operation/controller.ts +67 -97
  120. package/src/operation/direct.ts +1 -3
  121. package/src/operation/generated/fields.ts +4 -3
  122. package/src/operation/generated/labels.ts +1 -1
  123. package/src/operation/generated/protocol.ts +5 -1
  124. package/src/operation/generated/variant-fields.ts +1 -1
  125. package/src/operation/ports.ts +12 -10
  126. package/src/operation/serialized.ts +8 -9
  127. package/src/operation/validation.ts +189 -104
  128. package/src/settings/client.ts +11 -44
  129. package/src/settings/connection.ts +35 -53
  130. package/src/settings/generated/fields.ts +5 -4
  131. package/src/settings/generated/protocol.ts +14 -5
  132. package/src/settings/generated/variant-fields.ts +1 -1
  133. package/src/settings/names.ts +2 -4
  134. package/src/settings/registry.ts +23 -25
  135. package/src/settings/validation/authority.ts +21 -19
  136. package/src/settings/validation/command.ts +22 -41
  137. package/src/settings/validation/error.ts +2 -8
  138. package/src/settings/validation/primitives.ts +46 -97
  139. package/src/settings/validation/projection.ts +8 -24
  140. package/src/settings/validation/registry.ts +33 -79
  141. package/src/surface-transfer/client.ts +6 -18
  142. package/src/surface-transfer/generated/fields.ts +3 -3
  143. package/src/surface-transfer/generated/protocol.ts +3 -3
  144. package/src/surface-transfer/generated/variant-fields.ts +1 -1
  145. package/src/surface-transfer/validation.ts +91 -86
  146. package/src/surfaces/client.ts +33 -55
  147. package/src/surfaces/generated/fields.ts +3 -3
  148. package/src/surfaces/generated/protocol.ts +1 -1
  149. package/src/surfaces/generated/variant-fields.ts +1 -1
  150. package/src/surfaces/validation.ts +227 -99
  151. package/src/transfer/client.ts +26 -60
  152. package/src/transfer/connection.ts +29 -51
  153. package/src/transfer/generated/fields.ts +7 -6
  154. package/src/transfer/generated/protocol.ts +13 -5
  155. package/src/transfer/generated/variant-fields.ts +1 -1
  156. package/src/transfer/index.ts +8 -1
  157. package/src/transfer/payload.ts +20 -35
  158. package/src/transfer/validation.ts +169 -119
  159. package/src/update/client.ts +86 -9
  160. package/src/update/controller.ts +264 -116
  161. package/src/update/direct.ts +3 -1
  162. package/src/update/generated/fields.ts +5 -4
  163. package/src/update/generated/protocol.ts +25 -9
  164. package/src/update/generated/variant-fields.ts +4 -2
  165. package/src/update/ports.ts +14 -6
  166. package/src/update/serialized.ts +36 -10
  167. package/src/update/validation.ts +118 -48
@@ -1,20 +1,30 @@
1
- import { isNewerNotificationSnapshot, NotificationClient, type NotificationSubscription } from "./client.ts";
2
- import {
3
- NOTIFICATION_PROTOCOL_VERSION,
4
- type NotificationActionProjection,
5
- type NotificationId,
6
- type NotificationMutationResult,
7
- type NotificationRecordProjection,
8
- type NotificationRejection,
9
- type NotificationRequestId,
10
- type NotificationSnapshot,
1
+ import { ControllerLifecycle } from "../core/controller-lifecycle.ts";
2
+ import { isNewerNotificationSnapshot, NotificationClient } from "./client.ts";
3
+ import { NOTIFICATION_PROTOCOL_VERSION } from "./generated/protocol.ts";
4
+ import type {
5
+ NotificationActionProjection,
6
+ NotificationId,
7
+ NotificationMutationResult,
8
+ NotificationRecordProjection,
9
+ NotificationRejection,
10
+ NotificationRequestId,
11
+ NotificationSnapshot,
11
12
  } from "./generated/protocol.ts";
12
- import { notificationSeverityTone, type NotificationStatusTone } from "./tone.ts";
13
+ import { notificationSeverityTone } from "./tone.ts";
14
+ import type { NotificationStatusTone } from "./tone.ts";
13
15
  import { toastAction, toastTitle } from "./toast.ts";
14
16
 
15
17
  import type { NotificationPort } from "./ports.ts";
16
18
 
17
- export type NotificationControllerStatus = { readonly kind: "idle" } | { readonly kind: "loading" } | { readonly kind: "ready" } | { readonly kind: "failed"; readonly error: unknown };
19
+ export type NotificationControllerStatus =
20
+ | { readonly kind: "idle" }
21
+ | { readonly kind: "loading" }
22
+ | { readonly kind: "ready" }
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 };
18
28
  export type NotificationPendingKind = "markSeen" | "dismiss" | "action";
19
29
 
20
30
  export interface NotificationPendingCommand {
@@ -23,8 +33,12 @@ export interface NotificationPendingCommand {
23
33
  readonly kind: NotificationPendingKind;
24
34
  }
25
35
 
26
- export interface NotificationCommandRejection extends NotificationPendingCommand { readonly rejection: NotificationRejection; }
27
- export interface NotificationCommandFailure extends NotificationPendingCommand { readonly error: unknown; }
36
+ export interface NotificationCommandRejection extends NotificationPendingCommand {
37
+ readonly rejection: NotificationRejection;
38
+ }
39
+ export interface NotificationCommandFailure extends NotificationPendingCommand {
40
+ readonly error: unknown;
41
+ }
28
42
 
29
43
  export interface NotificationActionInvocation {
30
44
  readonly notificationId: NotificationId;
@@ -42,7 +56,7 @@ export interface NotificationToastProjection {
42
56
  readonly title: string;
43
57
  readonly description: string;
44
58
  readonly tone: NotificationStatusTone;
45
- readonly action?: NotificationActionProjection;
59
+ readonly action?: NotificationActionProjection | undefined;
46
60
  }
47
61
 
48
62
  export interface NotificationControllerOptions {
@@ -53,171 +67,356 @@ export interface NotificationControllerOptions {
53
67
  }
54
68
 
55
69
  export class NotificationController {
56
- readonly client: NotificationClient;
57
- readonly observers = new Set<() => void>();
58
- readonly pending = new Map<NotificationRequestId, NotificationPendingCommand>();
59
- readonly pageSize: number;
60
- readonly toastSelector: ((record: NotificationRecordProjection) => boolean) | undefined;
61
- readonly actionExecutor: NotificationActionExecutor | undefined;
62
- status: NotificationControllerStatus = { kind: "idle" };
63
- snapshot: NotificationSnapshot | undefined;
64
- records: NotificationRecordProjection[] = [];
65
- toasts: NotificationToastProjection[] = [];
66
- selectedNotificationId: NotificationId | undefined;
67
- commandRejection: NotificationCommandRejection | undefined;
68
- commandFailure: NotificationCommandFailure | undefined;
69
- subscription: NotificationSubscription | undefined;
70
- started = false;
71
- lifecycleRevision = 0;
72
- 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;
73
87
 
74
88
  constructor(options: NotificationControllerOptions) {
75
- this.client = new NotificationClient(options.port);
76
- this.pageSize = options.pageSize ?? 100;
77
- this.toastSelector = options.toast?.select;
78
- this.actionExecutor = options.actions;
79
- }
80
-
81
- get selected(): NotificationRecordProjection | undefined { return this.records.find((record) => record.notificationId === this.selectedNotificationId); }
82
- get hasMore(): boolean { return this.snapshot?.page.hasMore ?? false; }
83
- get pendingCommands(): readonly NotificationPendingCommand[] { return [...this.pending.values()]; }
84
-
85
- observe(observer: () => void): () => void { this.observers.add(observer); return () => this.observers.delete(observer); }
86
-
87
- async start(): Promise<void> {
88
- if (this.started) return;
89
- this.started = true;
90
- const lifecycle = ++this.lifecycleRevision;
91
- this.setStatus({ kind: "loading" });
92
- const subscription = this.client.subscribe(
93
- (snapshot) => { if (this.isCurrent(lifecycle)) this.install(snapshot); },
94
- ({ error }) => { if (this.isCurrent(lifecycle)) this.setStatus({ kind: "failed", error }); },
95
- this.pageSize,
89
+ this.#client = new NotificationClient(options.port);
90
+ this.#pageSize = options.pageSize ?? 100;
91
+ this.#toastSelector = options.toast?.select;
92
+ this.#actionExecutor = options.actions;
93
+ }
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
+ }
113
+ get selected(): NotificationRecordProjection | undefined {
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 };
123
+ }
124
+ get hasMore(): boolean {
125
+ return this.#snapshot?.page.hasMore ?? false;
126
+ }
127
+ get pendingCommands(): ReadonlyArray<NotificationPendingCommand> {
128
+ return Array.from(this.#pending.values(), (pending) => ({ ...pending }));
129
+ }
130
+
131
+ observe(observer: () => void): () => void {
132
+ this.#observers.add(observer);
133
+ return () => this.#observers.delete(observer);
134
+ }
135
+
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" }));
150
+ },
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(),
96
161
  );
97
- this.subscription = subscription;
98
- try {
99
- await subscription.ready;
100
- if (this.isCurrent(lifecycle)) this.setStatus({ kind: "ready" });
101
- } catch (error) {
102
- if (this.isCurrent(lifecycle)) this.setStatus({ kind: "failed", error });
103
- }
104
162
  }
105
163
 
106
- async stop(): Promise<void> {
107
- this.started = false;
108
- this.lifecycleRevision += 1;
109
- const subscription = this.subscription;
110
- this.subscription = undefined;
111
- this.snapshot = undefined;
112
- this.records = [];
113
- this.toasts = [];
114
- this.selectedNotificationId = undefined;
115
- this.pending.clear();
116
- this.commandFailure = undefined;
117
- this.commandRejection = undefined;
118
- this.setStatus({ kind: "idle" });
119
- if (subscription !== undefined) await subscription.dispose();
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
+ });
120
177
  }
121
178
 
122
179
  select(notificationId: NotificationId | undefined): void {
123
- if (notificationId !== undefined && !this.records.some((record) => record.notificationId === notificationId)) throw new NotificationControllerUnknownRecordError(notificationId);
124
- this.selectedNotificationId = notificationId;
125
- this.notify();
180
+ if (
181
+ notificationId !== undefined &&
182
+ !this.#records.some((record) => record.notificationId === notificationId)
183
+ ) {
184
+ throw new NotificationControllerUnknownRecordError(notificationId);
185
+ }
186
+ this.#selectedNotificationId = notificationId;
187
+ this.#notify();
126
188
  }
127
189
 
128
190
  async loadMore(): Promise<void> {
129
- const current = this.requireSnapshot();
130
- if (!current.page.hasMore) return;
131
- const next = (await this.client.snapshot(this.records.length, this.pageSize)).snapshot;
132
- if (next.authority.authorityId !== current.authority.authorityId || next.authority.authorityEpoch !== current.authority.authorityEpoch || next.ledgerRevision !== current.ledgerRevision) {
133
- this.install(next);
191
+ if (this.#pageLoad !== undefined) {
192
+ return this.#pageLoad;
193
+ }
194
+ const current = this.#requireSnapshot();
195
+ if (!current.page.hasMore) {
134
196
  return;
135
197
  }
136
- const known = new Set(this.records.map((record) => record.notificationId));
137
- this.records = [...this.records, ...next.page.records.filter((record) => !known.has(record.notificationId))];
138
- this.snapshot = { ...current, page: { ...current.page, hasMore: next.page.hasMore, records: [...this.records] } };
139
- this.notify();
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
+ }
217
+ }
140
218
  }
141
219
 
142
- markSeen(notificationId: NotificationId): Promise<NotificationMutationResult> { return this.mutateRecord(notificationId, "markSeen"); }
143
- dismiss(notificationId: NotificationId): Promise<NotificationMutationResult> { return this.mutateRecord(notificationId, "dismiss"); }
220
+ markSeen(notificationId: NotificationId): Promise<NotificationMutationResult> {
221
+ return this.#mutateRecord(notificationId, "markSeen");
222
+ }
223
+ dismiss(notificationId: NotificationId): Promise<NotificationMutationResult> {
224
+ return this.#mutateRecord(notificationId, "dismiss");
225
+ }
144
226
 
145
227
  dismissToast(id: string): void {
146
- const next = this.toasts.filter((toast) => toast.id !== id);
147
- if (next.length === this.toasts.length) return;
148
- this.toasts = next;
149
- this.notify();
228
+ const next = this.#toasts.filter((toast) => toast.id !== id);
229
+ if (next.length === this.#toasts.length) {
230
+ return;
231
+ }
232
+ this.#toasts = next;
233
+ this.#notify();
150
234
  }
151
235
 
152
236
  async invokeAction(notificationId: NotificationId, referenceId: string): Promise<void> {
153
- const record = this.requireRecord(notificationId);
237
+ const record = this.#requireRecord(notificationId);
154
238
  const action = record.draft.actions.find((candidate) => candidate.referenceId === referenceId);
155
- if (action === undefined) throw new NotificationControllerUnknownActionError(notificationId, referenceId);
156
- if (this.actionExecutor === undefined) throw new NotificationControllerActionUnavailableError();
157
- const pending = { requestId: this.client.nextRequestId(), notificationId, kind: "action" as const };
158
- await this.runPending(pending, async () => {
159
- await this.actionExecutor?.admitAndExecute({ notificationId, sourceId: record.draft.sourceId, referenceId: action.referenceId });
239
+ if (action === undefined) {
240
+ throw new NotificationControllerUnknownActionError(notificationId, referenceId);
241
+ }
242
+ if (this.#actionExecutor === undefined) {
243
+ throw new NotificationControllerActionUnavailableError();
244
+ }
245
+ const pending = {
246
+ requestId: this.#client.nextRequestId(),
247
+ notificationId,
248
+ kind: "action" as const,
249
+ };
250
+ await this.#runPending(pending, async () => {
251
+ await this.#actionExecutor?.admitAndExecute({
252
+ notificationId,
253
+ sourceId: record.draft.sourceId,
254
+ referenceId: action.referenceId,
255
+ });
160
256
  });
161
257
  }
162
258
 
163
259
  isPending(notificationId: NotificationId, kind: NotificationPendingKind): boolean {
164
- return [...this.pending.values()].some((item) => item.notificationId === notificationId && item.kind === kind);
260
+ return [...this.#pending.values()].some(
261
+ (item) => item.notificationId === notificationId && item.kind === kind,
262
+ );
165
263
  }
166
264
 
167
- private async mutateRecord(notificationId: NotificationId, kind: "markSeen" | "dismiss"): Promise<NotificationMutationResult> {
168
- const snapshot = this.requireSnapshot();
169
- this.requireRecord(notificationId);
265
+ async #mutateRecord(
266
+ notificationId: NotificationId,
267
+ kind: "markSeen" | "dismiss",
268
+ ): Promise<NotificationMutationResult> {
269
+ const snapshot = this.#requireSnapshot();
270
+ this.#requireRecord(notificationId);
170
271
  const command = {
171
272
  kind,
172
- requestId: this.client.nextRequestId(),
273
+ requestId: this.#client.nextRequestId(),
173
274
  protocolVersion: NOTIFICATION_PROTOCOL_VERSION,
174
275
  authority: snapshot.authority,
175
276
  expectedLedgerRevision: snapshot.ledgerRevision,
176
277
  notificationId,
177
278
  } as const;
178
- return this.runPending({ requestId: command.requestId, notificationId, kind }, async () => {
179
- const result = await this.client.mutate(command);
180
- this.install(result.snapshot);
181
- if (result.status === "rejected") this.commandRejection = { requestId: command.requestId, notificationId, kind, rejection: result.rejection };
182
- return result;
183
- });
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
+ );
184
298
  }
185
299
 
186
- private async runPending<Result>(pending: NotificationPendingCommand, run: () => Promise<Result>): Promise<Result> {
187
- if (this.isPending(pending.notificationId, pending.kind)) throw new NotificationControllerCommandPendingError(pending.notificationId, pending.kind);
188
- const lifecycle = this.lifecycleRevision;
189
- this.pending.set(pending.requestId, pending);
190
- this.commandFailure = undefined;
191
- this.commandRejection = undefined;
192
- this.notify();
193
- try { return await run(); }
194
- catch (error) {
195
- if (this.isCurrent(lifecycle)) this.commandFailure = { ...pending, error };
300
+ async #runPending<Result>(
301
+ pending: NotificationPendingCommand,
302
+ run: (lifecycle: number) => Promise<Result>,
303
+ ): Promise<Result> {
304
+ if (this.isPending(pending.notificationId, pending.kind)) {
305
+ throw new NotificationControllerCommandPendingError(pending.notificationId, pending.kind);
306
+ }
307
+ const lifecycle = this.#lifecycle.revision;
308
+ this.#pending.set(pending.requestId, pending);
309
+ this.#commandFailure = undefined;
310
+ this.#commandRejection = undefined;
311
+ this.#notify();
312
+ try {
313
+ return await run(lifecycle);
314
+ } catch (error) {
315
+ if (this.#lifecycle.isCurrent(lifecycle)) {
316
+ this.#commandFailure = { ...pending, error };
317
+ }
196
318
  throw error;
197
319
  } finally {
198
- if (this.isCurrent(lifecycle)) { this.pending.delete(pending.requestId); this.notify(); }
320
+ if (this.#lifecycle.isCurrent(lifecycle)) {
321
+ this.#pending.delete(pending.requestId);
322
+ this.#notify();
323
+ }
199
324
  }
200
325
  }
201
326
 
202
- private install(candidate: NotificationSnapshot): void {
203
- if (!isNewerNotificationSnapshot(candidate, this.snapshot)) return;
204
- const previous = this.snapshot;
205
- this.snapshot = candidate;
206
- this.records = [...candidate.page.records];
207
- if (previous !== undefined && this.toastSelector !== undefined) {
208
- const existing = new Set(this.toasts.map((toast) => toast.notificationId));
209
- const fresh = candidate.page.records.filter((record) => record.readState === "unseen" && record.lastChangedLedgerRevision > previous.ledgerRevision && this.toastSelector?.(record) === true && !existing.has(record.notificationId));
210
- this.toasts = [...this.toasts, ...fresh.map((record) => this.projectToast(record))];
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);
340
+ return;
341
+ }
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;
211
388
  }
212
- const retained = new Set(this.records.map((record) => record.notificationId));
213
- this.toasts = this.toasts.filter((toast) => retained.has(toast.notificationId));
214
- if (this.selectedNotificationId !== undefined && !retained.has(this.selectedNotificationId)) this.selectedNotificationId = undefined;
215
- this.notify();
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));
400
+ const fresh = candidate.page.records.filter(
401
+ (record) =>
402
+ record.readState === "unseen" &&
403
+ record.lastChangedLedgerRevision > previous.ledgerRevision &&
404
+ this.#toastSelector?.(structuredClone(record)) === true &&
405
+ !existing.has(record.notificationId),
406
+ );
407
+ this.#toasts = [...this.#toasts, ...fresh.map((record) => this.#projectToast(record))];
408
+ }
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;
413
+ }
414
+ this.#notify();
216
415
  }
217
416
 
218
- private projectToast(record: NotificationRecordProjection): NotificationToastProjection {
417
+ #projectToast(record: NotificationRecordProjection): NotificationToastProjection {
219
418
  return {
220
- id: `notification-toast:${++this.toastSequence}`,
419
+ id: `notification-toast:${++this.#toastSequence}`,
221
420
  notificationId: record.notificationId,
222
421
  title: toastTitle(record.draft),
223
422
  description: record.draft.summary,
@@ -226,15 +425,71 @@ export class NotificationController {
226
425
  };
227
426
  }
228
427
 
229
- private requireSnapshot(): NotificationSnapshot { if (!this.started || this.snapshot === undefined) throw new NotificationControllerUnavailableError(); return this.snapshot; }
230
- private requireRecord(id: NotificationId): NotificationRecordProjection { const record = this.records.find((candidate) => candidate.notificationId === id); if (record === undefined) throw new NotificationControllerUnknownRecordError(id); return record; }
231
- private isCurrent(revision: number): boolean { return this.started && this.lifecycleRevision === revision; }
232
- private setStatus(status: NotificationControllerStatus): void { this.status = status; this.notify(); }
233
- private notify(): void { for (const observer of this.observers) observer(); }
428
+ #requireSnapshot(): NotificationSnapshot {
429
+ if (!this.#lifecycle.active || this.#snapshot === undefined) {
430
+ throw new NotificationControllerUnavailableError();
431
+ }
432
+ return this.#snapshot;
433
+ }
434
+ #requireRecord(id: NotificationId): NotificationRecordProjection {
435
+ const record = this.#records.find((candidate) => candidate.notificationId === id);
436
+ if (record === undefined) {
437
+ throw new NotificationControllerUnknownRecordError(id);
438
+ }
439
+ return record;
440
+ }
441
+ #setStatus(status: NotificationControllerStatus): void {
442
+ this.#status = status;
443
+ this.#notify();
444
+ }
445
+ #notify(): void {
446
+ for (const observer of this.#observers) {
447
+ observer();
448
+ }
449
+ }
450
+ }
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
+ );
234
458
  }
235
459
 
236
- export class NotificationControllerUnavailableError extends Error { constructor() { super("notification controller is not ready"); this.name = "NotificationControllerUnavailableError"; } }
237
- export class NotificationControllerUnknownRecordError extends Error { constructor(readonly notificationId: string) { super(`unknown notification: ${notificationId}`); this.name = "NotificationControllerUnknownRecordError"; } }
238
- export class NotificationControllerUnknownActionError extends Error { constructor(readonly notificationId: string, readonly referenceId: string) { super(`unknown notification action ${referenceId} on ${notificationId}`); this.name = "NotificationControllerUnknownActionError"; } }
239
- export class NotificationControllerActionUnavailableError extends Error { constructor() { super("notification action executor is not configured"); this.name = "NotificationControllerActionUnavailableError"; } }
240
- export class NotificationControllerCommandPendingError extends Error { constructor(readonly notificationId: string, readonly kind: NotificationPendingKind) { super(`notification ${kind} already pending for ${notificationId}`); this.name = "NotificationControllerCommandPendingError"; } }
460
+ export class NotificationControllerUnavailableError extends Error {
461
+ constructor() {
462
+ super("notification controller is not ready");
463
+ this.name = "NotificationControllerUnavailableError";
464
+ }
465
+ }
466
+ export class NotificationControllerUnknownRecordError extends Error {
467
+ constructor(readonly notificationId: string) {
468
+ super(`unknown notification: ${notificationId}`);
469
+ this.name = "NotificationControllerUnknownRecordError";
470
+ }
471
+ }
472
+ export class NotificationControllerUnknownActionError extends Error {
473
+ constructor(
474
+ readonly notificationId: string,
475
+ readonly referenceId: string,
476
+ ) {
477
+ super(`unknown notification action ${referenceId} on ${notificationId}`);
478
+ this.name = "NotificationControllerUnknownActionError";
479
+ }
480
+ }
481
+ export class NotificationControllerActionUnavailableError extends Error {
482
+ constructor() {
483
+ super("notification action executor is not configured");
484
+ this.name = "NotificationControllerActionUnavailableError";
485
+ }
486
+ }
487
+ export class NotificationControllerCommandPendingError extends Error {
488
+ constructor(
489
+ readonly notificationId: string,
490
+ readonly kind: NotificationPendingKind,
491
+ ) {
492
+ super(`notification ${kind} already pending for ${notificationId}`);
493
+ this.name = "NotificationControllerCommandPendingError";
494
+ }
495
+ }
@@ -7,6 +7,8 @@ export interface DirectNotificationHandlers {
7
7
  readonly nextRequestId: NotificationPort["nextRequestId"];
8
8
  }
9
9
 
10
- export function createDirectNotificationPort(handlers: DirectNotificationHandlers): NotificationPort {
10
+ export function createDirectNotificationPort(
11
+ handlers: DirectNotificationHandlers,
12
+ ): NotificationPort {
11
13
  return { ...handlers };
12
14
  }
@@ -1,9 +1,9 @@
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.
5
5
 
6
- export const NOTIFICATIONS_FIELDS: Record<string, readonly string[]> = {
6
+ export const NOTIFICATIONS_FIELDS = {
7
7
  "NotificationAuthorityProjection": ["authorityId", "authorityEpoch"],
8
8
  "NotificationActionProjection": ["referenceId", "label"],
9
9
  "NotificationDraftProjection": ["sourceId", "severity", "title", "summary", "causeId", "actions", "replacementKey", "producerToken", "retentionClass", "presentationTimeUnixMs"],
@@ -16,4 +16,5 @@ export const NOTIFICATIONS_FIELDS: Record<string, readonly string[]> = {
16
16
  "NotificationRemovalProjection": ["record", "reason"],
17
17
  "NotificationRejection": ["code", "detail", "refreshRequired"],
18
18
  "NotificationChangedEvent": ["protocolVersion", "requestId", "authority", "previousLedgerRevision", "committedLedgerRevision", "affectedNotificationIds", "kind"],
19
- };
19
+ "NotificationHostError": ["code", "message", "retryable"],
20
+ } as const;