@assistant-ui/react-statewire 0.3.0 → 0.4.1

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.
@@ -13,6 +13,7 @@ import type { ExternalThreadMessage } from "@assistant-ui/react";
13
13
  import { AssistantTransportThread } from "./AssistantTransportThread";
14
14
  import { useAssistantTransportSendCommand } from "./hooks";
15
15
  import type {
16
+ InputRequestState,
16
17
  RunEditCommand,
17
18
  RunSteerCommand,
18
19
  RunUserMessage,
@@ -39,6 +40,7 @@ type LangGraphMessage =
39
40
  type LangGraphState = {
40
41
  messages: LangGraphMessage[];
41
42
  todos: string[];
43
+ inputRequests?: InputRequestState[];
42
44
  };
43
45
 
44
46
  const INITIAL_STATE: LangGraphState = { messages: [], todos: [] };
@@ -141,6 +143,7 @@ const createConverter = () => {
141
143
  messages,
142
144
  isRunning: meta.isSending,
143
145
  state: { todos: state.todos },
146
+ inputRequests: state.inputRequests ?? [],
144
147
  };
145
148
  };
146
149
 
@@ -325,6 +328,7 @@ describe("deep-agent e2e", () => {
325
328
  role: "user",
326
329
  parts: [{ type: "text", text: "what's the weather in SF?" }],
327
330
  },
331
+ anchorMessageId: null,
328
332
  },
329
333
  ]);
330
334
 
@@ -389,21 +393,32 @@ describe("deep-agent e2e", () => {
389
393
  path: ["messages", "1", "tool_calls"],
390
394
  value: [{ id: "tc1", name: "get_weather", args: { city: "SF" } }],
391
395
  },
396
+ {
397
+ type: "set",
398
+ path: ["inputRequests"],
399
+ value: [
400
+ {
401
+ type: "tool-call",
402
+ id: "in-tc1",
403
+ toolCallId: "tc1",
404
+ response: null,
405
+ },
406
+ ],
407
+ },
392
408
  ],
393
409
  });
394
410
  servers[0]!.done();
395
411
 
396
- // 3 — frontend tool executes and posts add-tool-result in a follow-up run.
412
+ // 3 — frontend tool executes and answers the parked input request via
413
+ // run/input in a follow-up run.
397
414
  await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
398
415
  const r2 = fetchMock.requests[1]!;
399
416
  expect(r2.url).toBe("https://sync.example.com/api/chat");
400
417
  expect(r2.body.commands).toEqual([
401
418
  {
402
- type: "add-tool-result",
403
- toolCallId: "tc1",
404
- toolName: "get_weather",
405
- result: { temp: 20, city: "SF" },
406
- isError: false,
419
+ type: "run/input",
420
+ requestId: "in-tc1",
421
+ response: { output: { temp: 20, city: "SF" } },
407
422
  },
408
423
  ]);
409
424
  // The follow-up run posts the converged state from run 1.
