@assistant-ui/react-statewire 0.8.0 → 0.10.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.
@@ -49,6 +49,7 @@ import {
49
49
  toWireMessage,
50
50
  viewedLeafId,
51
51
  } from "./runCommands";
52
+ import { runsOptimistic } from "./runsOptimistic";
52
53
  import {
53
54
  resolveToolApprovalInput,
54
55
  resolveToolResultInput,
@@ -176,20 +177,60 @@ const useAssistantTransportThread = (
176
177
  };
177
178
  });
178
179
 
179
- const { converter, optimistic } = options;
180
+ const { converter, optimistic, runs: runsOption, materialize } = options;
181
+ const [runsSeam] = useState(() => runsOption !== undefined);
182
+ if (runsSeam !== (runsOption !== undefined))
183
+ throw new Error(
184
+ "statewire: the runs option must be stable — it was " +
185
+ (runsSeam ? "set" : "unset") +
186
+ " on first render and changed since",
187
+ );
188
+ const [materializeSeam] = useState(() => materialize !== undefined);
189
+ if (materializeSeam !== (materialize !== undefined))
190
+ throw new Error(
191
+ "statewire: the materialize option must be stable — it was " +
192
+ (materializeSeam ? "set" : "unset") +
193
+ " on first render and changed since",
194
+ );
195
+
196
+ const project = useCallback(
197
+ (state: unknown): unknown => {
198
+ const fold: AssistantTransportThread.Optimistic<unknown> | undefined =
199
+ runsOption !== undefined
200
+ ? (draft, command, ctx) => {
201
+ runsOptimistic(
202
+ runsOption === true ? draft : runsOption(draft as never),
203
+ { method: command.type, params: [command] },
204
+ ctx,
205
+ );
206
+ optimistic?.(draft, command, ctx);
207
+ }
208
+ : optimistic;
209
+ let next = fold
210
+ ? foldOptimistic(
211
+ state,
212
+ [...queue.inTransit, ...queue.queued],
213
+ fold,
214
+ ctxOf,
215
+ )
216
+ : state;
217
+ if (materialize) {
218
+ try {
219
+ next = applyOptimistic(next, (draft) => materialize(draft as never));
220
+ } catch (error) {
221
+ console.error(
222
+ "statewire: materialize threw; publishing without its update",
223
+ error,
224
+ );
225
+ }
226
+ }
227
+ return next;
228
+ },
229
+ [runsOption, optimistic, materialize, queue, ctxOf],
230
+ );
180
231
  const converted = useMemo(
181
- () =>
182
- converter(
183
- optimistic
184
- ? foldOptimistic(
185
- agentState,
186
- [...queue.inTransit, ...queue.queued],
187
- optimistic,
188
- ctxOf,
189
- )
190
- : agentState,
191
- ),
192
- [converter, optimistic, agentState, queue, ctxOf],
232
+ () => converter(project(agentState)),
233
+ [converter, project, agentState],
193
234
  );
194
235
  const convertedRef = useRef(converted);
195
236
  convertedRef.current = converted;
@@ -261,7 +302,7 @@ const useAssistantTransportThread = (
261
302
  );
262
303
 
263
304
  const handleEdit = (message: AppendMessage) => {
264
- const command = resolveEditCommand(message);
305
+ const command = resolveEditCommand(convertedRef.current.messages, message);
265
306
  void toolInvocations.abort().then(() => dispatch(command));
266
307
  };
267
308
 
