@assistant-ui/react-statewire 0.2.0 → 0.3.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.
@@ -1,7 +1,7 @@
1
1
  // @vitest-environment jsdom
2
2
 
3
- import { render, waitFor } from "@testing-library/react";
4
- import { StrictMode } from "react";
3
+ import { act, render, waitFor } from "@testing-library/react";
4
+ import { StrictMode, useState } from "react";
5
5
  import type { FC } from "react";
6
6
  import { resource } from "@assistant-ui/tap";
7
7
  import { afterEach, describe, expect, it, vi } from "vitest";
@@ -11,7 +11,11 @@ import {
11
11
  ExternalThread,
12
12
  SimpleTextAttachmentAdapter,
13
13
  } from "@assistant-ui/react";
14
- import { AssistantTransportThread } from "./AssistantTransportThread";
14
+ import { ToolResponse } from "assistant-stream";
15
+ import {
16
+ asAssistantTransportExtras,
17
+ AssistantTransportThread,
18
+ } from "./AssistantTransportThread";
15
19
  import {
16
20
  useAssistantTransportSendCommand,
17
21
  useAssistantTransportState,
@@ -19,6 +23,7 @@ import {
19
23
  import type {
20
24
  AssistantTransportCommand,
21
25
  AssistantTransportConnectionMetadata,
26
+ InputRequestState,
22
27
  } from "./types";
23
28
  import {
24
29
  INITIAL_STATE,
@@ -56,10 +61,12 @@ describe("AssistantTransportThread", () => {
56
61
  expect(fetchMock.requests[0]!.url).toBe("https://example.com/api");
57
62
  expect(fetchMock.requests[0]!.body.commands).toEqual([
58
63
  {
59
- type: "message/add",
60
- message: { role: "user", parts: [{ type: "text", text: "hello" }] },
61
- parentId: null,
62
- sourceId: null,
64
+ type: "run/steer",
65
+ message: {
66
+ id: expect.any(String),
67
+ role: "user",
68
+ parts: [{ type: "text", text: "hello" }],
69
+ },
63
70
  },
64
71
  ]);
65
72
  expect(fetchMock.requests[0]!.body.state).toEqual(INITIAL_STATE);
@@ -147,7 +154,7 @@ describe("AssistantTransportThread", () => {
147
154
  const meta = metas.at(-1)!;
148
155
  expect(meta.isSending).toBe(true);
149
156
  expect(meta.pendingCommands).toHaveLength(1);
150
- expect(meta.pendingCommands[0]).toMatchObject({ type: "message/add" });
157
+ expect(meta.pendingCommands[0]).toMatchObject({ type: "run/steer" });
151
158
  });
152
159
 
153
160
  server.emit({
@@ -239,7 +246,7 @@ describe("AssistantTransportThread", () => {
239
246
  });
240
247
 
241
248
  sendCommand(aui, {
242
- type: "message/add",
249
+ type: "add-message",
243
250
  message: { role: "user", parts: [{ type: "text", text: "hello" }] },
244
251
  parentId: null,
245
252
  sourceId: null,
@@ -562,32 +569,19 @@ describe("AssistantTransportThread", () => {
562
569
  expect(errors).toEqual([]);
563
570
  });
564
571
 
565
- it("skips messages that produce zero parts", async () => {
572
+ it("throws on appends that produce zero parts", async () => {
566
573
  const fetchMock = installFetch();
567
574
  const { aui } = mountThread();
568
575
 
569
- aui().thread().append({ role: "user", content: [] });
576
+ expect(() => aui().thread().append({ role: "user", content: [] })).toThrow(
577
+ "statewire: cannot send an empty message",
578
+ );
570
579
 
571
580
  await new Promise((resolve) => setTimeout(resolve, 20));
572
581
  expect(fetchMock.requests).toHaveLength(0);
573
582
  expect(aui().thread().getState().messages).toHaveLength(0);
574
583
  });
575
584
 
576
- it("records parentId from appends that produce zero parts", async () => {
577
- const fetchMock = installFetch();
578
- const { aui } = mountThread();
579
-
580
- aui().thread().append({ role: "user", content: [], parentId: "p1" });
581
-
582
- await new Promise((resolve) => setTimeout(resolve, 20));
583
- expect(fetchMock.requests).toHaveLength(0);
584
-
585
- sendCommand(aui, { type: "custom-a" } as never);
586
-
587
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
588
- expect(fetchMock.requests[0]!.body.parentId).toBe("p1");
589
- });
590
-
591
585
  it("resumes runs against resumeApi with empty commands", async () => {
592
586
  const fetchMock = installFetch();
593
587
  fetchMock.setHandler(() => {
@@ -1126,11 +1120,11 @@ describe("AssistantTransportThread", () => {
1126
1120
  expect(aui().thread().getState().isRunning).toBe(false),
1127
1121
  );
1128
1122
 
1129
- // Give any stray tool-result/add dispatch a chance to fire.
1123
+ // Give any stray add-tool-result dispatch a chance to fire.
1130
1124
  await new Promise((resolve) => setTimeout(resolve, 20));
1131
1125
  expect(
1132
1126
  allCommands(fetchMock.requests).filter(
1133
- (c) => c.type === "tool-result/add",
1127
+ (c) => c.type === "add-tool-result",
1134
1128
  ),
1135
1129
  ).toEqual([]);
1136
1130
  });
@@ -1156,7 +1150,7 @@ describe("AssistantTransportThread", () => {
1156
1150
  );
1157
1151
  });
1158
1152
 
1159
- it("folds completed attachments into the message/add command (CompositeAttachmentAdapter)", async () => {
1153
+ it("folds completed attachments into the run/steer command (CompositeAttachmentAdapter)", async () => {
1160
1154
  const fetchMock = installFetch();
1161
1155
  const { aui } = mountThread({
1162
1156
  adapters: {
@@ -1180,14 +1174,15 @@ describe("AssistantTransportThread", () => {
1180
1174
 
1181
1175
  await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1182
1176
  const command = fetchMock.requests[0]!.body.commands[0];
1183
- expect(command.type).toBe("message/add");
1177
+ expect(command.type).toBe("run/steer");
1184
1178
  const texts = command.message.parts.map((p: any) => p.text);
1185
- expect(texts[0]).toBe("see file");
1186
- expect(texts[1]).toContain("attached body");
1187
- expect(texts[1]).toContain("notes.txt");
1179
+ expect(texts).toHaveLength(1);
1180
+ expect(texts[0]).toContain("see file");
1181
+ expect(texts[0]).toContain("attached body");
1182
+ expect(texts[0]).toContain("notes.txt");
1188
1183
  });
1189
1184
 
1190
- it("edits send the edited message's parent as parentId and itself as sourceId", async () => {
1185
+ it("edits send run/edit with the edited message as sourceId", async () => {
1191
1186
  const fetchMock = installFetch();
1192
1187
  const { aui } = mountThread({ capabilities: { edit: true } });
1193
1188
 
@@ -1212,13 +1207,16 @@ describe("AssistantTransportThread", () => {
1212
1207
  await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1213
1208
  expect(fetchMock.requests[0]!.body.commands).toEqual([
1214
1209
  {
1215
- type: "message/add",
1216
- message: { role: "user", parts: [{ type: "text", text: "edited" }] },
1217
- parentId: "a1",
1210
+ type: "run/edit",
1211
+ message: {
1212
+ id: expect.any(String),
1213
+ role: "user",
1214
+ parts: [{ type: "text", text: "edited" }],
1215
+ },
1218
1216
  sourceId: "u2",
1219
1217
  },
1220
1218
  ]);
1221
- expect(fetchMock.requests[0]!.body.parentId).toBe("a1");
1219
+ expect("parentId" in fetchMock.requests[0]!.body).toBe(false);
1222
1220
  });
1223
1221
 
1224
1222
  it("composer sends carry the last message's id as parentId; the run consumes it", async () => {
@@ -1244,10 +1242,12 @@ describe("AssistantTransportThread", () => {
1244
1242
  expect(body.parentId).toBe("a1");
1245
1243
  expect(body.commands).toEqual([
1246
1244
  {
1247
- type: "message/add",
1248
- message: { role: "user", parts: [{ type: "text", text: "again" }] },
1249
- parentId: "a1",
1250
- sourceId: null,
1245
+ type: "run/steer",
1246
+ message: {
1247
+ id: expect.any(String),
1248
+ role: "user",
1249
+ parts: [{ type: "text", text: "again" }],
1250
+ },
1251
1251
  },
1252
1252
  ]);
1253
1253
 
@@ -1306,7 +1306,7 @@ describe("AssistantTransportThread", () => {
1306
1306
  servers[1]!.done();
1307
1307
  });
1308
1308
 
1309
- it("executes frontend tools and posts tool-result/add in a follow-up run", async () => {
1309
+ it("executes frontend tools and posts add-tool-result in a follow-up run", async () => {
1310
1310
  const fetchMock = installFetch();
1311
1311
  const servers: StreamResponse[] = [];
1312
1312
  fetchMock.setHandler(() => {
@@ -1353,7 +1353,7 @@ describe("AssistantTransportThread", () => {
1353
1353
  await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
1354
1354
  expect(fetchMock.requests[1]!.body.commands).toEqual([
1355
1355
  {
1356
- type: "tool-result/add",
1356
+ type: "add-tool-result",
1357
1357
  toolCallId: "tc1",
1358
1358
  toolName: "probe_tool",
1359
1359
  result: { probed: true },
@@ -1414,7 +1414,7 @@ describe("AssistantTransportThread", () => {
1414
1414
  await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
1415
1415
  expect(fetchMock.requests[1]!.body.commands).toEqual([
1416
1416
  {
1417
- type: "tool-result/add",
1417
+ type: "add-tool-result",
1418
1418
  toolCallId: "tc1",
1419
1419
  toolName: "probe_tool",
1420
1420
  result: { answer: "yes" },
@@ -1463,7 +1463,7 @@ describe("AssistantTransportThread", () => {
1463
1463
 
1464
1464
  await waitFor(() =>
1465
1465
  expect(allCommands(fetchMock.requests)).toContainEqual({
1466
- type: "tool-result/add",
1466
+ type: "add-tool-result",
1467
1467
  toolCallId: "tc1",
1468
1468
  toolName: "probe_tool",
1469
1469
  result: "Tool execution was cancelled.",
@@ -1515,20 +1515,19 @@ describe("AssistantTransportThread", () => {
1515
1515
  await waitFor(() => {
1516
1516
  const commands = allCommands(fetchMock.requests);
1517
1517
  expect(commands).toContainEqual({
1518
- type: "tool-result/add",
1518
+ type: "add-tool-result",
1519
1519
  toolCallId: "tc1",
1520
1520
  toolName: "probe_tool",
1521
1521
  result: "Tool execution was cancelled.",
1522
1522
  isError: true,
1523
1523
  });
1524
1524
  expect(commands).toContainEqual({
1525
- type: "message/add",
1525
+ type: "run/steer",
1526
1526
  message: {
1527
+ id: expect.any(String),
1527
1528
  role: "user",
1528
1529
  parts: [{ type: "text", text: "next question" }],
1529
1530
  },
1530
- parentId: "a-tool",
1531
- sourceId: null,
1532
1531
  });
1533
1532
  });
1534
1533
  await waitFor(() => expect(metas.at(-1)!.toolStatuses).toEqual({}));
@@ -1960,20 +1959,27 @@ describe("reload", () => {
1960
1959
  );
1961
1960
  };
1962
1961
 
1963
- it("regenerates from idle with an empty queue", async () => {
1962
+ it("regenerates via a run/reload command targeting the assistant message", async () => {
1964
1963
  const fetchMock = installFetch();
1965
1964
  const { aui } = mountThread();
1966
1965
  await completeFirstTurn(fetchMock, aui);
1967
1966
 
1968
1967
  aui().thread().message({ id: "m2" }).reload();
1969
1968
  await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
1970
- expect(fetchMock.requests[1]!.body.commands).toEqual([]);
1971
- expect(fetchMock.requests[1]!.body.parentId).toBe("m1");
1969
+ expect(fetchMock.requests[1]!.body.commands).toEqual([
1970
+ { type: "run/reload", sourceId: "m2" },
1971
+ ]);
1972
+ expect("parentId" in fetchMock.requests[1]!.body).toBe(false);
1972
1973
  });
1973
1974
 
1974
- it("keeps the parentId for the next run when the reload run fails", async () => {
1975
+ it("surfaces the error and recovers when the reload run fails", async () => {
1976
+ const errors: string[] = [];
1975
1977
  const fetchMock = installFetch();
1976
- const { aui } = mountThread();
1978
+ const { aui } = mountThread({
1979
+ onError: (error) => {
1980
+ errors.push(error.message);
1981
+ },
1982
+ });
1977
1983
  await completeFirstTurn(fetchMock, aui);
1978
1984
 
1979
1985
  fetchMock.setHandler(() => new Response(null, { status: 500 }));
@@ -1982,21 +1988,18 @@ describe("reload", () => {
1982
1988
  await waitFor(() =>
1983
1989
  expect(aui().thread().getState().isRunning).toBe(false),
1984
1990
  );
1985
- expect(fetchMock.requests[1]!.body.parentId).toBe("m1");
1991
+ await waitFor(() => expect(errors).toHaveLength(1));
1986
1992
 
1987
1993
  fetchMock.setHandler(() => {
1988
1994
  const server = createStreamResponse();
1989
1995
  server.done();
1990
1996
  return server.response;
1991
1997
  });
1992
- sendCommand(aui, {
1993
- type: "message/add",
1994
- message: { role: "user", parts: [{ type: "text", text: "retry" }] },
1995
- parentId: null,
1996
- sourceId: null,
1997
- });
1998
+ aui().thread().message({ id: "m2" }).reload();
1998
1999
  await waitFor(() => expect(fetchMock.requests).toHaveLength(3));
1999
- expect(fetchMock.requests[2]!.body.parentId).toBe("m1");
2000
+ expect(fetchMock.requests[2]!.body.commands).toEqual([
2001
+ { type: "run/reload", sourceId: "m2" },
2002
+ ]);
2000
2003
  });
2001
2004
  });
2002
2005
 
@@ -2042,7 +2045,7 @@ describe("message queue", () => {
2042
2045
  await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
2043
2046
  expect(fetchMock.requests[1]!.body.commands).toMatchObject([
2044
2047
  {
2045
- type: "message/add",
2048
+ type: "run/steer",
2046
2049
  message: { role: "user", parts: [{ type: "text", text: "second" }] },
2047
2050
  },
2048
2051
  ]);
@@ -2101,7 +2104,7 @@ describe("message queue", () => {
2101
2104
  await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
2102
2105
  expect(fetchMock.requests[1]!.body.commands).toMatchObject([
2103
2106
  {
2104
- type: "message/add",
2107
+ type: "run/steer",
2105
2108
  message: { parts: [{ type: "text", text: "second" }] },
2106
2109
  },
2107
2110
  ]);
@@ -2138,3 +2141,524 @@ describe("message queue", () => {
2138
2141
  );
2139
2142
  });
2140
2143
  });
2144
+
2145
+ describe("run/continue", () => {
2146
+ it("resumes via a run/continue command under capabilities.continue", async () => {
2147
+ const fetchMock = installFetch();
2148
+ const { aui } = mountThread({ capabilities: { continue: true } });
2149
+
2150
+ aui().thread().resumeRun({ parentId: null });
2151
+
2152
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2153
+ expect(fetchMock.requests[0]!.url).toBe("https://example.com/api");
2154
+ expect(fetchMock.requests[0]!.body.commands).toEqual([
2155
+ { type: "run/continue" },
2156
+ ]);
2157
+ });
2158
+ });
2159
+
2160
+ describe("server queue projection", () => {
2161
+ type QueueState = TestState & {
2162
+ queue?: { id: string; parts: { type: "text"; text: string }[] }[];
2163
+ steerQueue?: { id: string; parts: { type: "text"; text: string }[] }[];
2164
+ };
2165
+
2166
+ const queueConverter: typeof defaultConverter = (state, meta) => ({
2167
+ ...defaultConverter(state, meta),
2168
+ queue: (state as QueueState).queue ?? [],
2169
+ steerQueue: (state as QueueState).steerQueue ?? [],
2170
+ });
2171
+
2172
+ const textEntry = (id: string, text: string) => ({
2173
+ id,
2174
+ parts: [{ type: "text" as const, text }],
2175
+ });
2176
+
2177
+ it("routes appends through run/enqueue and projects the lanes steer-first", async () => {
2178
+ const fetchMock = installFetch();
2179
+ const { aui } = mountThread({
2180
+ converter: queueConverter,
2181
+ initialState: {
2182
+ messages: [],
2183
+ queue: [textEntry("q1", "first")],
2184
+ steerQueue: [textEntry("s1", "urgent")],
2185
+ } as QueueState,
2186
+ });
2187
+
2188
+ await waitFor(() =>
2189
+ expect(aui().thread().composer().getState().queue).toMatchObject([
2190
+ { id: "s1", prompt: "urgent" },
2191
+ { id: "q1", prompt: "first" },
2192
+ ]),
2193
+ );
2194
+
2195
+ aui().thread().append("hello");
2196
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2197
+ expect(fetchMock.requests[0]!.body.commands).toEqual([
2198
+ {
2199
+ type: "run/enqueue",
2200
+ message: {
2201
+ id: expect.any(String),
2202
+ role: "user",
2203
+ parts: [{ type: "text", text: "hello" }],
2204
+ },
2205
+ },
2206
+ ]);
2207
+ });
2208
+
2209
+ it("steers when the composer sends mid-run", async () => {
2210
+ const fetchMock = installFetch();
2211
+ const servers: StreamResponse[] = [];
2212
+ fetchMock.setHandler(() => {
2213
+ const server = createStreamResponse();
2214
+ servers.push(server);
2215
+ return server.response;
2216
+ });
2217
+
2218
+ const { aui } = mountThread({ converter: queueConverter });
2219
+
2220
+ aui().thread().append("hello");
2221
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2222
+ await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
2223
+
2224
+ aui().thread().composer().setText("steer me");
2225
+ await waitFor(() =>
2226
+ expect(aui().thread().getState().composer.text).toBe("steer me"),
2227
+ );
2228
+ aui().thread().composer().send();
2229
+
2230
+ servers[0]!.done();
2231
+ await waitFor(() =>
2232
+ expect(allCommands(fetchMock.requests)).toContainEqual({
2233
+ type: "run/steer",
2234
+ message: {
2235
+ id: expect.any(String),
2236
+ role: "user",
2237
+ parts: [{ type: "text", text: "steer me" }],
2238
+ },
2239
+ }),
2240
+ );
2241
+ });
2242
+
2243
+ it("sends item controls as run/* commands with placement", async () => {
2244
+ const fetchMock = installFetch();
2245
+ const { aui } = mountThread({
2246
+ converter: queueConverter,
2247
+ initialState: {
2248
+ messages: [],
2249
+ queue: [textEntry("q1", "first"), textEntry("q2", "second")],
2250
+ steerQueue: [textEntry("s1", "urgent")],
2251
+ } as QueueState,
2252
+ });
2253
+
2254
+ await waitFor(() =>
2255
+ expect(aui().thread().composer().getState().queue).toHaveLength(3),
2256
+ );
2257
+
2258
+ aui().thread().composer().queueItem({ id: "q1" }).steer();
2259
+ await waitFor(() =>
2260
+ expect(allCommands(fetchMock.requests)).toContainEqual({
2261
+ type: "run/steer",
2262
+ messageId: "q1",
2263
+ insertAfter: null,
2264
+ }),
2265
+ );
2266
+
2267
+ aui()
2268
+ .thread()
2269
+ .composer()
2270
+ .queueItem({ id: "q2" })
2271
+ .move({ lane: "queue", insertBefore: "q1" });
2272
+ await waitFor(() =>
2273
+ expect(allCommands(fetchMock.requests)).toContainEqual({
2274
+ type: "run/enqueue",
2275
+ messageId: "q2",
2276
+ insertBefore: "q1",
2277
+ }),
2278
+ );
2279
+
2280
+ aui().thread().composer().queueItem({ id: "s1" }).remove();
2281
+ await waitFor(() =>
2282
+ expect(allCommands(fetchMock.requests)).toContainEqual({
2283
+ type: "run/dequeue",
2284
+ messageId: "s1",
2285
+ }),
2286
+ );
2287
+ });
2288
+
2289
+ it("throws when steerQueue is projected without queue", () => {
2290
+ installFetch();
2291
+ expect(() =>
2292
+ mountThread({
2293
+ converter: (state, meta) => ({
2294
+ ...defaultConverter(state, meta),
2295
+ steerQueue: [],
2296
+ }),
2297
+ }),
2298
+ ).toThrow(
2299
+ "statewire: the converter's steerQueue projection requires the queue projection",
2300
+ );
2301
+ });
2302
+
2303
+ it("throws when the queue projection is combined with capabilities.queue", () => {
2304
+ installFetch();
2305
+ expect(() =>
2306
+ mountThread({
2307
+ converter: queueConverter,
2308
+ capabilities: { queue: true },
2309
+ }),
2310
+ ).toThrow(
2311
+ "statewire: the converter's queue projection excludes capabilities.queue",
2312
+ );
2313
+ });
2314
+
2315
+ it("throws when the queue projection appears after the first convert", () => {
2316
+ installFetch();
2317
+ const withQueue: typeof defaultConverter = (state, meta) => ({
2318
+ ...defaultConverter(state, meta),
2319
+ queue: [],
2320
+ });
2321
+
2322
+ const captured: { setConverter?: (c: typeof defaultConverter) => void } =
2323
+ {};
2324
+ const App: FC = () => {
2325
+ const [converter, setConverter] = useState(() => defaultConverter);
2326
+ captured.setConverter = (c) => setConverter(() => c);
2327
+ const aui = useAui({
2328
+ thread: AssistantTransportThread<TestState>({
2329
+ initialState: INITIAL_STATE,
2330
+ api: "https://example.com/api",
2331
+ headers: {},
2332
+ converter,
2333
+ protocol: "assistant-transport",
2334
+ }),
2335
+ });
2336
+ return <AuiProvider value={aui}>{null}</AuiProvider>;
2337
+ };
2338
+ const { unmount } = render(<App />);
2339
+
2340
+ expect(() => act(() => captured.setConverter!(withQueue))).toThrow(
2341
+ /queue projection must be stable/,
2342
+ );
2343
+ unmount();
2344
+ });
2345
+ });
2346
+
2347
+ describe("input requests", () => {
2348
+ type InputState = TestState & {
2349
+ toolCall?: { id: string; name: string; argsText: string };
2350
+ inputRequests?: InputRequestState[];
2351
+ };
2352
+
2353
+ const requestConverter = (approval?: {
2354
+ id: string;
2355
+ }): typeof defaultConverter => {
2356
+ const inner = toolCallConverter([]);
2357
+ return (state, meta) => {
2358
+ const converted = inner(state, meta);
2359
+ return {
2360
+ ...converted,
2361
+ messages: approval
2362
+ ? converted.messages.map((m) =>
2363
+ m.id === "a-tool"
2364
+ ? ({
2365
+ ...m,
2366
+ content: [{ ...(m.content[0] as object), approval }],
2367
+ } as unknown as typeof m)
2368
+ : m,
2369
+ )
2370
+ : converted.messages,
2371
+ inputRequests: (state as InputState).inputRequests ?? [],
2372
+ };
2373
+ };
2374
+ };
2375
+
2376
+ const toolCallPart = (aui: () => ReturnType<typeof useAui>) =>
2377
+ aui().thread().message({ id: "a-tool" }).part({ toolCallId: "tc1" });
2378
+
2379
+ it("routes addToolResult through run/input when a pending tool-call request matches", async () => {
2380
+ const fetchMock = installFetch();
2381
+ const { aui } = mountThread({
2382
+ converter: requestConverter(),
2383
+ initialState: {
2384
+ messages: [],
2385
+ toolCall: { id: "tc1", name: "probe_tool", argsText: "{}" },
2386
+ inputRequests: [
2387
+ { type: "tool-call", id: "req1", toolCallId: "tc1", response: null },
2388
+ ],
2389
+ } as InputState,
2390
+ });
2391
+
2392
+ await waitFor(() =>
2393
+ expect(aui().thread().getState().messages).toHaveLength(1),
2394
+ );
2395
+ toolCallPart(aui).addToolResult({ ok: true });
2396
+
2397
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2398
+ expect(fetchMock.requests[0]!.body.commands).toEqual([
2399
+ {
2400
+ type: "run/input",
2401
+ requestId: "req1",
2402
+ response: { output: { ok: true } },
2403
+ },
2404
+ ]);
2405
+ });
2406
+
2407
+ it("passes isError and artifact through the run/input response", async () => {
2408
+ const fetchMock = installFetch();
2409
+ const { aui } = mountThread({
2410
+ converter: requestConverter(),
2411
+ initialState: {
2412
+ messages: [],
2413
+ toolCall: { id: "tc1", name: "probe_tool", argsText: "{}" },
2414
+ inputRequests: [
2415
+ { type: "tool-call", id: "req1", toolCallId: "tc1", response: null },
2416
+ ],
2417
+ } as InputState,
2418
+ });
2419
+
2420
+ await waitFor(() =>
2421
+ expect(aui().thread().getState().messages).toHaveLength(1),
2422
+ );
2423
+ toolCallPart(aui).addToolResult(
2424
+ new ToolResponse({
2425
+ result: { reason: "boom" },
2426
+ isError: true,
2427
+ artifact: { log: "trace" },
2428
+ }),
2429
+ );
2430
+
2431
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2432
+ expect(fetchMock.requests[0]!.body.commands).toEqual([
2433
+ {
2434
+ type: "run/input",
2435
+ requestId: "req1",
2436
+ response: {
2437
+ output: { reason: "boom" },
2438
+ isError: true,
2439
+ artifact: { log: "trace" },
2440
+ },
2441
+ },
2442
+ ]);
2443
+ });
2444
+
2445
+ it("falls back to add-tool-result without a matching pending request", async () => {
2446
+ const fetchMock = installFetch();
2447
+ const { aui } = mountThread({
2448
+ converter: requestConverter(),
2449
+ initialState: {
2450
+ messages: [],
2451
+ toolCall: { id: "tc1", name: "probe_tool", argsText: "{}" },
2452
+ inputRequests: [
2453
+ {
2454
+ type: "tool-call",
2455
+ id: "req1",
2456
+ toolCallId: "other",
2457
+ response: null,
2458
+ },
2459
+ ],
2460
+ } as InputState,
2461
+ });
2462
+
2463
+ await waitFor(() =>
2464
+ expect(aui().thread().getState().messages).toHaveLength(1),
2465
+ );
2466
+ toolCallPart(aui).addToolResult({ ok: true });
2467
+
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
+ ]);
2478
+ });
2479
+
2480
+ it("throws on answering a request that already carries a response", async () => {
2481
+ installFetch();
2482
+ const { aui } = mountThread({
2483
+ converter: requestConverter(),
2484
+ initialState: {
2485
+ messages: [],
2486
+ toolCall: { id: "tc1", name: "probe_tool", argsText: "{}" },
2487
+ inputRequests: [
2488
+ {
2489
+ type: "tool-call",
2490
+ id: "req1",
2491
+ toolCallId: "tc1",
2492
+ response: { output: "done" },
2493
+ },
2494
+ ],
2495
+ } as InputState,
2496
+ });
2497
+
2498
+ await waitFor(() =>
2499
+ expect(aui().thread().getState().messages).toHaveLength(1),
2500
+ );
2501
+ expect(() => toolCallPart(aui).addToolResult({ ok: true })).toThrow(
2502
+ 'statewire: input request "req1" is already answered',
2503
+ );
2504
+ });
2505
+
2506
+ it("answers tool approvals via run/input decisions", async () => {
2507
+ const fetchMock = installFetch();
2508
+ const { aui } = mountThread({
2509
+ converter: requestConverter({ id: "req2" }),
2510
+ initialState: {
2511
+ messages: [],
2512
+ toolCall: { id: "tc1", name: "probe_tool", argsText: "{}" },
2513
+ inputRequests: [
2514
+ {
2515
+ type: "tool-approval",
2516
+ id: "req2",
2517
+ toolCallId: "tc1",
2518
+ response: null,
2519
+ },
2520
+ ],
2521
+ } as InputState,
2522
+ });
2523
+
2524
+ await waitFor(() =>
2525
+ expect(aui().thread().getState().messages).toHaveLength(1),
2526
+ );
2527
+ toolCallPart(aui).respondToToolApproval({
2528
+ approved: false,
2529
+ reason: "not allowed",
2530
+ });
2531
+
2532
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2533
+ expect(fetchMock.requests[0]!.body.commands).toEqual([
2534
+ {
2535
+ type: "run/input",
2536
+ requestId: "req2",
2537
+ response: { decision: "reject", message: "not allowed" },
2538
+ },
2539
+ ]);
2540
+ });
2541
+
2542
+ it("posts frontend tool results as run/input when the host parks a matching request", async () => {
2543
+ const fetchMock = installFetch();
2544
+ const servers: StreamResponse[] = [];
2545
+ fetchMock.setHandler(() => {
2546
+ const server = createStreamResponse();
2547
+ servers.push(server);
2548
+ return server.response;
2549
+ });
2550
+
2551
+ const { aui } = mountThread({ converter: requestConverter() });
2552
+ aui()
2553
+ .modelContext()
2554
+ .register({
2555
+ getModelContext: () => ({
2556
+ tools: {
2557
+ probe_tool: {
2558
+ parameters: { type: "object", properties: {} },
2559
+ execute: async () => ({ probed: true }),
2560
+ },
2561
+ },
2562
+ }),
2563
+ });
2564
+
2565
+ sendCommand(aui, { type: "custom-a" } as never);
2566
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2567
+ servers[0]!.emit({
2568
+ type: "update-state",
2569
+ operations: [
2570
+ {
2571
+ type: "set",
2572
+ path: ["toolCall"],
2573
+ value: { id: "tc1", name: "probe_tool", argsText: '{"x":1}' },
2574
+ },
2575
+ {
2576
+ type: "set",
2577
+ path: ["inputRequests"],
2578
+ value: [
2579
+ {
2580
+ type: "tool-call",
2581
+ id: "req1",
2582
+ toolCallId: "tc1",
2583
+ response: null,
2584
+ },
2585
+ ],
2586
+ },
2587
+ ],
2588
+ });
2589
+ servers[0]!.done();
2590
+
2591
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
2592
+ expect(fetchMock.requests[1]!.body.commands).toEqual([
2593
+ {
2594
+ type: "run/input",
2595
+ requestId: "req1",
2596
+ response: { output: { probed: true } },
2597
+ },
2598
+ ]);
2599
+ servers[1]!.done();
2600
+ });
2601
+
2602
+ it("surfaces custom request types through extras.inputRequests", async () => {
2603
+ installFetch();
2604
+ const { aui } = mountThread({
2605
+ converter: requestConverter(),
2606
+ initialState: {
2607
+ messages: [],
2608
+ inputRequests: [
2609
+ {
2610
+ type: "human-review",
2611
+ id: "req9",
2612
+ prompt: "check this",
2613
+ response: null,
2614
+ },
2615
+ ],
2616
+ } as InputState,
2617
+ });
2618
+
2619
+ await waitFor(() =>
2620
+ expect(
2621
+ asAssistantTransportExtras(aui().thread().getState().extras)
2622
+ .inputRequests,
2623
+ ).toEqual([
2624
+ {
2625
+ type: "human-review",
2626
+ id: "req9",
2627
+ prompt: "check this",
2628
+ response: null,
2629
+ },
2630
+ ]),
2631
+ );
2632
+ });
2633
+
2634
+ it("throws when the inputRequests projection appears after the first convert", () => {
2635
+ installFetch();
2636
+ const withRequests: typeof defaultConverter = (state, meta) => ({
2637
+ ...defaultConverter(state, meta),
2638
+ inputRequests: [],
2639
+ });
2640
+
2641
+ const captured: { setConverter?: (c: typeof defaultConverter) => void } =
2642
+ {};
2643
+ const App: FC = () => {
2644
+ const [converter, setConverter] = useState(() => defaultConverter);
2645
+ captured.setConverter = (c) => setConverter(() => c);
2646
+ const aui = useAui({
2647
+ thread: AssistantTransportThread<TestState>({
2648
+ initialState: INITIAL_STATE,
2649
+ api: "https://example.com/api",
2650
+ headers: {},
2651
+ converter,
2652
+ protocol: "assistant-transport",
2653
+ }),
2654
+ });
2655
+ return <AuiProvider value={aui}>{null}</AuiProvider>;
2656
+ };
2657
+ const { unmount } = render(<App />);
2658
+
2659
+ expect(() => act(() => captured.setConverter!(withRequests))).toThrow(
2660
+ /inputRequests projection must be stable/,
2661
+ );
2662
+ unmount();
2663
+ });
2664
+ });