package/src/index.ts CHANGED
@@ -15,8 +15,6 @@ export namespace AssistantTransportThread {
15
15
  export type State = types.AssistantTransportState;
16
16
  export type ConnectionMetadata = types.AssistantTransportConnectionMetadata;
17
17
  export type StateConverter<T> = types.AssistantTransportStateConverter<T>;
18
- export type AddMessageCommand = types.AddMessageCommand;
19
- export type AddToolResultCommand = types.AddToolResultCommand;
20
18
  export type RunCommand = types.RunCommand;
21
19
  export type RunEnqueueCommand = types.RunEnqueueCommand;
22
20
  export type RunSteerCommand = types.RunSteerCommand;
@@ -37,11 +35,7 @@ export namespace AssistantTransportThread {
37
35
  export type RunQueueItem = types.RunQueueItem;
38
36
  export type RunPlacement = types.RunPlacement;
39
37
  export type SendCommandsRequestBody = types.SendCommandsRequestBody;
40
- export type UserMessage = types.UserMessage;
41
- export type AssistantMessage = types.AssistantMessage;
42
- export type UserMessagePart = types.UserMessagePart;
43
38
  export type TextPart = types.TextPart;
44
39
  export type FilePart = types.FilePart;
45
- export type ImagePart = types.ImagePart;
46
40
  export type HeadersValue = types.HeadersValue;
47
41
  }
@@ -17,11 +17,14 @@ export const resolveToolResultInput = (
17
17
  isError: boolean;
18
18
  artifact?: ReadonlyJSONValue | undefined;
19
19
  },
20
- ): RunInputCommand | undefined => {
20
+ ): RunInputCommand => {
21
21
  const request = inputRequests.find(
22
22
  (r) => r.type === "tool-call" && r.toolCallId === options.toolCallId,
23
23
  );
24
- if (request === undefined) return undefined;
24
+ if (request === undefined)
25
+ throw new Error(
26
+ `statewire: no tool-call input request for tool call "${options.toolCallId}"`,
27
+ );
25
28
  assertUnanswered(request);
26
29
  return {
27
30
  type: "run/input",
@@ -46,7 +46,8 @@ const converter: AssistantTransportStateConverter<TestState> = (
46
46
  }) as unknown as ExternalThreadMessage,
47
47
  ),