@@ -439,16 +480,7 @@ const useAssistantTransportThread = (
439
480
  onLoadExternalState: (imported: unknown) => {
440
481
  void commands.importState(imported).catch(() => {});
441
482
  // reset() aborts tools before React re-renders — gate their late results against the imported state
442
- convertedRef.current = converter(
443
- optimistic
444
- ? foldOptimistic(
445
- imported,
446
- [...queue.inTransit, ...queue.queued],
447
- optimistic,
448
- ctxOf,
449
- )
450
- : imported,
451
- );
483
+ convertedRef.current = converter(project(imported));
452
484
  toolInvocations.reset();
453
485
  setToolStatuses(EMPTY_TOOL_STATUSES);
454
486
  },
@@ -524,6 +556,8 @@ export namespace AssistantTransportThread {
524
556
  readonly type: "run/edit";
525
557
  readonly message: RunUserMessage;
526
558
  readonly sourceId: string;
559
+ /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
560
+ readonly rollbackTo: string | null;
527
561
  };
528
562
 
529
563
  export type RunContinueCommand = {
@@ -583,6 +617,8 @@ export namespace AssistantTransportThread {
583
617
  export type RunReloadCommand = {
584
618
  readonly type: "run/reload";
585
619
  readonly sourceId: string;
620
+ /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
621
+ readonly rollbackTo: string | null;
586
622
  };
587
623
 
588
624
  export type RunCommand =
@@ -653,6 +689,10 @@ export namespace AssistantTransportThread {
653
689
  initialState: T;
654
690
  converter: StateConverter<T>;
655
691
  optimistic?: Optimistic<T> | undefined;
692
+ /** Folds the lib's run-dialect optimistic reducer before `optimistic`: `true` reads the run mounts off the state root; a selector picks a nested mount. */
693
+ runs?: true | ((state: T) => unknown) | undefined;
694
+ /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */
695
+ materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;
656
696
  api: string;
657
697
  resumeApi?: string | undefined;
658
698
  protocol?: Protocol | undefined;
@@ -12,6 +12,7 @@ import { resource } from "@assistant-ui/tap";
12
12
  import { StatewireSSE } from "statewire";
13
13
  import { useStatewireCommands, useStatewireState } from "statewire/host";
14
14
  import { StatewireThread } from "./StatewireThread";
15
+ import { runsMaterialize } from "./runsMaterialize";
15
16
  import { useStatewireRuns } from "./hooks";
16
17
  import { sendCommand, toThreadMessage } from "./__tests__/testHelpers";
17
18
 
@@ -66,6 +67,23 @@ const withRun = (
66
67
  ],
67
68
  });
68
69
 
70
+ const rollbackMaterialize = (draft: RunsServerState): void =>
71
+ runsMaterialize(draft, {
72
+ append: (m) =>
73
+ draft.messages.push({
74
+ id: m.id,
75
+ role: m.role,
76
+ text: m.parts.map((p) => (p.type === "text" ? p.text : "")).join(""),
77
+ }),
78
+ rollback: (to) => {
79
+ if (to === null) {
80
+ draft.messages = [];
81
+ return;
82
+ }
83
+ draft.messages.splice(draft.messages.findIndex((m) => m.id === to) + 1);
84
+ },
85
+ });
86
+
69
87
  const converter: StatewireThread.RunsStateConverter<RunsServerState> = (
70
88
  state,
71
89
  ) => ({
@@ -322,7 +340,7 @@ describe("StatewireThread runs mode", () => {
322
340
  );
323
341
  });
324
342
 
325
- it("projects dispatching items as in-flight messages, deduped by id", async () => {
343
+ it("keeps dispatch limbo out of messages when no materialize option is set", async () => {
326
344
  const server = createServer({
327
345
  messages: [{ id: "m1", role: "user", text: "hi" }],
328
346
  ...withRun({
@@ -331,7 +349,6 @@ describe("StatewireThread runs mode", () => {
331
349
  dispatching: {
332
350
  trigger: "message-send",
333
351
  messages: [
334
- { id: "m1", role: "user", parts: [{ type: "text", text: "hi" }] },
335
352
  { id: "d1", role: "user", parts: [{ type: "text", text: "go" }] },
336
353
  ],
337
354
  },
@@ -339,10 +356,49 @@ describe("StatewireThread runs mode", () => {
339
356
  });
340
357
  const { aui, runs } = mountThread({ transport: server.transport });
341
358
 
342
- await waitFor(() => expect(runs().dispatching?.messages).toHaveLength(2));
359
+ await waitFor(() => expect(runs().dispatching?.messages).toHaveLength(1));
360
+ expect(
361
+ aui()
362
+ .thread()
363
+ .getState()
364
+ .messages.map((m) => m.id),
365
+ ).toEqual(["m1"]);
366
+ });
367
+
368
+ it("projects the dispatch record through the materialize fold", async () => {
369
+ const server = createServer({
370
+ messages: [{ id: "m1", role: "user", text: "hi" }],
371
+ ...withRun({
372
+ status: "running",
373
+ runId: "run-1",
374
+ dispatching: {
375
+ trigger: "message-send",
376
+ messages: [
377
+ { id: "d1", role: "user", parts: [{ type: "text", text: "go" }] },
378
+ ],
379
+ },
380
+ }),
381
+ });
382
+ const { aui, runs } = mountThread({
383
+ transport: server.transport,
384
+ materialize: (draft) =>
385
+ runsMaterialize(draft, {
386
+ append: (m) =>
387
+ draft.messages.push({
388
+ id: m.id,
389
+ role: m.role,
390
+ text: m.parts
391
+ .map((p) => (p.type === "text" ? p.text : ""))
392
+ .join(""),
393
+ }),
394
+ }),
395
+ });
396
+
397
+ await waitFor(() => expect(runs().dispatching?.messages).toHaveLength(1));
343
398
  const messages = aui().thread().getState().messages;
344
399
  expect(messages.map((m) => m.id)).toEqual(["m1", "d1"]);
345
- expect(messages[1]!.role).toBe("user");
400
+ // Epoch createdAt proves d1 came through the converter (state-side fold).
401
+ expect(messages[1]!.createdAt.getTime()).toBe(0);
346
402
 
347
403
  act(() => {
348
404
  server.cell.state!.messages.push({ id: "d1", role: "user", text: "go" });
@@ -357,7 +413,7 @@ describe("StatewireThread runs mode", () => {
357
413
  ).toEqual(["m1", "d1"]);
358
414
  });
359
415
 
360
- it("renders the edit replacement in branch position while it dispatches", async () => {
416
+ it("renders the edit replacement in branch position through the materialize fold", async () => {
361
417
  const server = createServer({
362
418
  messages: [
363
419
  { id: "u1", role: "user", text: "one" },
@@ -381,7 +437,10 @@ describe("StatewireThread runs mode", () => {
381
437
  },
382
438
  }),
383
439
  });
384
- const { aui, runs } = mountThread({ transport: server.transport });
440
+ const { aui, runs } = mountThread({
441
+ transport: server.transport,
442
+ materialize: rollbackMaterialize,
443
+ });
385
444
 
386
445
  await waitFor(() => expect(runs().status).toBe("running"));
387
446
  expect(
@@ -392,7 +451,7 @@ describe("StatewireThread runs mode", () => {
392
451
  ).toEqual(["u1", "a1", "u2b"]);
393
452
  });
394
453
 
395
- it("renders the rolled-back view for a reload dispatch", async () => {
454
+ it("renders the rolled-back view for a reload dispatch through the materialize fold", async () => {
396
455
  const server = createServer({
397
456
  messages: [
398
457
  { id: "u1", role: "user", text: "one" },
@@ -408,7 +467,10 @@ describe("StatewireThread runs mode", () => {
408
467
  },
409
468
  }),
410
469
  });
411
- const { aui, runs } = mountThread({ transport: server.transport });
470
+ const { aui, runs } = mountThread({
471
+ transport: server.transport,
472
+ materialize: rollbackMaterialize,
473
+ });
412
474
 
413
475
  await waitFor(() => expect(runs().status).toBe("running"));
414
476
  expect(
@@ -441,7 +503,10 @@ describe("StatewireThread runs mode", () => {
441
503
  },
442
504
  }),
443
505
  });
444
- const { aui, runs } = mountThread({ transport: server.transport });
506
+ const { aui, runs } = mountThread({
507
+ transport: server.transport,
508
+ materialize: rollbackMaterialize,
509
+ });
445
510
 
446
511
  await waitFor(() => expect(runs().status).toBe("running"));
447
512
  expect(
@@ -481,7 +546,10 @@ describe("StatewireThread runs mode", () => {
481
546
 
482
547
  it("flips the run optimistically for a dispatching send", async () => {
483
548
  const server = createRemoteServer();
484
- const { aui, runs } = mountThread({ transport: server.transport });
549
+ const { aui, runs } = mountThread({
550
+ transport: server.transport,
551
+ materialize: rollbackMaterialize,
552
+ });
485
553
 
486
554
  await waitFor(() =>
487
555
  expect(aui().thread().getState().isLoading).toBe(false),
@@ -936,6 +936,7 @@ describe("StatewireThread", () => {
936
936
  expect(server.received).toContainEqual({
937
937
  type: "run/edit",
938
938
  sourceId: "h1",
939
+ rollbackTo: null,
939
940
  message: {
940
941
  id: expect.any(String),
941
942
  role: "user",
@@ -976,6 +977,7 @@ describe("StatewireThread", () => {
976
977
  {
977
978
  type: "run/edit",
978
979
  sourceId: "h1",
980
+ rollbackTo: null,
979
981
  message: {
980
982
  id: expect.any(String),
981
983
  role: "user",
@@ -1279,6 +1281,7 @@ describe("StatewireThread", () => {
1279
1281
  expect(server.received).toContainEqual({
1280
1282
  type: "run/reload",
1281
1283
  sourceId: "a1",
1284
+ rollbackTo: "h1",
1282
1285
  }),
1283
1286
  );
1284
1287
  });
@@ -1301,6 +1304,7 @@ describe("StatewireThread", () => {
1301
1304
  expect(server.received).toContainEqual({
1302
1305
  type: "run/reload",
1303
1306
  sourceId: "a0",
1307
+ rollbackTo: null,
1304
1308
  }),
1305
1309
  );
1306
1310
  });
@@ -1341,6 +1345,7 @@ describe("StatewireThread", () => {
1341
1345
  {
1342
1346
  type: "run/edit",
1343
1347
  sourceId: "h1",
1348
+ rollbackTo: null,
1344
1349
  message: {
1345
1350
  id: expect.any(String),
1346
1351
  role: "user",
@@ -32,7 +32,6 @@ import {
32
32
  createRunQueueAdapter,
33
33
  resolveEditCommand,
34
34
  resolveReloadCommand,
35
- toDispatchingMessage,
36
35
  toWireMessage,
37
36
  viewedLeafId,
38
37
  } from "./runCommands";
@@ -93,6 +92,16 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
93
92
  " on first render and changed since",
94
93
  );
95
94
 
95
+ const materializeOption = (options as StatewireThread.RunsOptions<unknown>)
96
+ .materialize;
97
+ const [materializeSeam] = useState(() => materializeOption !== undefined);
98
+ if (materializeSeam !== (materializeOption !== undefined))
99
+ throw new Error(
100
+ "statewire: the materialize option must be stable — it was " +
101
+ (materializeSeam ? "set" : "unset") +
102
+ " on first render and changed since",
103
+ );
104
+
96
105
  const {
97
106
  state: transportState,
98
107
  commands,
@@ -111,6 +120,12 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
111
120
  );
112
121
  },
113
122
  }),
123
+ ...(materializeSeam && {
124
+ materialize: (draft: {}) =>
125
+ (latest.current as StatewireThread.RunsOptions<unknown>).materialize!(
126
+ draft,
127
+ ),
128
+ }),
114
129
  onCommandChange: (update, ctx) => {
115
130
  if (update.status === "acked" || update.status === "settled")
116
131
  retire(update.params[0]);
@@ -222,26 +237,9 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
222
237
  ) as StatewireThread.State,
223
238
  [converter, state, metadata],
224
239
  );
225
- // Dispatch limbo renders as in-flight messages; ids already converted win.
226
- // A rollbackTo key truncates to the rolled-back view first (null = root).
227
- const messages = useMemo((): StatewireThread.State["messages"] => {
228
- const record = runs?.dispatching ?? null;
229
- if (record === null) return converted.messages;
230
- let base = converted.messages;
231
- if ("rollbackTo" in record) {
232
- base =
233
- record.rollbackTo == null
234
- ? []
235
- : base.slice(
236
- 0,
237
- base.findIndex((m) => m.id === record.rollbackTo) + 1,
238
- );
239
- }
240
- const known = new Set(base.map((m) => m.id));
241
- const pending = record.messages.filter((e) => !known.has(e.id));
242
- if (pending.length === 0) return base;
243
- return [...base, ...pending.map(toDispatchingMessage)];
244
- }, [converted.messages, runs]);
240
+ // Dispatch limbo is a materialize concern: the fold makes the record
241
+ // concrete in state before conversion.
242
+ const messages = converted.messages;
245
243
  const queueItems = runs !== undefined ? runs.queue : converted.queue;
246
244
  const steerQueueItems =
247
245
  runs !== undefined ? runs.steerQueue : converted.steerQueue;
@@ -300,7 +298,7 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
300
298
  const handleAppend = (message: AppendMessage) => {
301
299
  dispatchSend(
302
300
  message.sourceId != null
303
- ? resolveEditCommand(message)
301
+ ? resolveEditCommand(messages, message)
304
302
  : {
305
303
  type: "run/steer",
306
304
  message: toWireMessage(message, crypto.randomUUID()),
@@ -315,7 +313,7 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
315
313
  };
316
314
 
317
315
  const handleEdit = (message: AppendMessage) => {
318
- dispatch(resolveEditCommand(message));
316
+ dispatch(resolveEditCommand(messages, message));
319
317
  };
320
318
 
321
319
  const thread = useResource(
@@ -439,6 +437,8 @@ export namespace StatewireThread {
439
437
  readonly type: "run/edit";
440
438
  readonly message: UserMessage;
441
439
  readonly sourceId: string;
440
+ /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
441
+ readonly rollbackTo: string | null;
442
442
  };
443
443
 
444
444
  export type RunContinueCommand = {
@@ -498,6 +498,8 @@ export namespace StatewireThread {
498
498
  export type RunReloadCommand = {
499
499
  readonly type: "run/reload";
500
500
  readonly sourceId: string;
501
+ /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
502
+ readonly rollbackTo: string | null;
501
503
  };
502
504
 
503
505
  export type RunCommand =
@@ -599,6 +601,14 @@ export namespace StatewireThread {
599
601
  readonly error: RunsError | null;
600
602
  };
601
603
 
604
+ /** App-shaped effects `runsMaterialize` applies for the dispatch record. */
605
+ export type MaterializeEffects = {
606
+ /** Append one dispatched message to the app's committed message state. */
607
+ append: (message: RunsQueueEntry) => void;
608
+ /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */
609
+ rollback?: (to: string | null) => void;
610
+ };
611
+
602
612
  /** The runs mount as replicated: the run entries plus the top-level status projection. */
603
613
  export type RunsState = {
604
614
  /** Projection of `runs[0]?.status ?? "ready"`. */
@@ -716,6 +726,8 @@ export namespace StatewireThread {
716
726
  Record<string, (...args: any[]) => unknown>
717
727
  >
718
728
  | undefined;
729
+ /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */
730
+ materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;
719
731
  };
720
732
  }
721
733
 
@@ -578,6 +578,7 @@ describe("deep-agent e2e", () => {
578
578
  parts: [{ type: "text", text: "better question" }],
579
579
  },
580
580
  sourceId: "h2",
581
+ rollbackTo: "a1",
581
582
  },
582
583
  ]);
583
584
  expect("parentId" in fetchMock.requests[0]!.body).toBe(false);
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { AssistantTransportThread } from "./AssistantTransportThread";
2
2
  export { StatewireThread } from "./StatewireThread";
3
+ export { runsMaterialize } from "./runsMaterialize";
3
4
  export {
4
5
  useAssistantTransportSendCommand,
5
6
  useAssistantTransportState,
@@ -2,10 +2,8 @@ import type {
2
2
  AppendMessage,
3
3
  ExternalThreadQueueAdapter,
4
4
  QueuePlacement,
5
- ThreadMessage,
6
5
  } from "@assistant-ui/core";
7
6
  import type { AssistantTransportThread } from "./AssistantTransportThread";
8
- import type { StatewireThread } from "./StatewireThread";
9
7
 
10
8
  export const toWireMessage = (
11
9
  message: AppendMessage,
@@ -69,26 +67,6 @@ export const toQueueItemState = (
69
67
  ),
70
68
  });
71
69
 
72
- export const toDispatchingMessage = (
73
- item: StatewireThread.RunsQueueEntry,
74
- ): ThreadMessage => ({
75
- id: item.id,
76
- role: "user",
77
- createdAt: new Date(),
78
- content: item.parts.map((part) =>
79
- part.type === "text"
80
- ? part
81
- : {
82
- type: "file" as const,
83
- data: part.url,
84
- mimeType: part.mediaType,
85
- ...(part.filename !== undefined && { filename: part.filename }),
86
- },
87
- ),
88
- attachments: [],
89
- metadata: { custom: {} },
90
- });
91
-
92
70
  const placementFields = (placement: QueuePlacement) => ({
93
71
  ...(placement.insertAfter !== undefined && {
94
72
  insertAfter: placement.insertAfter,
@@ -103,14 +81,21 @@ export const viewedLeafId = (
103
81
  ): string | null => messages.at(-1)?.id ?? null;
104
82
 
105
83
  export const resolveEditCommand = (
84
+ messages: readonly { id: string }[],
106
85
  message: AppendMessage,
107
86
  ): AssistantTransportThread.RunEditCommand => {
108
87
  if (message.sourceId == null)
109
88
  throw new Error("statewire: run/edit requires a sourceId");
89
+ const index = messages.findIndex((m) => m.id === message.sourceId);
90
+ if (index === -1)
91
+ throw new Error(
92
+ `statewire: run/edit source "${message.sourceId}" is unknown`,
93
+ );
110
94
  return {
111
95
  type: "run/edit",
112
96
  message: toWireMessage(message, crypto.randomUUID()),
113
97
  sourceId: message.sourceId,
98
+ rollbackTo: messages[index - 1]?.id ?? null,
114
99
  };
115
100
  };
116
101
 
@@ -135,7 +120,7 @@ export const createRunQueueAdapter = (
135
120
  lane: "queue" | "steer",
136
121
  message: AppendMessage,
137
122
  ): AssistantTransportThread.RunCommand => {
138
- if (message.sourceId != null) return resolveEditCommand(message);
123
+ if (message.sourceId != null) return resolveEditCommand(messages, message);
139
124
  const fields = {
140
125
  message: toWireMessage(message, crypto.randomUUID()),
141
126
  anchorMessageId: viewedLeafId(messages),
@@ -189,5 +174,5 @@ export const resolveReloadCommand = (
189
174
  throw new Error(
190
175
  "statewire: run/reload requires an assistant message to regenerate",
191
176
  );
192
- return { type: "run/reload", sourceId: target.id };
177
+ return { type: "run/reload", sourceId: target.id, rollbackTo: parentId };
193
178
  };
@@ -0,0 +1,91 @@
1
+ // Contract tests for the run-dialect materialize fold: the dispatch record
2
+ // becomes concrete through app-shaped effects, in record order.
3
+
4
+ import { describe, expect, it } from "vitest";
5
+ import { runsMaterialize } from "./runsMaterialize";
6
+
7
+ type Draft = Record<string, any>;
8
+
9
+ const mount = (dispatching: Draft | null): Draft => ({
10
+ status: "running",
11
+ runs: [
12
+ {
13
+ runId: "run-1",
14
+ status: "running",
15
+ queue: [],
16
+ steerQueue: [],
17
+ dispatching,
18
+ error: null,
19
+ },
20
+ ],
21
+ });
22
+
23
+ const message = (id: string) => ({
24
+ id,
25
+ role: "user" as const,
26
+ parts: [{ type: "text" as const, text: id }],
27
+ });
28
+
29
+ const record = () => {
30
+ const appended: string[] = [];
31
+ const rollbacks: (string | null)[] = [];
32
+ return {
33
+ appended,
34
+ rollbacks,
35
+ effects: {
36
+ append: (m: { id: string }) => appended.push(m.id),
37
+ rollback: (to: string | null) => {
38
+ rollbacks.push(to);
39
+ appended.push("(rollback)");
40
+ },
41
+ },
42
+ };
43
+ };
44
+
45
+ describe("runsMaterialize", () => {
46
+ it("does nothing while resting or between dispatches", () => {
47
+ const { appended, effects } = record();
48
+ runsMaterialize({ status: "ready", runs: [] }, effects);
49
+ runsMaterialize(mount(null), effects);
50
+ expect(appended).toEqual([]);
51
+ });
52
+
53
+ it("appends each dispatched message in record order", () => {
54
+ const { appended, effects } = record();
55
+ runsMaterialize(
56
+ mount({
57
+ trigger: "message-send",
58
+ messages: [message("m1"), message("m2")],
59
+ }),
60
+ effects,
61
+ );
62
+ expect(appended).toEqual(["m1", "m2"]);
63
+ });
64
+
65
+ it("rolls back before appending on rewind dispatches, null naming the root", () => {
66
+ const { appended, rollbacks, effects } = record();
67
+ runsMaterialize(
68
+ mount({
69
+ trigger: "message-edit",
70
+ messages: [message("m3")],
71
+ rollbackTo: "m1",
72
+ }),
73
+ effects,
74
+ );
75
+ runsMaterialize(
76
+ mount({ trigger: "message-reload", messages: [], rollbackTo: null }),
77
+ effects,
78
+ );
79
+ expect(appended).toEqual(["(rollback)", "m3", "(rollback)"]);
80
+ expect(rollbacks).toEqual(["m1", null]);
81
+ });
82
+
83
+ it("throws on a rewind dispatch without a rollback effect", () => {
84
+ expect(() =>
85
+ runsMaterialize(
86
+ mount({ trigger: "message-edit", messages: [], rollbackTo: "m1" }),
87
+ { append: () => {} },
88
+ ),
89
+ ).toThrow("rollbackTo");
90
+ });
91
+ });
@@ -0,0 +1,23 @@
1
+ import type { StatewireThread } from "./StatewireThread";
2
+
3
+ /**
4
+ * The run dialect's materialize fold: makes the mount's dispatch record
5
+ * concrete through app-shaped effects, in record order.
6
+ */
7
+ export const runsMaterialize = (
8
+ mount: unknown,
9
+ effects: StatewireThread.MaterializeEffects,
10
+ ): void => {
11
+ const record =
12
+ (mount as StatewireThread.RunsState).runs?.[0]?.dispatching ?? null;
13
+ if (record === null) return;
14
+ if ("rollbackTo" in record) {
15
+ if (effects.rollback === undefined) {
16
+ throw new Error(
17
+ "statewire: the dispatch record carries rollbackTo but no rollback effect was provided",
18
+ );
19
+ }
20
+ effects.rollback(record.rollbackTo ?? null);
21
+ }
22
+ for (const message of record.messages) effects.append(message);
23
+ };