48
48
  ...meta.pendingCommands.flatMap((c, i) =>
49
- (c.type === "run/steer" || c.type === "add-message") &&
49
+ // The legacy runtime still surfaces add-message pending commands.
50
+ (c.type === "run/steer" || (c.type as string) === "add-message") &&
50
51
  "message" in c &&
51
52
  c.message.role === "user"
52
53
  ? [
@@ -73,10 +74,11 @@ const converter: AssistantTransportStateConverter<TestState> = (
73
74
 
74
75
  type RecordedRequest = { url: string; body: Record<string, any> };
75
76
 
76
- // deliberate divergence: the re-implementation sends finalized user messages
77
- // as run/steer (with a client-generated message id, no per-command
78
- // parentId/sourceId — parentId rides the request body); legacy add-message
79
- // bodies are translated before comparison. add-tool-result is unchanged.
77
+ // deliberate divergence: the re-implementation speaks the run/* dialect —
78
+ // user messages go out as run/steer (client-generated message id, no
79
+ // per-command parentId/sourceId — parentId rides the request body) and tool
80
+ // results as run/input against the parked request; legacy add-message /
81
+ // add-tool-result bodies are translated before comparison.
80
82
  const renameWire = (commands: unknown) =>
81
83
  (commands as Record<string, any>[]).map((c) =>
82
84
  c.type === "add-message"
@@ -87,8 +89,20 @@ const renameWire = (commands: unknown) =>
87
89
  role: c.message.role,
88
90
  parts: c.message.parts,
89
91
  },
92
+ anchorMessageId: expect.toSatisfy(
93
+ (v) => v === null || typeof v === "string",
94
+ ),
90
95
  }
91
- : c,
96
+ : c.type === "add-tool-result"
97
+ ? {
98
+ type: "run/input",
99
+ requestId: `req-${c.toolCallId}`,
100
+ response: {
101
+ output: c.result,
102
+ ...(c.isError && { isError: true }),
103
+ },
104
+ }
105
+ : c,
92
106
  );
93
107
 
94
108
  // Scripted server: request N gets transcript N, streamed whole.
@@ -265,6 +279,12 @@ const observeNew = async (): Promise<{
265
279
 
266
280
  type ToolState = TestState & {
267
281
  toolCall?: { id: string; name: string; argsText: string } | null;
282
+ inputRequests?: {
283
+ type: "tool-call";
284
+ id: string;
285
+ toolCallId: string;
286
+ response: null;
287
+ }[];
268
288
  note?: string;
269
289
  };
270
290
 
@@ -272,7 +292,10 @@ const toolConverter: AssistantTransportStateConverter<ToolState> = (
272
292
  state,
273
293
  meta,
274
294
  ) => {
275
- const base = converter(state, meta);
295
+ const base = {
296
+ ...converter(state, meta),
297
+ inputRequests: state.inputRequests ?? [],
298
+ };
276
299
  if (!state.toolCall) return base;
277
300
  return {
278
301
  ...base,
@@ -318,6 +341,18 @@ const TOOL_TRANSCRIPT: string[][] = [
318
341
  path: ["toolCall"],
319
342
  value: { id: "tc1", name: "probe_tool", argsText: '{"x":1}' },
320
343
  },
344
+ {
345
+ type: "set",
346
+ path: ["inputRequests"],
347
+ value: [
348
+ {
349
+ type: "tool-call",
350
+ id: "req-tc1",
351
+ toolCallId: "tc1",
352
+ response: null,
353
+ },
354
+ ],
355
+ },
321
356
  ],
322
357
  }),
323
358
  "data: [DONE]\n\n",
@@ -327,6 +362,7 @@ const TOOL_TRANSCRIPT: string[][] = [
327
362
  type: "update-state",
328
363
  operations: [
329
364
  { type: "set", path: ["toolCall"], value: null },
365
+ { type: "set", path: ["inputRequests"], value: [] },
330
366
  {
331
367
  type: "set",
332
368
  path: ["messages"],
@@ -78,7 +78,12 @@ const placementFields = (placement: QueuePlacement) => ({
78
78
  }),
79
79
  });
80
80
 
81
+ export const viewedLeafId = (
82
+ messages: readonly { id: string }[],
83
+ ): string | null => messages.at(-1)?.id ?? null;
84
+
81
85
  export const createRunQueueAdapter = (
86
+ messages: readonly { id: string }[],
82
87
  queueItems: readonly RunQueueItem[],
83
88
  steerQueueItems: readonly RunQueueItem[] | undefined,
84
89
  dispatch: (command: RunCommand) => void,
@@ -96,11 +101,13 @@ export const createRunQueueAdapter = (
96
101
  dispatch({
97
102
  type: "run/enqueue",
98
103
  message: toWireMessage(message, crypto.randomUUID()),
104
+ anchorMessageId: viewedLeafId(messages),
99
105
  }),
100
106
  steer: (message) =>
101
107
  dispatch({
102
108
  type: "run/steer",
103
109
  message: toWireMessage(message, crypto.randomUUID()),
110
+ anchorMessageId: viewedLeafId(messages),
104
111
  }),
105
112
  move: (queueItemId, placement) => {
106
113
  const lane = placement.lane ?? laneOf(queueItemId);
@@ -142,5 +149,9 @@ export const resolveReloadCommand = (
142
149
  throw new Error(
143
150
  "statewire: run/reload requires an assistant message to regenerate",
144
151
  );
145
- return { type: "run/reload", sourceId: target.id };
152
+ return {
153
+ type: "run/reload",
154
+ sourceId: target.id,
155
+ messageId: crypto.randomUUID(),
156
+ };
146
157
  };
@@ -67,6 +67,7 @@ describe("AssistantTransportThread", () => {
67
67
  role: "user",
68
68
  parts: [{ type: "text", text: "hello" }],
69
69
  },
70
+ anchorMessageId: null,
70
71
  },
71
72
  ]);
72
73
  expect(fetchMock.requests[0]!.body.state).toEqual(INITIAL_STATE);
@@ -246,10 +247,12 @@ describe("AssistantTransportThread", () => {
246
247
  });
247
248
 
248
249
  sendCommand(aui, {
249
- type: "add-message",
250
- message: { role: "user", parts: [{ type: "text", text: "hello" }] },
251
- parentId: null,
252
- sourceId: null,
250
+ type: "run/steer",
251
+ message: {
252
+ id: "u1",
253
+ role: "user",
254
+ parts: [{ type: "text", text: "hello" }],
255
+ },
253
256
  });
254
257
  await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
255
258
  await waitFor(() =>
@@ -1120,12 +1123,10 @@ describe("AssistantTransportThread", () => {
1120
1123
  expect(aui().thread().getState().isRunning).toBe(false),
1121
1124
  );
1122
1125
 
1123
- // Give any stray add-tool-result dispatch a chance to fire.
1126
+ // Give any stray run/input dispatch a chance to fire.
1124
1127
  await new Promise((resolve) => setTimeout(resolve, 20));
1125
1128
  expect(
1126
- allCommands(fetchMock.requests).filter(
1127
- (c) => c.type === "add-tool-result",
1128
- ),
1129
+ allCommands(fetchMock.requests).filter((c) => c.type === "run/input"),
1129
1130
  ).toEqual([]);
1130
1131
  });
1131
1132
 
@@ -1248,6 +1249,7 @@ describe("AssistantTransportThread", () => {
1248
1249
  role: "user",
1249
1250
  parts: [{ type: "text", text: "again" }],
1250
1251
  },
1252
+ anchorMessageId: "a1",
1251
1253
  },
1252
1254
  ]);
1253
1255
 
@@ -1306,7 +1308,7 @@ describe("AssistantTransportThread", () => {
1306
1308
  servers[1]!.done();
1307
1309
  });
1308
1310
 
1309
- it("executes frontend tools and posts add-tool-result in a follow-up run", async () => {
1311
+ it("executes frontend tools and posts run/input in a follow-up run", async () => {
1310
1312
  const fetchMock = installFetch();
1311
1313
  const servers: StreamResponse[] = [];
1312
1314
  fetchMock.setHandler(() => {
@@ -1353,11 +1355,9 @@ describe("AssistantTransportThread", () => {
1353
1355
  await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
1354
1356
  expect(fetchMock.requests[1]!.body.commands).toEqual([
1355
1357
  {
1356
- type: "add-tool-result",
1357
- toolCallId: "tc1",
1358
- toolName: "probe_tool",
1359
- result: { probed: true },
1360
- isError: false,
1358
+ type: "run/input",
1359
+ requestId: "req-tc1",
1360
+ response: { output: { probed: true } },
1361
1361
  },
1362
1362
  ]);
1363
1363
  servers[1]!.done();
@@ -1414,11 +1414,9 @@ describe("AssistantTransportThread", () => {
1414
1414
  await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
1415
1415
  expect(fetchMock.requests[1]!.body.commands).toEqual([
1416
1416
  {
1417
- type: "add-tool-result",
1418
- toolCallId: "tc1",
1419
- toolName: "probe_tool",
1420
- result: { answer: "yes" },
1421
- isError: false,
1417
+ type: "run/input",
1418
+ requestId: "req-tc1",
1419
+ response: { output: { answer: "yes" } },
1422
1420
  },
1423
1421
  ]);
1424
1422
  servers[1]!.done();
@@ -1463,11 +1461,9 @@ describe("AssistantTransportThread", () => {
1463
1461
 
1464
1462
  await waitFor(() =>
1465
1463
  expect(allCommands(fetchMock.requests)).toContainEqual({
1466
- type: "add-tool-result",
1467
- toolCallId: "tc1",
1468
- toolName: "probe_tool",
1469
- result: "Tool execution was cancelled.",
1470
- isError: true,
1464
+ type: "run/input",
1465
+ requestId: "req-tc1",
1466
+ response: { output: "Tool execution was cancelled.", isError: true },
1471
1467
  }),
1472
1468
  );
1473
1469
  servers.at(-1)!.done();
@@ -1515,11 +1511,9 @@ describe("AssistantTransportThread", () => {
1515
1511
  await waitFor(() => {
1516
1512
  const commands = allCommands(fetchMock.requests);
1517
1513
  expect(commands).toContainEqual({
1518
- type: "add-tool-result",
1519
- toolCallId: "tc1",
1520
- toolName: "probe_tool",
1521
- result: "Tool execution was cancelled.",
1522
- isError: true,
1514
+ type: "run/input",
1515
+ requestId: "req-tc1",
1516
+ response: { output: "Tool execution was cancelled.", isError: true },
1523
1517
  });
1524
1518
  expect(commands).toContainEqual({
1525
1519
  type: "run/steer",
@@ -1528,6 +1522,7 @@ describe("AssistantTransportThread", () => {
1528
1522
  role: "user",
1529
1523
  parts: [{ type: "text", text: "next question" }],
1530
1524
  },
1525
+ anchorMessageId: "a-tool",
1531
1526
  });
1532
1527
  });
1533
1528
  await waitFor(() => expect(metas.at(-1)!.toolStatuses).toEqual({}));
@@ -1967,7 +1962,11 @@ describe("reload", () => {
1967
1962
  aui().thread().message({ id: "m2" }).reload();
1968
1963
  await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
1969
1964
  expect(fetchMock.requests[1]!.body.commands).toEqual([
1970
- { type: "run/reload", sourceId: "m2" },
1965
+ {
1966
+ type: "run/reload",
1967
+ sourceId: "m2",
1968
+ messageId: expect.stringMatching(/^[0-9a-f-]{36}$/),
1969
+ },
1971
1970
  ]);
1972
1971
  expect("parentId" in fetchMock.requests[1]!.body).toBe(false);
1973
1972
  });
@@ -1998,7 +1997,11 @@ describe("reload", () => {
1998
1997
  aui().thread().message({ id: "m2" }).reload();
1999
1998
  await waitFor(() => expect(fetchMock.requests).toHaveLength(3));
2000
1999
  expect(fetchMock.requests[2]!.body.commands).toEqual([
2001
- { type: "run/reload", sourceId: "m2" },
2000
+ {
2001
+ type: "run/reload",
2002
+ sourceId: "m2",
2003
+ messageId: expect.stringMatching(/^[0-9a-f-]{36}$/),
2004
+ },
2002
2005
  ]);
2003
2006
  });
2004
2007
  });
@@ -2202,6 +2205,7 @@ describe("server queue projection", () => {
2202
2205
  role: "user",
2203
2206
  parts: [{ type: "text", text: "hello" }],
2204
2207
  },
2208
+ anchorMessageId: null,
2205
2209
  },
2206
2210
  ]);
2207
2211
  });
@@ -2236,6 +2240,7 @@ describe("server queue projection", () => {
2236
2240
  role: "user",
2237
2241
  parts: [{ type: "text", text: "steer me" }],
2238
2242
  },
2243
+ anchorMessageId: null,
2239
2244
  }),
2240
2245
  );
2241
2246
  });
@@ -2442,7 +2447,7 @@ describe("input requests", () => {
2442
2447
  ]);
2443
2448
  });
2444
2449
 
2445
- it("falls back to add-tool-result without a matching pending request", async () => {
2450
+ it("throws without a matching pending request", async () => {
2446
2451
  const fetchMock = installFetch();
2447
2452
  const { aui } = mountThread({
2448
2453
  converter: requestConverter(),
@@ -2463,18 +2468,12 @@ describe("input requests", () => {
2463
2468
  await waitFor(() =>
2464
2469
  expect(aui().thread().getState().messages).toHaveLength(1),
2465
2470
  );
2466
- toolCallPart(aui).addToolResult({ ok: true });
2471
+ expect(() => toolCallPart(aui).addToolResult({ ok: true })).toThrow(
2472
+ 'statewire: no tool-call input request for tool call "tc1"',
2473
+ );
2467
2474
 
2468
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2469
- expect(fetchMock.requests[0]!.body.commands).toEqual([
2470
- {
2471
- type: "add-tool-result",
2472
- toolCallId: "tc1",
2473
- toolName: "probe_tool",
2474
- result: { ok: true },
2475
- isError: false,
2476
- },
2477
- ]);
2475
+ await new Promise((resolve) => setTimeout(resolve, 20));
2476
+ expect(fetchMock.requests).toHaveLength(0);
2478
2477
  });
2479
2478
 
2480
2479
  it("throws on answering a request that already carries a response", async () => {
package/src/types.ts CHANGED
@@ -1,4 +1,3 @@
1
- import type { ToolModelContentPart } from "assistant-stream";
2
1
  import type { ReadonlyJSONValue } from "assistant-stream/utils";
3
2
  import type {
4
3
  AttachmentAdapter,
@@ -19,46 +18,6 @@ export type TextPart = {
19
18
  readonly text: string;
20
19
  };
21
20
 
22
- export type ImagePart = {
23
- readonly type: "image";
24
- readonly image: string;
25
- };
26
-
27
- export type UserMessagePart = TextPart | ImagePart;
28
-
29
- export type UserMessage = {
30
- readonly role: "user";
31
- readonly parts: readonly UserMessagePart[];
32
- };
33
-
34
- export type AssistantMessage = {
35
- readonly role: "assistant";
36
- readonly parts: readonly TextPart[];
37
- };
38
-
39
- export type AddMessageCommand = {
40
- readonly type: "add-message";
41
- readonly message: UserMessage | AssistantMessage;
42
- readonly parentId: string | null;
43
- readonly sourceId: string | null;
44
- /**
45
- * How the host handles the message while a run is active: `"queue"`
46
- * appends to the queue, `"steer"` moves it to the front and interrupts
47
- * the run. Absent, the host decides. Ignored when the host is idle.
48
- */
49
- readonly behavior?: "queue" | "steer";
50
- };
51
-
52
- export type AddToolResultCommand = {
53
- readonly type: "add-tool-result";
54
- readonly toolCallId: string;
55
- readonly toolName: string;
56
- readonly result: ReadonlyJSONValue;
57
- readonly isError: boolean;
58
- readonly artifact?: ReadonlyJSONValue;
59
- readonly modelContent?: readonly ToolModelContentPart[];
60
- };
61
-
62
21
  export type FilePart = {
63
22
  readonly type: "file";
64
23
  readonly mediaType: string;
@@ -81,12 +40,26 @@ export type RunPlacement = {
81
40
 
82
41
  export type RunEnqueueCommand = {
83
42
  readonly type: "run/enqueue";
84
- } & ({ readonly message: RunUserMessage } | { readonly messageId: string }) &
43
+ } & (
44
+ | {
45
+ readonly message: RunUserMessage;
46
+ /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */
47
+ readonly anchorMessageId?: string | null;
48
+ }
49
+ | { readonly messageId: string }
50
+ ) &
85
51
  RunPlacement;
86
52
 
87
53
  export type RunSteerCommand = {
88
54
  readonly type: "run/steer";
89
- } & ({ readonly message: RunUserMessage } | { readonly messageId: string }) &
55
+ } & (
56
+ | {
57
+ readonly message: RunUserMessage;
58
+ /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */
59
+ readonly anchorMessageId?: string | null;
60
+ }
61
+ | { readonly messageId: string }
62
+ ) &
90
63
  RunPlacement;
91
64
 
92
65
  export type RunDequeueCommand = {
@@ -157,6 +130,8 @@ export type InputRequestState = InputRequest & {
157
130
  export type RunReloadCommand = {
158
131
  readonly type: "run/reload";
159
132
  readonly sourceId: string;
133
+ /** Client-generated id of the regenerated assistant message. */
134
+ readonly messageId: string;
160
135
  };
161
136
 
162
137
  export type RunCommand =
@@ -168,11 +143,7 @@ export type RunCommand =
168
143
  | RunReloadCommand
169
144
  | RunInputCommand;
170
145
 
171
- export type AssistantTransportCommand =
172
- | AddMessageCommand
173
- | AddToolResultCommand
174
- | RunCommand
175
- | UserCommands;
146
+ export type AssistantTransportCommand = RunCommand | UserCommands;
176
147
 
177
148
  /** A queued message projected out of the host state, wire shape. */
178
149
  export type RunQueueItem = {