@assistant-ui/react-statewire 0.13.0 → 0.15.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 (57) hide show
  1. package/dist/StatewireThread.d.ts +86 -105
  2. package/dist/StatewireThread.d.ts.map +1 -1
  3. package/dist/StatewireThread.js +36 -51
  4. package/dist/StatewireThread.js.map +1 -1
  5. package/dist/hooks.d.ts +6 -9
  6. package/dist/hooks.d.ts.map +1 -1
  7. package/dist/hooks.js +9 -20
  8. package/dist/hooks.js.map +1 -1
  9. package/dist/index.d.ts +2 -3
  10. package/dist/index.js +2 -3
  11. package/dist/inputRequests.d.ts +4 -4
  12. package/dist/inputRequests.d.ts.map +1 -1
  13. package/dist/inputRequests.js +1 -1
  14. package/dist/inputRequests.js.map +1 -1
  15. package/dist/runCommands.d.ts +8 -24
  16. package/dist/runCommands.d.ts.map +1 -1
  17. package/dist/runCommands.js +3 -3
  18. package/dist/runCommands.js.map +1 -1
  19. package/dist/runsOptimistic.d.ts.map +1 -1
  20. package/dist/runsOptimistic.js +30 -13
  21. package/dist/runsOptimistic.js.map +1 -1
  22. package/package.json +4 -5
  23. package/src/StatewireThread.runs.test.tsx +65 -33
  24. package/src/StatewireThread.test.tsx +228 -426
  25. package/src/StatewireThread.ts +133 -224
  26. package/src/__tests__/testHelpers.tsx +6 -226
  27. package/src/hooks.ts +11 -32
  28. package/src/index.ts +2 -4
  29. package/src/inputRequests.ts +7 -9
  30. package/src/runCommands.ts +17 -23
  31. package/src/runsMaterialize.test.ts +7 -8
  32. package/src/runsOptimistic.test.ts +86 -19
  33. package/src/runsOptimistic.ts +49 -19
  34. package/dist/AssistantTransportThread.d.ts +0 -227
  35. package/dist/AssistantTransportThread.d.ts.map +0 -1
  36. package/dist/AssistantTransportThread.js +0 -264
  37. package/dist/AssistantTransportThread.js.map +0 -1
  38. package/dist/host.d.ts +0 -38
  39. package/dist/host.d.ts.map +0 -1
  40. package/dist/host.js +0 -299
  41. package/dist/host.js.map +0 -1
  42. package/dist/replayBoundaryStream.d.ts +0 -6
  43. package/dist/replayBoundaryStream.d.ts.map +0 -1
  44. package/dist/replayBoundaryStream.js +0 -49
  45. package/dist/replayBoundaryStream.js.map +0 -1
  46. package/dist/stateOps.d.ts +0 -10
  47. package/dist/stateOps.d.ts.map +0 -1
  48. package/dist/stateOps.js +0 -114
  49. package/dist/stateOps.js.map +0 -1
  50. package/src/AssistantTransportThread.ts +0 -791
  51. package/src/athena.e2e.test.tsx +0 -654
  52. package/src/host.ts +0 -437
  53. package/src/legacy-diff.test.tsx +0 -628
  54. package/src/replayBoundaryStream.ts +0 -71
  55. package/src/stateOps.test.ts +0 -165
  56. package/src/stateOps.ts +0 -126
  57. package/src/transport.test.tsx +0 -3001
@@ -1,3001 +0,0 @@
1
- // @vitest-environment jsdom
2
-
3
- import { act, render, waitFor } from "@testing-library/react";
4
- import { StrictMode, useState } from "react";
5
- import type { FC } from "react";
6
- import { resource } from "@assistant-ui/tap";
7
- import { afterEach, describe, expect, it, vi } from "vitest";
8
- import { AuiProvider, useAui } from "@assistant-ui/store";
9
- import {
10
- CompositeAttachmentAdapter,
11
- ExternalThread,
12
- SimpleTextAttachmentAdapter,
13
- } from "@assistant-ui/react";
14
- import { ToolResponse } from "assistant-stream";
15
- import {
16
- asAssistantTransportExtras,
17
- AssistantTransportThread,
18
- } from "./AssistantTransportThread";
19
- import {
20
- useAssistantTransportSendCommand,
21
- useAssistantTransportState,
22
- } from "./hooks";
23
- import { runsMaterialize } from "./runsMaterialize";
24
-
25
- import {
26
- INITIAL_STATE,
27
- abortableStream,
28
- allCommands,
29
- createStreamResponse,
30
- defaultConverter,
31
- emitToolCall,
32
- installFetch,
33
- mountThread,
34
- sendCommand,
35
- sseEvent,
36
- threadTexts,
37
- toolCallConverter,
38
- toThreadMessage,
39
- } from "./__tests__/testHelpers";
40
- import type { StreamResponse, TestState } from "./__tests__/testHelpers";
41
-
42
- afterEach(() => {
43
- vi.unstubAllGlobals();
44
- });
45
-
46
- describe("AssistantTransportThread", () => {
47
- it("sends appended messages and applies streamed state", async () => {
48
- const fetchMock = installFetch();
49
- let server!: StreamResponse;
50
- fetchMock.setHandler(() => {
51
- server = createStreamResponse();
52
- return server.response;
53
- });
54
-
55
- const { aui } = mountThread();
56
- aui().thread().append("hello");
57
-
58
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
59
- expect(fetchMock.requests[0]!.url).toBe("https://example.com/api");
60
- expect(fetchMock.requests[0]!.body.commands).toEqual([
61
- {
62
- type: "run/steer",
63
- runId: expect.any(String),
64
- message: {
65
- id: expect.any(String),
66
- role: "user",
67
- parts: [{ type: "text", text: "hello" }],
68
- },
69
- runAnchorMessageId: null,
70
- },
71
- ]);
72
- expect(fetchMock.requests[0]!.body.state).toEqual(INITIAL_STATE);
73
- expect(fetchMock.requests[0]!.body.threadId).toBeNull();
74
-
75
- await waitFor(() => expect(threadTexts(aui)).toEqual(["hello"]));
76
- expect(aui().thread().getState().isRunning).toBe(true);
77
-
78
- server.emit({
79
- type: "update-state",
80
- operations: [
81
- {
82
- type: "set",
83
- path: ["messages"],
84
- value: [
85
- { id: "m1", role: "user", text: "hello" },
86
- { id: "m2", role: "assistant", text: "hi there" },
87
- ],
88
- },
89
- ],
90
- });
91
-
92
- await waitFor(() =>
93
- expect(threadTexts(aui)).toEqual(["hello", "hi there"]),
94
- );
95
- server.done();
96
-
97
- await waitFor(() =>
98
- expect(aui().thread().getState().isRunning).toBe(false),
99
- );
100
- });
101
-
102
- it("streams append-text deltas into the state", async () => {
103
- const fetchMock = installFetch();
104
- let server!: StreamResponse;
105
- fetchMock.setHandler(() => {
106
- server = createStreamResponse();
107
- return server.response;
108
- });
109
-
110
- const { aui } = mountThread();
111
- aui().thread().append("hello");
112
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
113
-
114
- server.emit({
115
- type: "update-state",
116
- operations: [
117
- {
118
- type: "set",
119
- path: ["messages"],
120
- value: [{ id: "m1", role: "assistant", text: "" }],
121
- },
122
- ],
123
- });
124
- server.emit({
125
- type: "update-state",
126
- operations: [
127
- { type: "append-text", path: ["messages", "0", "text"], value: "wor" },
128
- { type: "append-text", path: ["messages", "0", "text"], value: "ld" },
129
- ],
130
- });
131
- server.done();
132
-
133
- await waitFor(() => expect(threadTexts(aui)).toEqual(["world"]));
134
- });
135
-
136
- it("folds pending commands through optimistic in send order and retires them on delivery", async () => {
137
- const fetchMock = installFetch();
138
- let server!: StreamResponse;
139
- fetchMock.setHandler(() => {
140
- server = createStreamResponse();
141
- return server.response;
142
- });
143
-
144
- const { aui } = mountThread();
145
- sendCommand(aui, {
146
- type: "run/steer",
147
- runId: "run-u1",
148
- message: { id: "u1", role: "user", parts: [{ type: "text", text: "a" }] },
149
- });
150
- sendCommand(aui, {
151
- type: "run/steer",
152
- runId: "run-u2",
153
- message: { id: "u2", role: "user", parts: [{ type: "text", text: "b" }] },
154
- });
155
-
156
- await waitFor(() => expect(threadTexts(aui)).toEqual(["a", "b"]));
157
- expect(aui().thread().getState().isRunning).toBe(true);
158
-
159
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
160
- server.emit({
161
- type: "update-state",
162
- operations: [
163
- {
164
- type: "set",
165
- path: ["messages"],
166
- value: [{ id: "m1", role: "user", text: "canonical" }],
167
- },
168
- ],
169
- });
170
-
171
- // delivery retires the optimistic copies — the canonical echo stands alone
172
- await waitFor(() => expect(threadTexts(aui)).toEqual(["canonical"]));
173
-
174
- server.done();
175
- await waitFor(() =>
176
- expect(aui().thread().getState().isRunning).toBe(false),
177
- );
178
- });
179
-
180
- it("keeps ctx.seq stable per command across refolds", async () => {
181
- const fetchMock = installFetch();
182
- let server!: StreamResponse;
183
- fetchMock.setHandler(() => {
184
- server = createStreamResponse();
185
- return server.response;
186
- });
187
-
188
- const folds: [string, number][] = [];
189
- const { aui } = mountThread({
190
- optimistic: (draft, command, ctx) => {
191
- draft.isRunning = true;
192
- if (command.type === "run/steer" && "message" in command)
193
- folds.push([command.message.id, ctx.seq]);
194
- },
195
- });
196
-
197
- sendCommand(aui, {
198
- type: "run/steer",
199
- runId: "run-u1",
200
- message: { id: "u1", role: "user", parts: [{ type: "text", text: "a" }] },
201
- });
202
- sendCommand(aui, {
203
- type: "run/steer",
204
- runId: "run-u2",
205
- message: { id: "u2", role: "user", parts: [{ type: "text", text: "b" }] },
206
- });
207
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
208
-
209
- // a state change while both commands are pending re-runs the fold
210
- server.emit({
211
- type: "update-state",
212
- operations: [{ type: "set", path: ["todos"], value: ["t"] }],
213
- });
214
- server.done();
215
- await waitFor(() =>
216
- expect(aui().thread().getState().isRunning).toBe(false),
217
- );
218
-
219
- const seqsOf = (id: string) =>
220
- new Set(folds.filter(([m]) => m === id).map(([, seq]) => seq));
221
- expect(seqsOf("u1").size).toBe(1);
222
- expect(seqsOf("u2").size).toBe(1);
223
- expect([...seqsOf("u1")][0]!).toBeLessThan([...seqsOf("u2")][0]!);
224
- });
225
-
226
- it("a throwing optimistic fold drops that command's update and keeps the rest", async () => {
227
- const fetchMock = installFetch();
228
- let server!: StreamResponse;
229
- fetchMock.setHandler(() => {
230
- server = createStreamResponse();
231
- return server.response;
232
- });
233
-
234
- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
235
- try {
236
- const { aui } = mountThread({
237
- optimistic: (draft, command) => {
238
- if (!("message" in command)) throw new Error("no message");
239
- if (command.type === "run/steer")
240
- draft.messages.push({
241
- id: command.message.id,
242
- role: "user",
243
- text:
244
- command.message.parts.find((p) => p.type === "text")?.text ??
245
- "",
246
- });
247
- },
248
- });
249
-
250
- sendCommand(aui, { type: "custom-a" } as never);
251
- sendCommand(aui, {
252
- type: "run/steer",
253
- runId: "run-u1",
254
- message: {
255
- id: "u1",
256
- role: "user",
257
- parts: [{ type: "text", text: "kept" }],
258
- },
259
- });
260
-
261
- await waitFor(() => expect(threadTexts(aui)).toEqual(["kept"]));
262
- expect(errorSpy).toHaveBeenCalledWith(
263
- expect.stringContaining(
264
- 'optimistic reducer threw for "custom-a"; dropping its optimistic update',
265
- ),
266
- expect.any(Error),
267
- );
268
-
269
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
270
- server.done();
271
- } finally {
272
- errorSpy.mockRestore();
273
- }
274
- });
275
-
276
- it("folds pending commands over imported state before converting", async () => {
277
- const fetchMock = installFetch();
278
- let server!: StreamResponse;
279
- fetchMock.setHandler(() => {
280
- server = createStreamResponse();
281
- return server.response;
282
- });
283
-
284
- const { aui } = mountThread();
285
- aui().thread().append("pending question");
286
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
287
-
288
- aui().thread().importExternalState!({
289
- messages: [{ id: "m1", role: "assistant", text: "imported" }],
290
- });
291
-
292
- await waitFor(() =>
293
- expect(threadTexts(aui)).toEqual(["imported", "pending question"]),
294
- );
295
- server.done();
296
- });
297
-
298
- it("coalesces two synchronous sends into one request; the empty follow-up run is a no-op", async () => {
299
- const fetchMock = installFetch();
300
- const errors: string[] = [];
301
- const cancels: unknown[] = [];
302
-
303
- const { aui } = mountThread({
304
- onError: (error) => {
305
- errors.push(error.message);
306
- },
307
- onCancel: (params) => {
308
- cancels.push(params.commands);
309
- },
310
- });
311
-
312
- sendCommand(aui, { type: "custom-a" } as never);
313
- sendCommand(aui, { type: "custom-b" } as never);
314
-
315
- await waitFor(() =>
316
- expect(aui().thread().getState().isRunning).toBe(false),
317
- );
318
- expect(errors).toEqual([]);
319
- expect(cancels).toEqual([]);
320
- expect(fetchMock.requests).toHaveLength(1);
321
- expect(
322
- fetchMock.requests[0]!.body.commands.map((c: any) => c.type),
323
- ).toEqual(["custom-a", "custom-b"]);
324
- });
325
-
326
- it("restarts once with commands queued during a run", async () => {
327
- const fetchMock = installFetch();
328
- const servers: StreamResponse[] = [];
329
- fetchMock.setHandler(() => {
330
- const server = createStreamResponse();
331
- servers.push(server);
332
- return server.response;
333
- });
334
-
335
- const { aui } = mountThread();
336
- sendCommand(aui, { type: "custom-a" } as never);
337
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
338
-
339
- sendCommand(aui, { type: "custom-b" } as never);
340
- servers[0]!.done();
341
-
342
- await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
343
- expect(fetchMock.requests[1]!.body.commands).toEqual([
344
- { type: "custom-b" },
345
- ]);
346
- servers[1]!.done();
347
- });
348
-
349
- it("marks commands delivered when a run completes cleanly without state chunks", async () => {
350
- const fetchMock = installFetch();
351
- const servers: StreamResponse[] = [];
352
- fetchMock.setHandler(() => {
353
- const server = createStreamResponse();
354
- servers.push(server);
355
- server.done();
356
- return server.response;
357
- });
358
-
359
- const errors: string[] = [];
360
- const { aui } = mountThread({
361
- onError: (error) => {
362
- errors.push(error.message);
363
- },
364
- });
365
-
366
- sendCommand(aui, {
367
- type: "run/steer",
368
- runId: "run-u1",
369
- message: {
370
- id: "u1",
371
- role: "user",
372
- parts: [{ type: "text", text: "hello" }],
373
- },
374
- });
375
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
376
- await waitFor(() =>
377
- expect(aui().thread().getState().isRunning).toBe(false),
378
- );
379
-
380
- // No update-state chunk arrived, but the run completed cleanly: the
381
- // command counts as delivered and leaves pending (unlike legacy).
382
- expect(errors).toEqual([]);
383
- expect(aui().thread().getState().messages).toEqual([]);
384
-
385
- sendCommand(aui, { type: "custom-b" } as never);
386
- await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
387
- expect(fetchMock.requests[1]!.body.commands).toEqual([
388
- { type: "custom-b" },
389
- ]);
390
- });
391
-
392
- it("runs onError with in-transit commands, then onCancel with queued commands", async () => {
393
- const fetchMock = installFetch();
394
- fetchMock.setHandler(() => new Response("boom", { status: 500 }));
395
-
396
- const events: string[] = [];
397
- const { aui } = mountThread({
398
- onError: (error, { commands }) => {
399
- events.push(`error:${error.message}:${commands.length}`);
400
- },
401
- onCancel: ({ commands, error }) => {
402
- events.push(`cancel:${commands.length}:${error?.message}`);
403
- },
404
- });
405
-
406
- sendCommand(aui, { type: "custom-a" } as never);
407
-
408
- await waitFor(() =>
409
- expect(events).toEqual([
410
- "error:Status 500: boom:1",
411
- "cancel:0:Status 500: boom",
412
- ]),
413
- );
414
- await waitFor(() =>
415
- expect(aui().thread().getState().isRunning).toBe(false),
416
- );
417
- });
418
-
419
- it("supports updateState from onError", async () => {
420
- const fetchMock = installFetch();
421
- fetchMock.setHandler(() => new Response("boom", { status: 500 }));
422
-
423
- const { aui } = mountThread({
424
- onError: (_error, { updateState }) => {
425
- updateState((state) => ({
426
- messages: [
427
- ...state.messages,
428
- { id: "err", role: "assistant", text: "request failed" },
429
- ],
430
- }));
431
- },
432
- });
433
-
434
- aui().thread().append("hello");
435
-
436
- await waitFor(() => expect(threadTexts(aui)).toEqual(["request failed"]));
437
- });
438
-
439
- it("keeps commands in transit when the first chunk fails to apply — onError receives them", async () => {
440
- const fetchMock = installFetch();
441
- const servers: StreamResponse[] = [];
442
- fetchMock.setHandler(() => {
443
- const server = createStreamResponse();
444
- servers.push(server);
445
- if (servers.length > 1) server.done();
446
- return server.response;
447
- });
448
-
449
- const errored: AssistantTransportThread.Command[][] = [];
450
- const { aui } = mountThread({
451
- onError: (_error, { commands }) => {
452
- errored.push(commands);
453
- },
454
- });
455
-
456
- sendCommand(aui, { type: "custom-a" } as never);
457
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
458
-
459
- // The very first chunk is invalid — the legacy accumulator errors the run
460
- // before any state change surfaces, so markDelivered never fires and
461
- // onError sees the in-transit command.
462
- servers[0]!.emit({
463
- type: "update-state",
464
- operations: [{ type: "append-text", path: ["messages"], value: "x" }],
465
- });
466
- servers[0]!.done();
467
-
468
- await waitFor(() => expect(errored).toHaveLength(1));
469
- expect(errored[0]).toEqual([{ type: "custom-a" }]);
470
- });
471
-
472
- it("applies chunk ops one-by-one — an op error mid-chunk keeps the applied prefix", async () => {
473
- const fetchMock = installFetch();
474
- const servers: StreamResponse[] = [];
475
- fetchMock.setHandler(() => {
476
- const server = createStreamResponse();
477
- servers.push(server);
478
- if (servers.length > 1) server.done();
479
- return server.response;
480
- });
481
-
482
- const errors: string[] = [];
483
- const { aui } = mountThread({
484
- onError: (error) => {
485
- errors.push(error.message);
486
- },
487
- });
488
-
489
- sendCommand(aui, { type: "custom-a" } as never);
490
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
491
-
492
- // Second op is invalid (append-text onto a non-string) — the run errors,
493
- // but the ops before it stay applied.
494
- servers[0]!.emit({
495
- type: "update-state",
496
- operations: [
497
- {
498
- type: "set",
499
- path: ["messages"],
500
- value: [{ id: "m1", role: "assistant", text: "partial" }],
501
- },
502
- { type: "append-text", path: ["messages"], value: "x" },
503
- ],
504
- });
505
- servers[0]!.done();
506
-
507
- await waitFor(() => expect(errors).toHaveLength(1));
508
-
509
- // The applied prefix carries into the next request body.
510
- sendCommand(aui, { type: "custom-b" } as never);
511
- await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
512
- expect(fetchMock.requests[1]!.body.state).toEqual({
513
- messages: [{ id: "m1", role: "assistant", text: "partial" }],
514
- });
515
- expect(threadTexts(aui)).toEqual(["partial"]);
516
- });
517
-
518
- it("cancels a running request and reports all pending commands", async () => {
519
- const fetchMock = installFetch();
520
- fetchMock.setHandler(({ init }) => abortableStream(init).response);
521
-
522
- const cancelled: AssistantTransportThread.Command[][] = [];
523
- const errors: string[] = [];
524
- const { aui } = mountThread({
525
- onCancel: ({ commands, error }) => {
526
- cancelled.push(commands);
527
- if (error) errors.push(error.message);
528
- },
529
- });
530
-
531
- sendCommand(aui, { type: "custom-a" } as never);
532
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
533
-
534
- aui().thread().cancelRun();
535
-
536
- await waitFor(() => expect(cancelled).toHaveLength(1));
537
- expect(cancelled[0]!.map((c: any) => c.type)).toEqual(["custom-a"]);
538
- expect(errors).toEqual([]);
539
- await waitFor(() =>
540
- expect(aui().thread().getState().isRunning).toBe(false),
541
- );
542
- });
543
-
544
- it("errors when the stream ends without the [DONE] marker", async () => {
545
- const fetchMock = installFetch();
546
- let server!: StreamResponse;
547
- fetchMock.setHandler(() => {
548
- server = createStreamResponse();
549
- return server.response;
550
- });
551
-
552
- const errors: string[] = [];
553
- const { aui } = mountThread({
554
- protocol: "assistant-transport",
555
- onError: (error) => {
556
- errors.push(error.message);
557
- },
558
- });
559
-
560
- sendCommand(aui, { type: "custom-a" } as never);
561
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
562
- server.close();
563
-
564
- await waitFor(() =>
565
- expect(errors).toEqual([
566
- "Stream ended abruptly without receiving [DONE] marker",
567
- ]),
568
- );
569
- });
570
-
571
- it("decodes resume runs leniently — unknown events and a missing [DONE] still apply valid chunks", async () => {
572
- const fetchMock = installFetch();
573
- fetchMock.setHandler(() => {
574
- const server = createStreamResponse();
575
- server.push("event: custom\ndata: {}\n\n");
576
- server.emit({
577
- type: "update-state",
578
- operations: [
579
- {
580
- type: "set",
581
- path: ["messages"],
582
- value: [{ id: "m1", role: "assistant", text: "recovered" }],
583
- },
584
- ],
585
- });
586
- server.close();
587
- return server.response;
588
- });
589
-
590
- const errors: string[] = [];
591
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
592
- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
593
- try {
594
- const { aui } = mountThread({
595
- resumeApi: "https://example.com/resume",
596
- onError: (error) => {
597
- errors.push(error.message);
598
- },
599
- });
600
- aui().thread().resumeRun({ parentId: null });
601
-
602
- await waitFor(() => expect(threadTexts(aui)).toEqual(["recovered"]));
603
- await waitFor(() =>
604
- expect(aui().thread().getState().isRunning).toBe(false),
605
- );
606
- expect(errors).toEqual([]);
607
- } finally {
608
- warnSpy.mockRestore();
609
- errorSpy.mockRestore();
610
- }
611
- });
612
-
613
- it("surfaces error chunks after the stream completes", async () => {
614
- const fetchMock = installFetch();
615
- fetchMock.setHandler(() => {
616
- const server = createStreamResponse();
617
- server.emit({ type: "error", error: "kaboom" });
618
- server.done();
619
- return server.response;
620
- });
621
-
622
- const errors: string[] = [];
623
- const { aui } = mountThread({
624
- onError: (error) => {
625
- errors.push(error.message);
626
- },
627
- });
628
-
629
- sendCommand(aui, { type: "custom-a" } as never);
630
- await waitFor(() => expect(errors).toEqual(["kaboom"]));
631
- });
632
-
633
- it("decodes update-state parts from the default data-stream protocol", async () => {
634
- const fetchMock = installFetch();
635
- fetchMock.setHandler(() => {
636
- const server = createStreamResponse();
637
- server.push(
638
- `aui-state:${JSON.stringify([
639
- {
640
- type: "set",
641
- path: ["messages"],
642
- value: [{ id: "m1", role: "assistant", text: "from data stream" }],
643
- },
644
- ])}\n`,
645
- );
646
- server.close();
647
- return server.response;
648
- });
649
-
650
- const { aui } = mountThread({ protocol: undefined });
651
- sendCommand(aui, { type: "custom-a" } as never);
652
-
653
- await waitFor(() => expect(threadTexts(aui)).toEqual(["from data stream"]));
654
- });
655
-
656
- it("skips blank data-stream lines emitted as framing on reconnect", async () => {
657
- const fetchMock = installFetch();
658
- const errors: string[] = [];
659
- fetchMock.setHandler(() => {
660
- const server = createStreamResponse();
661
- server.push("\n");
662
- server.push(
663
- `aui-state:${JSON.stringify([
664
- {
665
- type: "set",
666
- path: ["messages"],
667
- value: [{ id: "m1", role: "assistant", text: "hi" }],
668
- },
669
- ])}\n`,
670
- );
671
- server.push("\n \n");
672
- server.push(
673
- `aui-state:${JSON.stringify([
674
- { type: "append-text", path: ["messages", "0", "text"], value: "!" },
675
- ])}\n`,
676
- );
677
- server.close();
678
- return server.response;
679
- });
680
-
681
- const { aui } = mountThread({
682
- protocol: undefined,
683
- onError: (error) => {
684
- errors.push(error.message);
685
- },
686
- });
687
- sendCommand(aui, { type: "custom-a" } as never);
688
-
689
- await waitFor(() => expect(threadTexts(aui)).toEqual(["hi!"]));
690
- expect(errors).toEqual([]);
691
- });
692
-
693
- it("throws on appends that produce zero parts", async () => {
694
- const fetchMock = installFetch();
695
- const { aui } = mountThread();
696
-
697
- expect(() => aui().thread().append({ role: "user", content: [] })).toThrow(
698
- "statewire: cannot send an empty message",
699
- );
700
-
701
- await new Promise((resolve) => setTimeout(resolve, 20));
702
- expect(fetchMock.requests).toHaveLength(0);
703
- expect(aui().thread().getState().messages).toHaveLength(0);
704
- });
705
-
706
- it("resumes runs against resumeApi with empty commands", async () => {
707
- const fetchMock = installFetch();
708
- fetchMock.setHandler(() => {
709
- const server = createStreamResponse({
710
- headers: { "X-Stream-Status": "active" },
711
- });
712
- server.done();
713
- return server.response;
714
- });
715
-
716
- const streamStatuses: (string | null)[] = [];
717
- const { aui } = mountThread({
718
- resumeApi: "https://example.com/resume",
719
- onResponse: (response) => {
720
- streamStatuses.push(response.headers.get("X-Stream-Status"));
721
- },
722
- });
723
-
724
- aui().thread().resumeRun({ parentId: null });
725
-
726
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
727
- expect(fetchMock.requests[0]!.url).toBe("https://example.com/resume");
728
- expect(fetchMock.requests[0]!.body.commands).toEqual([]);
729
- await waitFor(() => expect(streamStatuses).toEqual(["active"]));
730
- await waitFor(() =>
731
- expect(aui().thread().getState().isRunning).toBe(false),
732
- );
733
- });
734
-
735
- it("flushes commands coalesced into a resume run in a follow-up run", async () => {
736
- const fetchMock = installFetch();
737
- const servers: StreamResponse[] = [];
738
- fetchMock.setHandler(() => {
739
- const server = createStreamResponse();
740
- servers.push(server);
741
- return server.response;
742
- });
743
-
744
- const { aui } = mountThread({
745
- resumeApi: "https://example.com/resume",
746
- });
747
-
748
- sendCommand(aui, { type: "custom-a" } as never);
749
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
750
-
751
- // Both land while the first run is active and coalesce into one follow-up.
752
- sendCommand(aui, { type: "custom-b" } as never);
753
- aui().thread().resumeRun({ parentId: null });
754
-
755
- servers[0]!.done();
756
- await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
757
- expect(fetchMock.requests[1]!.url).toBe("https://example.com/resume");
758
- expect(fetchMock.requests[1]!.body.commands).toEqual([]);
759
- servers[1]!.done();
760
-
761
- // custom-b must not starve in the queue.
762
- await waitFor(() => expect(fetchMock.requests).toHaveLength(3));
763
- expect(fetchMock.requests[2]!.url).toBe("https://example.com/api");
764
- expect(fetchMock.requests[2]!.body.commands).toEqual([
765
- { type: "custom-b" },
766
- ]);
767
- servers[2]!.done();
768
- });
769
-
770
- it("throws when resuming without resumeApi", () => {
771
- installFetch();
772
- const { aui } = mountThread();
773
-
774
- expect(() => aui().thread().resumeRun({ parentId: null })).toThrow(
775
- "Must pass resumeApi to options to resume runs",
776
- );
777
- });
778
-
779
- it("cancel clears a pending resume flag", async () => {
780
- const fetchMock = installFetch();
781
- const servers: StreamResponse[] = [];
782
- fetchMock.setHandler(({ init }) => {
783
- const server = abortableStream(init);
784
- servers.push(server);
785
- return server.response;
786
- });
787
-
788
- const { aui } = mountThread({
789
- resumeApi: "https://example.com/resume",
790
- });
791
-
792
- sendCommand(aui, { type: "custom-a" } as never);
793
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
794
-
795
- // Request a resume while the run is in flight, then cancel everything.
796
- aui().thread().resumeRun({ parentId: null });
797
- aui().thread().cancelRun();
798
- await waitFor(() =>
799
- expect(aui().thread().getState().isRunning).toBe(false),
800
- );
801
-
802
- sendCommand(aui, { type: "custom-b" } as never);
803
- await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
804
-
805
- expect(fetchMock.requests[1]!.url).toBe("https://example.com/api");
806
- expect(fetchMock.requests[1]!.body.commands).toEqual([
807
- { type: "custom-b" },
808
- ]);
809
- servers[1]!.done();
810
- });
811
-
812
- it("gates isLoading around the replay boundary", async () => {
813
- const fetchMock = installFetch();
814
- const replayEvent = sseEvent({
815
- type: "update-state",
816
- operations: [
817
- {
818
- type: "set",
819
- path: ["messages"],
820
- value: [{ id: "m1", role: "assistant", text: "replayed" }],
821
- },
822
- ],
823
- });
824
-
825
- let server!: StreamResponse;
826
- fetchMock.setHandler(() => {
827
- server = createStreamResponse({
828
- headers: {
829
- "Aui-Replay-Content-Length": String(
830
- new TextEncoder().encode(replayEvent).byteLength,
831
- ),
832
- },
833
- });
834
- return server.response;
835
- });
836
-
837
- const { aui } = mountThread({
838
- resumeApi: "https://example.com/resume",
839
- });
840
-
841
- aui().thread().resumeRun({ parentId: null });
842
-
843
- await waitFor(() => expect(aui().thread().getState().isLoading).toBe(true));
844
-
845
- server.push(replayEvent);
846
- await waitFor(() => expect(threadTexts(aui)).toEqual(["replayed"]));
847
- await waitFor(() =>
848
- expect(aui().thread().getState().isLoading).toBe(false),
849
- );
850
-
851
- server.emit({
852
- type: "update-state",
853
- operations: [
854
- { type: "append-text", path: ["messages", "0", "text"], value: "!" },
855
- ],
856
- });
857
- server.done();
858
-
859
- await waitFor(() => expect(threadTexts(aui)).toEqual(["replayed!"]));
860
- });
861
-
862
- it("renders the replay boundary before replayed content becomes visible", async () => {
863
- const fetchMock = installFetch();
864
- const replayEvent = sseEvent({
865
- type: "update-state",
866
- operations: [
867
- {
868
- type: "set",
869
- path: ["messages"],
870
- value: [{ id: "m1", role: "assistant", text: "replayed" }],
871
- },
872
- ],
873
- });
874
-
875
- fetchMock.setHandler(() => {
876
- const server = createStreamResponse({
877
- headers: {
878
- "Aui-Replay-Content-Length": String(
879
- new TextEncoder().encode(replayEvent).byteLength,
880
- ),
881
- },
882
- });
883
- // All bytes are available immediately — the boundary gating alone must
884
- // guarantee the loading state renders before replayed content.
885
- server.push(replayEvent);
886
- server.emit({
887
- type: "update-state",
888
- operations: [
889
- { type: "append-text", path: ["messages", "0", "text"], value: "!" },
890
- ],
891
- });
892
- server.done();
893
- return server.response;
894
- });
895
-
896
- const records: { isLoading: boolean; texts: string[] }[] = [];
897
- const { aui } = mountThread({
898
- resumeApi: "https://example.com/resume",
899
- });
900
- const record = () => {
901
- const state = aui().thread().getState();
902
- records.push({
903
- isLoading: state.isLoading,
904
- texts: state.messages.map((m) =>
905
- m.parts.flatMap((p) => (p.type === "text" ? [p.text] : [])).join(""),
906
- ),
907
- });
908
- };
909
- const unsubscribe = aui().subscribe(record);
910
-
911
- aui().thread().resumeRun({ parentId: null });
912
-
913
- await waitFor(() =>
914
- expect(records.at(-1)).toEqual({
915
- isLoading: false,
916
- texts: ["replayed!"],
917
- }),
918
- );
919
- unsubscribe();
920
-
921
- const firstReplayed = records.findIndex((r) =>
922
- r.texts.join("").includes("replayed"),
923
- );
924
- const firstLoading = records.findIndex((r) => r.isLoading);
925
- expect(firstLoading).toBeGreaterThanOrEqual(0);
926
- expect(firstLoading).toBeLessThan(firstReplayed);
927
- // live bytes only render after the boundary flip back to not-loading
928
- const firstLive = records.findIndex(
929
- (r) => r.texts.join("") === "replayed!",
930
- );
931
- expect(records[firstLive]!.isLoading).toBe(false);
932
- });
933
-
934
- it("handles a replay boundary landing mid-multibyte-char and mid-SSE-event", async () => {
935
- const fetchMock = installFetch();
936
- const replayEvent = sseEvent({
937
- type: "update-state",
938
- operations: [
939
- {
940
- type: "set",
941
- path: ["messages"],
942
- value: [{ id: "m1", role: "assistant", text: "héllo ✓ wörld" }],
943
- },
944
- ],
945
- });
946
- const replayBytes = new TextEncoder().encode(replayEvent);
947
- // Boundary inside the multibyte "✓" (3 bytes) which itself sits mid-event.
948
- const checkmarkOffset = replayEvent.indexOf("✓");
949
- const boundary =
950
- new TextEncoder().encode(replayEvent.slice(0, checkmarkOffset))
951
- .byteLength + 1;
952
- expect(boundary).toBeLessThan(replayBytes.byteLength);
953
-
954
- let server!: StreamResponse;
955
- fetchMock.setHandler(() => {
956
- server = createStreamResponse({
957
- headers: { "Aui-Replay-Content-Length": String(boundary) },
958
- });
959
- return server.response;
960
- });
961
-
962
- const { aui } = mountThread({
963
- resumeApi: "https://example.com/resume",
964
- });
965
- aui().thread().resumeRun({ parentId: null });
966
- await waitFor(() => expect(aui().thread().getState().isLoading).toBe(true));
967
-
968
- // Deliver the replay bytes in a chunk that straddles the boundary.
969
- server.pushBytes(replayBytes);
970
- await waitFor(() => expect(threadTexts(aui)).toEqual(["héllo ✓ wörld"]));
971
- await waitFor(() =>
972
- expect(aui().thread().getState().isLoading).toBe(false),
973
- );
974
-
975
- server.emit({
976
- type: "update-state",
977
- operations: [
978
- { type: "append-text", path: ["messages", "0", "text"], value: " ✔" },
979
- ],
980
- });
981
- server.done();
982
- await waitFor(() => expect(threadTexts(aui)).toEqual(["héllo ✓ wörld ✔"]));
983
- });
984
-
985
- it("treats a zero-length replay header as no replay", async () => {
986
- const fetchMock = installFetch();
987
- let server!: StreamResponse;
988
- const loadingStates: boolean[] = [];
989
- fetchMock.setHandler(() => {
990
- server = createStreamResponse({
991
- headers: { "Aui-Replay-Content-Length": "0" },
992
- });
993
- return server.response;
994
- });
995
-
996
- const { aui } = mountThread({
997
- resumeApi: "https://example.com/resume",
998
- });
999
- aui().thread().resumeRun({ parentId: null });
1000
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1001
- loadingStates.push(aui().thread().getState().isLoading);
1002
-
1003
- server.emit({
1004
- type: "update-state",
1005
- operations: [
1006
- {
1007
- type: "set",
1008
- path: ["messages"],
1009
- value: [{ id: "m1", role: "assistant", text: "live" }],
1010
- },
1011
- ],
1012
- });
1013
- server.done();
1014
-
1015
- await waitFor(() => expect(threadTexts(aui)).toEqual(["live"]));
1016
- loadingStates.push(aui().thread().getState().isLoading);
1017
- expect(loadingStates).toEqual([false, false]);
1018
- });
1019
-
1020
- it("surfaces an invalid replay header via onError", async () => {
1021
- const fetchMock = installFetch();
1022
- fetchMock.setHandler(() => {
1023
- const server = createStreamResponse({
1024
- headers: { "Aui-Replay-Content-Length": "garbage" },
1025
- });
1026
- return server.response;
1027
- });
1028
-
1029
- const errors: string[] = [];
1030
- const { aui } = mountThread({
1031
- resumeApi: "https://example.com/resume",
1032
- onError: (error) => {
1033
- errors.push(error.message);
1034
- },
1035
- });
1036
- aui().thread().resumeRun({ parentId: null });
1037
-
1038
- await waitFor(() =>
1039
- expect(errors).toEqual([
1040
- 'statewire: invalid Aui-Replay-Content-Length header "garbage"',
1041
- ]),
1042
- );
1043
- });
1044
-
1045
- it("reads body object getters at request time", async () => {
1046
- const fetchMock = installFetch();
1047
- let dynamic = "before";
1048
- const { aui } = mountThread({
1049
- body: {
1050
- get dynamic() {
1051
- return dynamic;
1052
- },
1053
- },
1054
- });
1055
-
1056
- dynamic = "after";
1057
- sendCommand(aui, { type: "custom-a" } as never);
1058
-
1059
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1060
- expect(fetchMock.requests[0]!.body.dynamic).toBe("after");
1061
- });
1062
-
1063
- it("supports async body functions", async () => {
1064
- const fetchMock = installFetch();
1065
- const { aui } = mountThread({
1066
- body: async () => ({ sessionId: "s1" }),
1067
- });
1068
-
1069
- sendCommand(aui, { type: "custom-a" } as never);
1070
-
1071
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1072
- expect(fetchMock.requests[0]!.body.sessionId).toBe("s1");
1073
- });
1074
-
1075
- it("supports async header functions", async () => {
1076
- const fetchMock = installFetch();
1077
- const { aui } = mountThread({
1078
- headers: async () => ({ authorization: "Bearer token" }),
1079
- });
1080
-
1081
- sendCommand(aui, { type: "custom-a" } as never);
1082
-
1083
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1084
- const headers = new Headers(fetchMock.requests[0]!.init.headers);
1085
- expect(headers.get("authorization")).toBe("Bearer token");
1086
- expect(headers.get("content-type")).toBe("application/json");
1087
- });
1088
-
1089
- it("applies prepareSendCommandsRequest to the request body", async () => {
1090
- const fetchMock = installFetch();
1091
- const { aui } = mountThread({
1092
- prepareSendCommandsRequest: async (body) => ({
1093
- wrapped: { commands: body.commands },
1094
- }),
1095
- });
1096
-
1097
- sendCommand(aui, { type: "custom-a" } as never);
1098
-
1099
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1100
- expect(fetchMock.requests[0]!.body).toEqual({
1101
- wrapped: { commands: [{ type: "custom-a" }] },
1102
- });
1103
- });
1104
-
1105
- it("passes custom user commands through verbatim", async () => {
1106
- const fetchMock = installFetch();
1107
- const { aui } = mountThread();
1108
-
1109
- sendCommand(aui, {
1110
- type: "set-model",
1111
- modelId: "gpt-6",
1112
- nested: { a: [1, 2] },
1113
- } as never);
1114
-
1115
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1116
- expect(fetchMock.requests[0]!.body.commands).toEqual([
1117
- { type: "set-model", modelId: "gpt-6", nested: { a: [1, 2] } },
1118
- ]);
1119
- });
1120
-
1121
- it("sends model context (system, tools, callSettings, config) in the request body", async () => {
1122
- const fetchMock = installFetch();
1123
- const { aui } = mountThread();
1124
-
1125
- aui()
1126
- .modelContext()
1127
- .register({
1128
- getModelContext: () => ({
1129
- system: "be helpful",
1130
- tools: {
1131
- probe_tool: {
1132
- parameters: { type: "object", properties: {} },
1133
- },
1134
- },
1135
- callSettings: { temperature: 0.5 },
1136
- config: { modelName: "test-model" },
1137
- }),
1138
- });
1139
-
1140
- sendCommand(aui, { type: "custom-a" } as never);
1141
-
1142
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1143
- const body = fetchMock.requests[0]!.body;
1144
- expect(body.system).toBe("be helpful");
1145
- expect(body.tools).toEqual({
1146
- probe_tool: { parameters: { type: "object", properties: {} } },
1147
- });
1148
- expect(body.callSettings).toEqual({ temperature: 0.5 });
1149
- expect(body.config).toEqual({ modelName: "test-model" });
1150
- // deprecated top-level spread, matching the legacy runtime
1151
- expect(body.temperature).toBe(0.5);
1152
- expect(body.modelName).toBe("test-model");
1153
- });
1154
-
1155
- it("imports external state", async () => {
1156
- installFetch();
1157
- const { aui } = mountThread();
1158
-
1159
- aui().thread().importExternalState!({
1160
- messages: [{ id: "m1", role: "assistant", text: "imported" }],
1161
- });
1162
-
1163
- await waitFor(() => expect(threadTexts(aui)).toEqual(["imported"]));
1164
- });
1165
-
1166
- it("importExternalState preserves queued commands and sends the imported state", async () => {
1167
- const fetchMock = installFetch();
1168
- const servers: StreamResponse[] = [];
1169
- fetchMock.setHandler(() => {
1170
- const server = createStreamResponse();
1171
- servers.push(server);
1172
- if (servers.length > 1) server.done();
1173
- return server.response;
1174
- });
1175
-
1176
- const { aui } = mountThread();
1177
-
1178
- sendCommand(aui, { type: "custom-a" } as never);
1179
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1180
-
1181
- // custom-b queues while the run streams; the import must not clobber it.
1182
- sendCommand(aui, { type: "custom-b" } as never);
1183
- const imported: TestState = {
1184
- messages: [{ id: "m1", role: "assistant", text: "imported" }],
1185
- };
1186
- aui().thread().importExternalState!(imported);
1187
-
1188
- await waitFor(() => expect(threadTexts(aui)).toEqual(["imported"]));
1189
-
1190
- servers[0]!.done();
1191
- await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
1192
- expect(fetchMock.requests[1]!.body.commands).toEqual([
1193
- { type: "custom-b" },
1194
- ]);
1195
- expect(fetchMock.requests[1]!.body.state).toEqual(imported);
1196
- });
1197
-
1198
- it("importExternalState aborts executing tools without leaking their cancellation results", async () => {
1199
- const fetchMock = installFetch();
1200
- const servers: StreamResponse[] = [];
1201
- fetchMock.setHandler(() => {
1202
- const server = createStreamResponse();
1203
- servers.push(server);
1204
- if (servers.length > 1) server.done();
1205
- return server.response;
1206
- });
1207
-
1208
- let executing = false;
1209
- const { aui } = mountThread({ converter: toolCallConverter() });
1210
- aui()
1211
- .modelContext()
1212
- .register({
1213
- getModelContext: () => ({
1214
- tools: {
1215
- probe_tool: {
1216
- parameters: { type: "object", properties: {} },
1217
- execute: () => {
1218
- executing = true;
1219
- return new Promise(() => {});
1220
- },
1221
- },
1222
- },
1223
- }),
1224
- });
1225
-
1226
- sendCommand(aui, { type: "custom-a" } as never);
1227
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1228
- emitToolCall(servers[0]!);
1229
-
1230
- await waitFor(() => expect(executing).toBe(true));
1231
-
1232
- // The imported state no longer contains the tool call.
1233
- aui().thread().importExternalState!({
1234
- messages: [{ id: "m1", role: "assistant", text: "restored" }],
1235
- });
1236
-
1237
- await waitFor(() => expect(threadTexts(aui)).toEqual(["restored"]));
1238
- await waitFor(() =>
1239
- expect(aui().thread().getState().isRunning).toBe(false),
1240
- );
1241
-
1242
- // Give any stray run/input dispatch a chance to fire.
1243
- await new Promise((resolve) => setTimeout(resolve, 20));
1244
- expect(
1245
- allCommands(fetchMock.requests).filter((c) => c.type === "run/input"),
1246
- ).toEqual([]);
1247
- });
1248
-
1249
- it("enables edit and attachments capabilities from options", async () => {
1250
- installFetch();
1251
- const attachmentAdapter = {
1252
- accept: "image/*",
1253
- add: async () => ({}) as never,
1254
- remove: async () => {},
1255
- send: async () => ({}) as never,
1256
- };
1257
- const { aui } = mountThread({
1258
- capabilities: { edit: true },
1259
- adapters: { attachments: attachmentAdapter },
1260
- });
1261
-
1262
- const capabilities = aui().thread().getState().capabilities;
1263
- expect(capabilities.edit).toBe(true);
1264
- expect(capabilities.attachments).toBe(true);
1265
- expect(aui().thread().composer().getState().attachmentAccept).toBe(
1266
- "image/*",
1267
- );
1268
- });
1269
-
1270
- it("folds completed attachments into the run/steer command (CompositeAttachmentAdapter)", async () => {
1271
- const fetchMock = installFetch();
1272
- const { aui } = mountThread({
1273
- adapters: {
1274
- attachments: new CompositeAttachmentAdapter([
1275
- new SimpleTextAttachmentAdapter(),
1276
- ]),
1277
- },
1278
- });
1279
-
1280
- const file = new File(["attached body"], "notes.txt", {
1281
- type: "text/plain",
1282
- });
1283
- await aui().thread().composer().addAttachment(file);
1284
- aui().thread().composer().setText("see file");
1285
- await waitFor(() => {
1286
- const composer = aui().thread().getState().composer;
1287
- expect(composer.text).toBe("see file");
1288
- expect(composer.attachments).toHaveLength(1);
1289
- });
1290
- aui().thread().composer().send();
1291
-
1292
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1293
- const command = fetchMock.requests[0]!.body.commands[0];
1294
- expect(command.type).toBe("run/steer");
1295
- const texts = command.message.parts.map((p: any) => p.text);
1296
- expect(texts).toHaveLength(1);
1297
- expect(texts[0]).toContain("see file");
1298
- expect(texts[0]).toContain("attached body");
1299
- expect(texts[0]).toContain("notes.txt");
1300
- });
1301
-
1302
- it("edits send run/edit with the edited message as sourceId", async () => {
1303
- const fetchMock = installFetch();
1304
- const { aui } = mountThread({ capabilities: { edit: true } });
1305
-
1306
- aui().thread().importExternalState!({
1307
- messages: [
1308
- { id: "u1", role: "user", text: "one" },
1309
- { id: "a1", role: "assistant", text: "two" },
1310
- { id: "u2", role: "user", text: "three" },
1311
- ],
1312
- });
1313
- await waitFor(() =>
1314
- expect(threadTexts(aui)).toEqual(["one", "two", "three"]),
1315
- );
1316
-
1317
- const composer = aui().thread().message({ id: "u2" }).composer();
1318
- composer.beginEdit();
1319
- await waitFor(() => expect(composer.getState().isEditing).toBe(true));
1320
- composer.setText("edited");
1321
- await waitFor(() => expect(composer.getState().text).toBe("edited"));
1322
- composer.send();
1323
-
1324
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1325
- expect(fetchMock.requests[0]!.body.commands).toEqual([
1326
- {
1327
- type: "run/edit",
1328
- runId: expect.any(String),
1329
- message: {
1330
- id: expect.any(String),
1331
- role: "user",
1332
- parts: [{ type: "text", text: "edited" }],
1333
- },
1334
- sourceId: "u2",
1335
- runAnchorMessageId: "a1",
1336
- },
1337
- ]);
1338
- expect("parentId" in fetchMock.requests[0]!.body).toBe(false);
1339
- });
1340
-
1341
- it("composer sends carry the last message's id as parentId; the run consumes it", async () => {
1342
- const fetchMock = installFetch();
1343
- const { aui } = mountThread();
1344
-
1345
- aui().thread().importExternalState!({
1346
- messages: [
1347
- { id: "u1", role: "user", text: "hi" },
1348
- { id: "a1", role: "assistant", text: "yo" },
1349
- ],
1350
- } satisfies TestState);
1351
- await waitFor(() => expect(threadTexts(aui)).toEqual(["hi", "yo"]));
1352
-
1353
- aui().thread().composer().setText("again");
1354
- await waitFor(() =>
1355
- expect(aui().thread().getState().composer.text).toBe("again"),
1356
- );
1357
- aui().thread().composer().send();
1358
-
1359
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1360
- const body = fetchMock.requests[0]!.body;
1361
- expect(body.parentId).toBe("a1");
1362
- expect(body.commands).toEqual([
1363
- {
1364
- type: "run/steer",
1365
- runId: expect.any(String),
1366
- message: {
1367
- id: expect.any(String),
1368
- role: "user",
1369
- parts: [{ type: "text", text: "again" }],
1370
- },
1371
- runAnchorMessageId: "a1",
1372
- },
1373
- ]);
1374
-
1375
- await waitFor(() =>
1376
- expect(aui().thread().getState().isRunning).toBe(false),
1377
- );
1378
- sendCommand(aui, { type: "custom-a" } as never);
1379
- await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
1380
- expect("parentId" in fetchMock.requests[1]!.body).toBe(false);
1381
- });
1382
-
1383
- it("a mid-run append's parentId reaches the follow-up flush", async () => {
1384
- const fetchMock = installFetch();
1385
- const servers: StreamResponse[] = [];
1386
- fetchMock.setHandler(() => {
1387
- const server = createStreamResponse();
1388
- servers.push(server);
1389
- return server.response;
1390
- });
1391
-
1392
- const { aui } = mountThread();
1393
- aui().thread().importExternalState!({
1394
- messages: [
1395
- { id: "u1", role: "user", text: "hi" },
1396
- { id: "a1", role: "assistant", text: "yo" },
1397
- ],
1398
- } satisfies TestState);
1399
- await waitFor(() => expect(threadTexts(aui)).toEqual(["hi", "yo"]));
1400
-
1401
- aui().thread().append("first");
1402
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1403
- expect(fetchMock.requests[0]!.body.parentId).toBe("a1");
1404
-
1405
- servers[0]!.emit({
1406
- type: "update-state",
1407
- operations: [
1408
- {
1409
- type: "set",
1410
- path: ["messages"],
1411
- value: [
1412
- { id: "u1", role: "user", text: "hi" },
1413
- { id: "a1", role: "assistant", text: "yo" },
1414
- { id: "u2", role: "user", text: "first" },
1415
- { id: "a2", role: "assistant", text: "sure" },
1416
- ],
1417
- },
1418
- ],
1419
- });
1420
- await waitFor(() => expect(threadTexts(aui)).toHaveLength(4));
1421
-
1422
- aui().thread().append("second");
1423
- servers[0]!.done();
1424
-
1425
- await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
1426
- expect(fetchMock.requests[1]!.body.parentId).toBe("a2");
1427
- servers[1]!.done();
1428
- });
1429
-
1430
- it("executes frontend tools and posts run/input in a follow-up run", async () => {
1431
- const fetchMock = installFetch();
1432
- const servers: StreamResponse[] = [];
1433
- fetchMock.setHandler(() => {
1434
- const server = createStreamResponse();
1435
- servers.push(server);
1436
- return server.response;
1437
- });
1438
-
1439
- let resolveExecute!: (value: unknown) => void;
1440
- const executeGate = new Promise((resolve) => {
1441
- resolveExecute = resolve;
1442
- });
1443
-
1444
- let executing = false;
1445
- const { aui } = mountThread({ converter: toolCallConverter() });
1446
- aui()
1447
- .modelContext()
1448
- .register({
1449
- getModelContext: () => ({
1450
- tools: {
1451
- probe_tool: {
1452
- parameters: { type: "object", properties: {} },
1453
- execute: async () => {
1454
- executing = true;
1455
- await executeGate;
1456
- return { probed: true };
1457
- },
1458
- },
1459
- },
1460
- }),
1461
- });
1462
-
1463
- sendCommand(aui, { type: "custom-a" } as never);
1464
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1465
- emitToolCall(servers[0]!);
1466
-
1467
- await waitFor(() => expect(executing).toBe(true));
1468
-
1469
- resolveExecute(undefined);
1470
-
1471
- await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
1472
- expect(fetchMock.requests[1]!.body.commands).toEqual([
1473
- {
1474
- type: "run/input",
1475
- requestId: "req-tc1",
1476
- response: { output: { probed: true } },
1477
- },
1478
- ]);
1479
- servers[1]!.done();
1480
-
1481
- await waitFor(() =>
1482
- expect(aui().thread().getState().isRunning).toBe(false),
1483
- );
1484
- });
1485
-
1486
- it("resumes human-input interrupts through resumeToolCall", async () => {
1487
- const fetchMock = installFetch();
1488
- const servers: StreamResponse[] = [];
1489
- fetchMock.setHandler(() => {
1490
- const server = createStreamResponse();
1491
- servers.push(server);
1492
- return server.response;
1493
- });
1494
-
1495
- const { aui } = mountThread({ converter: toolCallConverter() });
1496
- aui()
1497
- .modelContext()
1498
- .register({
1499
- getModelContext: () => ({
1500
- tools: {
1501
- probe_tool: {
1502
- parameters: { type: "object", properties: {} },
1503
- execute: async (_args: unknown, context: any) => {
1504
- await Promise.resolve();
1505
- return { answer: await context.human({ q: "proceed?" }) };
1506
- },
1507
- },
1508
- },
1509
- }),
1510
- });
1511
-
1512
- sendCommand(aui, { type: "custom-a" } as never);
1513
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1514
- emitToolCall(servers[0]!);
1515
-
1516
- // resumeToolCall throws until the tool is waiting on the interrupt.
1517
- await waitFor(() =>
1518
- aui()
1519
- .thread()
1520
- .message({ id: "a-tool" })
1521
- .part({ toolCallId: "tc1" })
1522
- .resumeToolCall("yes"),
1523
- );
1524
-
1525
- await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
1526
- expect(fetchMock.requests[1]!.body.commands).toEqual([
1527
- {
1528
- type: "run/input",
1529
- requestId: "req-tc1",
1530
- response: { output: { answer: "yes" } },
1531
- },
1532
- ]);
1533
- servers[1]!.done();
1534
- await waitFor(() =>
1535
- expect(aui().thread().getState().isRunning).toBe(false),
1536
- );
1537
- });
1538
-
1539
- it("cancelRun aborts in-flight tool executions", async () => {
1540
- const fetchMock = installFetch();
1541
- const servers: StreamResponse[] = [];
1542
- fetchMock.setHandler(() => {
1543
- const server = createStreamResponse();
1544
- servers.push(server);
1545
- return server.response;
1546
- });
1547
-
1548
- let executing = false;
1549
- const { aui } = mountThread({ converter: toolCallConverter() });
1550
- aui()
1551
- .modelContext()
1552
- .register({
1553
- getModelContext: () => ({
1554
- tools: {
1555
- probe_tool: {
1556
- parameters: { type: "object", properties: {} },
1557
- execute: () => {
1558
- executing = true;
1559
- return new Promise(() => {});
1560
- },
1561
- },
1562
- },
1563
- }),
1564
- });
1565
-
1566
- sendCommand(aui, { type: "custom-a" } as never);
1567
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1568
- emitToolCall(servers[0]!);
1569
-
1570
- await waitFor(() => expect(executing).toBe(true));
1571
-
1572
- aui().thread().cancelRun();
1573
-
1574
- await waitFor(() =>
1575
- expect(allCommands(fetchMock.requests)).toContainEqual({
1576
- type: "run/input",
1577
- requestId: "req-tc1",
1578
- response: { output: "Tool execution was cancelled.", isError: true },
1579
- }),
1580
- );
1581
- servers.at(-1)!.done();
1582
- });
1583
-
1584
- it("aborts in-flight tool executions when a new user message starts a run", async () => {
1585
- const fetchMock = installFetch();
1586
- const servers: StreamResponse[] = [];
1587
- fetchMock.setHandler(() => {
1588
- const server = createStreamResponse();
1589
- servers.push(server);
1590
- // Follow-up runs complete immediately; only the first run streams.
1591
- if (servers.length > 1) server.done();
1592
- return server.response;
1593
- });
1594
-
1595
- let executing = false;
1596
- const { aui } = mountThread({ converter: toolCallConverter() });
1597
- aui()
1598
- .modelContext()
1599
- .register({
1600
- getModelContext: () => ({
1601
- tools: {
1602
- probe_tool: {
1603
- parameters: { type: "object", properties: {} },
1604
- execute: () => {
1605
- executing = true;
1606
- return new Promise(() => {});
1607
- },
1608
- },
1609
- },
1610
- }),
1611
- });
1612
-
1613
- sendCommand(aui, { type: "custom-a" } as never);
1614
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1615
- emitToolCall(servers[0]!);
1616
-
1617
- await waitFor(() => expect(executing).toBe(true));
1618
-
1619
- aui().thread().append("next question");
1620
-
1621
- await waitFor(() => {
1622
- const commands = allCommands(fetchMock.requests);
1623
- expect(commands).toContainEqual({
1624
- type: "run/input",
1625
- requestId: "req-tc1",
1626
- response: { output: "Tool execution was cancelled.", isError: true },
1627
- });
1628
- expect(commands).toContainEqual({
1629
- type: "run/steer",
1630
- runId: expect.any(String),
1631
- message: {
1632
- id: expect.any(String),
1633
- role: "user",
1634
- parts: [{ type: "text", text: "next question" }],
1635
- },
1636
- runAnchorMessageId: "a-tool",
1637
- });
1638
- });
1639
- });
1640
-
1641
- it("unmounting mid-stream aborts the run without callbacks or crashes", async () => {
1642
- const fetchMock = installFetch();
1643
- let server!: StreamResponse;
1644
- let aborted = false;
1645
- fetchMock.setHandler(({ init }) => {
1646
- server = createStreamResponse();
1647
- init.signal?.addEventListener("abort", () => {
1648
- aborted = true;
1649
- server.error(
1650
- new DOMException("The operation was aborted.", "AbortError"),
1651
- );
1652
- });
1653
- return server.response;
1654
- });
1655
-
1656
- const onCancel = vi.fn();
1657
- const onError = vi.fn();
1658
- const onFinish = vi.fn();
1659
- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
1660
- try {
1661
- const { aui, unmount } = mountThread({ onCancel, onError, onFinish });
1662
- sendCommand(aui, { type: "custom-a" } as never);
1663
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1664
-
1665
- server.emit({
1666
- type: "update-state",
1667
- operations: [
1668
- {
1669
- type: "set",
1670
- path: ["messages"],
1671
- value: [{ id: "m1", role: "assistant", text: "hi" }],
1672
- },
1673
- ],
1674
- });
1675
- await waitFor(() => expect(threadTexts(aui)).toEqual(["hi"]));
1676
-
1677
- unmount();
1678
-
1679
- await waitFor(() => expect(aborted).toBe(true));
1680
- await new Promise((resolve) => setTimeout(resolve, 20));
1681
- expect(onCancel).not.toHaveBeenCalled();
1682
- expect(onError).not.toHaveBeenCalled();
1683
- expect(onFinish).not.toHaveBeenCalled();
1684
- expect(errorSpy).not.toHaveBeenCalled();
1685
- } finally {
1686
- errorSpy.mockRestore();
1687
- }
1688
- });
1689
-
1690
- it("runs normally under React StrictMode double-mounting", async () => {
1691
- const fetchMock = installFetch();
1692
- let server!: StreamResponse;
1693
- fetchMock.setHandler(() => {
1694
- server = createStreamResponse();
1695
- return server.response;
1696
- });
1697
-
1698
- const { aui } = mountThread(undefined, {
1699
- wrap: (node) => <StrictMode>{node}</StrictMode>,
1700
- });
1701
-
1702
- sendCommand(aui, { type: "custom-a" } as never);
1703
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1704
-
1705
- server.emit({
1706
- type: "update-state",
1707
- operations: [
1708
- {
1709
- type: "set",
1710
- path: ["messages"],
1711
- value: [{ id: "m1", role: "assistant", text: "strict" }],
1712
- },
1713
- ],
1714
- });
1715
- server.done();
1716
-
1717
- await waitFor(() => expect(threadTexts(aui)).toEqual(["strict"]));
1718
- await waitFor(() =>
1719
- expect(aui().thread().getState().isRunning).toBe(false),
1720
- );
1721
- expect(fetchMock.requests).toHaveLength(1);
1722
- });
1723
-
1724
- it("keeps message client identity stable when messages are prepended", async () => {
1725
- const fetchMock = installFetch();
1726
- let server!: StreamResponse;
1727
- fetchMock.setHandler(() => {
1728
- server = createStreamResponse();
1729
- return server.response;
1730
- });
1731
-
1732
- const { aui } = mountThread();
1733
- sendCommand(aui, { type: "custom-a" } as never);
1734
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1735
-
1736
- server.emit({
1737
- type: "update-state",
1738
- operations: [
1739
- {
1740
- type: "set",
1741
- path: ["messages"],
1742
- value: [{ id: "m2", role: "assistant", text: "reply" }],
1743
- },
1744
- ],
1745
- });
1746
- await waitFor(() => expect(threadTexts(aui)).toEqual(["reply"]));
1747
-
1748
- const before = aui().thread().message({ id: "m2" }).getState();
1749
- expect(before.branchNumber).toBe(1);
1750
- expect(before.branchCount).toBe(1);
1751
-
1752
- // History load prepends the echoed human message; m2 must survive
1753
- // re-keying (no duplicate, no phantom branch).
1754
- server.emit({
1755
- type: "update-state",
1756
- operations: [
1757
- {
1758
- type: "set",
1759
- path: ["messages"],
1760
- value: [
1761
- { id: "m1", role: "user", text: "question" },
1762
- { id: "m2", role: "assistant", text: "reply" },
1763
- ],
1764
- },
1765
- ],
1766
- });
1767
- server.done();
1768
-
1769
- await waitFor(() =>
1770
- expect(threadTexts(aui)).toEqual(["question", "reply"]),
1771
- );
1772
- const after = aui().thread().message({ id: "m2" }).getState();
1773
- expect(after.id).toBe("m2");
1774
- expect(after.branchNumber).toBe(1);
1775
- expect(after.branchCount).toBe(1);
1776
- expect(after.parentId).toBe("m1");
1777
- const ids = aui()
1778
- .thread()
1779
- .getState()
1780
- .messages.map((m) => m.id);
1781
- expect(ids).toEqual(["m1", "m2"]);
1782
- });
1783
-
1784
- it("re-renders state selectors only when the selected slice changes", async () => {
1785
- const fetchMock = installFetch();
1786
- let server!: StreamResponse;
1787
- fetchMock.setHandler(() => {
1788
- server = createStreamResponse();
1789
- return server.response;
1790
- });
1791
-
1792
- const todoValues: (string[] | undefined)[] = [];
1793
- const textValues: (string | undefined)[] = [];
1794
- const TodoProbe: FC = () => {
1795
- const todos = useAssistantTransportState((s) => (s as TestState).todos);
1796
- todoValues.push(todos);
1797
- return null;
1798
- };
1799
- const TextProbe: FC = () => {
1800
- const text = useAssistantTransportState(
1801
- (s) => (s as TestState).messages[0]?.text,
1802
- );
1803
- textValues.push(text);
1804
- return null;
1805
- };
1806
-
1807
- const { aui } = mountThread(
1808
- { initialState: { messages: [], todos: ["a"] } },
1809
- {
1810
- children: (
1811
- <>
1812
- <TodoProbe />
1813
- <TextProbe />
1814
- </>
1815
- ),
1816
- },
1817
- );
1818
-
1819
- sendCommand(aui, { type: "custom-a" } as never);
1820
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1821
-
1822
- server.emit({
1823
- type: "update-state",
1824
- operations: [
1825
- {
1826
- type: "set",
1827
- path: ["messages"],
1828
- value: [{ id: "m1", role: "assistant", text: "" }],
1829
- },
1830
- ],
1831
- });
1832
-
1833
- await waitFor(() => expect(textValues.at(-1)).toBe(""));
1834
- const todoRendersBeforeDeltas = todoValues.length;
1835
- const initialTodos = todoValues.at(-1);
1836
-
1837
- for (const delta of ["a", "b", "c", "d", "e"]) {
1838
- server.emit({
1839
- type: "update-state",
1840
- operations: [
1841
- {
1842
- type: "append-text",
1843
- path: ["messages", "0", "text"],
1844
- value: delta,
1845
- },
1846
- ],
1847
- });
1848
- await waitFor(() => expect(threadTexts(aui).at(-1)).toContain(delta));
1849
- }
1850
- server.done();
1851
-
1852
- // Every flushed batch reached the converter and the text selector.
1853
- await waitFor(() => expect(textValues.at(-1)).toBe("abcde"));
1854
-
1855
- // The untouched slice kept its identity — structural sharing means the
1856
- // todos selector saw no new value and did not re-render for the deltas.
1857
- expect(todoValues.at(-1)).toBe(initialTodos);
1858
- expect(todoValues.length).toBe(todoRendersBeforeDeltas);
1859
- });
1860
-
1861
- it("throws a descriptive error when transport hooks run against a non-transport thread", () => {
1862
- installFetch();
1863
- const errors: string[] = [];
1864
- const Probe: FC = () => {
1865
- try {
1866
- useAssistantTransportState();
1867
- } catch (error) {
1868
- errors.push((error as Error).message);
1869
- }
1870
- return null;
1871
- };
1872
- const App: FC = () => {
1873
- const aui = useAui({
1874
- thread: ExternalThread({ messages: [] }),
1875
- });
1876
- return (
1877
- <AuiProvider value={aui}>
1878
- <Probe />
1879
- </AuiProvider>
1880
- );
1881
- };
1882
- render(<App />);
1883
- expect(errors.at(0)).toMatch(/AssistantTransportThread/);
1884
- });
1885
-
1886
- it("sends threadId null when the thread list item lookup throws", async () => {
1887
- const fetchMock = installFetch();
1888
-
1889
- const brokenItem = {
1890
- getState: () => {
1891
- throw new Error("no current item");
1892
- },
1893
- };
1894
- const BrokenThreads = resource(
1895
- () =>
1896
- ({
1897
- getState: () => ({}),
1898
- item: () => brokenItem,
1899
- }) as never,
1900
- );
1901
-
1902
- const captured: { aui?: ReturnType<typeof useAui> } = {};
1903
- const Capture: FC = () => {
1904
- captured.aui = useAui();
1905
- return null;
1906
- };
1907
- const App: FC = () => {
1908
- const aui = useAui({
1909
- thread: AssistantTransportThread<TestState>({
1910
- initialState: INITIAL_STATE,
1911
- api: "https://example.com/api",
1912
- headers: {},
1913
- converter: defaultConverter,
1914
- protocol: "assistant-transport",
1915
- }),
1916
- threads: BrokenThreads() as never,
1917
- });
1918
- return (
1919
- <AuiProvider value={aui}>
1920
- <Capture />
1921
- </AuiProvider>
1922
- );
1923
- };
1924
- render(<App />);
1925
-
1926
- captured.aui!.thread().append("hello");
1927
-
1928
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1929
- expect(fetchMock.requests[0]!.body.threadId).toBeNull();
1930
- });
1931
-
1932
- it("exposes state and sendCommand through the public hooks", async () => {
1933
- const fetchMock = installFetch();
1934
-
1935
- const captured: {
1936
- state?: TestState;
1937
- send?: (command: AssistantTransportThread.Command) => void;
1938
- } = {};
1939
- const HookCapture: FC = () => {
1940
- captured.state = useAssistantTransportState() as TestState;
1941
- captured.send = useAssistantTransportSendCommand();
1942
- return null;
1943
- };
1944
- mountThread(undefined, { children: <HookCapture /> });
1945
-
1946
- await waitFor(() => expect(captured.state).toEqual(INITIAL_STATE));
1947
-
1948
- captured.send!({ type: "custom-a" } as never);
1949
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1950
- expect(fetchMock.requests[0]!.body.commands).toEqual([
1951
- { type: "custom-a" },
1952
- ]);
1953
- });
1954
-
1955
- it("derives tool part status from the message status (legacy parity)", async () => {
1956
- type S = TestState & { toolCall?: { id: string; result?: string } };
1957
- const converter = (state: S) => {
1958
- const tc = state.toolCall;
1959
- return {
1960
- messages: tc
1961
- ? [
1962
- {
1963
- id: "a1",
1964
- role: "assistant",
1965
- createdAt: new Date(0),
1966
- content: [
1967
- { type: "text", text: "let me check" },
1968
- {
1969
- type: "tool-call",
1970
- toolCallId: tc.id,
1971
- toolName: "probe_tool",
1972
- args: {},
1973
- argsText: "{}",
1974
- ...(tc.result !== undefined && { result: tc.result }),
1975
- },
1976
- ],
1977
- attachments: [],
1978
- metadata: { custom: {} },
1979
- status: tc.result
1980
- ? { type: "complete", reason: "stop" }
1981
- : { type: "running" },
1982
- } as never,
1983
- ]
1984
- : [],
1985
- isRunning: state.isRunning ?? false,
1986
- };
1987
- };
1988
- const fetchMock = installFetch();
1989
- const server = createStreamResponse();
1990
- fetchMock.setHandler(() => server.response);
1991
-
1992
- const { aui } = mountThread({ converter });
1993
- aui().thread().append("go");
1994
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1995
-
1996
- server.emit({
1997
- type: "update-state",
1998
- operations: [{ type: "set", path: ["toolCall"], value: { id: "tc1" } }],
1999
- });
2000
- await waitFor(() =>
2001
- expect(aui().thread().getState().messages).toHaveLength(1),
2002
- );
2003
- const part = () =>
2004
- aui().thread().message({ id: "a1" }).part({ toolCallId: "tc1" });
2005
- expect(part().getState().status).toEqual({ type: "running" });
2006
-
2007
- server.emit({
2008
- type: "update-state",
2009
- operations: [
2010
- { type: "set", path: ["toolCall"], value: { id: "tc1", result: "ok" } },
2011
- ],
2012
- });
2013
- server.done();
2014
- await waitFor(() =>
2015
- expect(part().getState().status).toEqual({ type: "complete" }),
2016
- );
2017
- });
2018
-
2019
- it("dispatches a synchronous composer setText + send sequence", async () => {
2020
- const fetchMock = installFetch();
2021
- const { aui } = mountThread();
2022
-
2023
- aui().thread().composer().setText("hello");
2024
- aui().thread().composer().send();
2025
-
2026
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2027
- expect(fetchMock.requests[0]!.body.commands[0].message.parts).toEqual([
2028
- { type: "text", text: "hello" },
2029
- ]);
2030
- });
2031
- });
2032
-
2033
- describe("reload", () => {
2034
- const completeFirstTurn = async (
2035
- fetchMock: ReturnType<typeof installFetch>,
2036
- aui: () => ReturnType<typeof useAui>,
2037
- ) => {
2038
- let server!: StreamResponse;
2039
- fetchMock.setHandler(() => {
2040
- server = createStreamResponse();
2041
- return server.response;
2042
- });
2043
- aui().thread().append("hello");
2044
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2045
- server.emit({
2046
- type: "update-state",
2047
- operations: [
2048
- {
2049
- type: "set",
2050
- path: ["messages"],
2051
- value: [
2052
- { id: "m1", role: "user", text: "hello" },
2053
- { id: "m2", role: "assistant", text: "hi" },
2054
- ],
2055
- },
2056
- ],
2057
- });
2058
- server.done();
2059
- await waitFor(() =>
2060
- expect(aui().thread().getState().isRunning).toBe(false),
2061
- );
2062
- };
2063
-
2064
- it("regenerates via a run/reload command targeting the assistant message", async () => {
2065
- const fetchMock = installFetch();
2066
- const { aui } = mountThread();
2067
- await completeFirstTurn(fetchMock, aui);
2068
-
2069
- aui().thread().message({ id: "m2" }).reload();
2070
- await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
2071
- expect(fetchMock.requests[1]!.body.commands).toEqual([
2072
- {
2073
- type: "run/reload",
2074
- runId: expect.any(String),
2075
- sourceId: "m2",
2076
- runAnchorMessageId: "m1",
2077
- },
2078
- ]);
2079
- expect("parentId" in fetchMock.requests[1]!.body).toBe(false);
2080
- });
2081
-
2082
- it("surfaces the error and recovers when the reload run fails", async () => {
2083
- const errors: string[] = [];
2084
- const fetchMock = installFetch();
2085
- const { aui } = mountThread({
2086
- onError: (error) => {
2087
- errors.push(error.message);
2088
- },
2089
- });
2090
- await completeFirstTurn(fetchMock, aui);
2091
-
2092
- fetchMock.setHandler(() => new Response(null, { status: 500 }));
2093
- aui().thread().message({ id: "m2" }).reload();
2094
- await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
2095
- await waitFor(() =>
2096
- expect(aui().thread().getState().isRunning).toBe(false),
2097
- );
2098
- await waitFor(() => expect(errors).toHaveLength(1));
2099
-
2100
- fetchMock.setHandler(() => {
2101
- const server = createStreamResponse();
2102
- server.done();
2103
- return server.response;
2104
- });
2105
- aui().thread().message({ id: "m2" }).reload();
2106
- await waitFor(() => expect(fetchMock.requests).toHaveLength(3));
2107
- expect(fetchMock.requests[2]!.body.commands).toEqual([
2108
- {
2109
- type: "run/reload",
2110
- runId: expect.any(String),
2111
- sourceId: "m2",
2112
- runAnchorMessageId: "m1",
2113
- },
2114
- ]);
2115
- });
2116
- });
2117
-
2118
- describe("message queue", () => {
2119
- it("buffers a send during a run and dispatches it once the run settles", async () => {
2120
- const fetchMock = installFetch();
2121
- const servers: StreamResponse[] = [];
2122
- fetchMock.setHandler(() => {
2123
- const server = createStreamResponse();
2124
- servers.push(server);
2125
- return server.response;
2126
- });
2127
-
2128
- const { aui } = mountThread({ capabilities: { queue: true } });
2129
- aui().thread().append("first");
2130
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2131
- await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
2132
- expect(aui().thread().getState().capabilities.queue).toBe(true);
2133
-
2134
- aui().thread().append("second");
2135
- await waitFor(() =>
2136
- expect(aui().thread().composer().getState().queue).toMatchObject([
2137
- { prompt: "second" },
2138
- ]),
2139
- );
2140
- expect(fetchMock.requests).toHaveLength(1);
2141
-
2142
- servers[0]!.emit({
2143
- type: "update-state",
2144
- operations: [
2145
- {
2146
- type: "set",
2147
- path: ["messages"],
2148
- value: [
2149
- { id: "m1", role: "user", text: "first" },
2150
- { id: "m2", role: "assistant", text: "reply" },
2151
- ],
2152
- },
2153
- ],
2154
- });
2155
- servers[0]!.done();
2156
-
2157
- await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
2158
- expect(fetchMock.requests[1]!.body.commands).toMatchObject([
2159
- {
2160
- type: "run/steer",
2161
- message: { role: "user", parts: [{ type: "text", text: "second" }] },
2162
- },
2163
- ]);
2164
- // restamped at dispatch time: parented under the finished run's head
2165
- expect(fetchMock.requests[1]!.body.parentId).toBe("m2");
2166
- await waitFor(() =>
2167
- expect(aui().thread().composer().getState().queue).toHaveLength(0),
2168
- );
2169
- });
2170
-
2171
- it("holds the queue through the stop-settling window until the transport releases", async () => {
2172
- const fetchMock = installFetch();
2173
- const servers: StreamResponse[] = [];
2174
- fetchMock.setHandler(() => {
2175
- const server = createStreamResponse();
2176
- servers.push(server);
2177
- return server.response;
2178
- });
2179
-
2180
- type RunningState = TestState & { running?: boolean };
2181
- const { aui } = mountThread({
2182
- capabilities: { queue: true },
2183
- converter: (state) => ({
2184
- ...defaultConverter(state),
2185
- isRunning: (state as RunningState).running ?? false,
2186
- }),
2187
- optimistic: undefined,
2188
- });
2189
-
2190
- aui().thread().append("first");
2191
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2192
- servers[0]!.emit({
2193
- type: "update-state",
2194
- operations: [{ type: "set", path: ["running"], value: true }],
2195
- });
2196
- await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
2197
-
2198
- aui().thread().append("second");
2199
- await waitFor(() =>
2200
- expect(aui().thread().composer().getState().queue).toHaveLength(1),
2201
- );
2202
-
2203
- // state says the run stopped, but the stream has not settled yet: the
2204
- // queued message must not dispatch into this window
2205
- servers[0]!.emit({
2206
- type: "update-state",
2207
- operations: [{ type: "set", path: ["running"], value: false }],
2208
- });
2209
- await waitFor(() =>
2210
- expect(aui().thread().getState().isRunning).toBe(false),
2211
- );
2212
- expect(fetchMock.requests).toHaveLength(1);
2213
- expect(aui().thread().composer().getState().queue).toHaveLength(1);
2214
-
2215
- servers[0]!.done();
2216
-
2217
- await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
2218
- expect(fetchMock.requests[1]!.body.commands).toMatchObject([
2219
- {
2220
- type: "run/steer",
2221
- message: { parts: [{ type: "text", text: "second" }] },
2222
- },
2223
- ]);
2224
- });
2225
-
2226
- it("drops queued messages when the run is cancelled", async () => {
2227
- const fetchMock = installFetch();
2228
- fetchMock.setHandler(({ init }) => abortableStream(init).response);
2229
-
2230
- const { aui } = mountThread({ capabilities: { queue: true } });
2231
- aui().thread().append("first");
2232
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2233
- await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
2234
-
2235
- aui().thread().append("second");
2236
- await waitFor(() =>
2237
- expect(aui().thread().composer().getState().queue).toHaveLength(1),
2238
- );
2239
-
2240
- aui().thread().cancelRun();
2241
-
2242
- await waitFor(() =>
2243
- expect(aui().thread().getState().isRunning).toBe(false),
2244
- );
2245
- expect(aui().thread().composer().getState().queue).toHaveLength(0);
2246
- expect(fetchMock.requests).toHaveLength(1);
2247
- });
2248
-
2249
- it("stays off without the capability", async () => {
2250
- installFetch();
2251
- const { aui } = mountThread();
2252
- await waitFor(() =>
2253
- expect(aui().thread().getState().capabilities.queue).toBe(false),
2254
- );
2255
- });
2256
- });
2257
-
2258
- describe("run/continue", () => {
2259
- it("resumes via a run/continue command under capabilities.continue", async () => {
2260
- const fetchMock = installFetch();
2261
- const { aui } = mountThread({ capabilities: { continue: true } });
2262
-
2263
- aui().thread().resumeRun({ parentId: null });
2264
-
2265
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2266
- expect(fetchMock.requests[0]!.url).toBe("https://example.com/api");
2267
- expect(fetchMock.requests[0]!.body.commands).toEqual([
2268
- { type: "run/continue" },
2269
- ]);
2270
- });
2271
- });
2272
-
2273
- describe("server queue projection", () => {
2274
- type QueueState = TestState & {
2275
- queue?: { id: string; parts: { type: "text"; text: string }[] }[];
2276
- steerQueue?: { id: string; parts: { type: "text"; text: string }[] }[];
2277
- runs?: {
2278
- runId: string | null;
2279
- status: string;
2280
- queue: never[];
2281
- steerQueue: never[];
2282
- dispatching: null;
2283
- error: null;
2284
- }[];
2285
- };
2286
-
2287
- const queueConverter: typeof defaultConverter = (state) => ({
2288
- ...defaultConverter(state),
2289
- queue: (state as QueueState).queue ?? [],
2290
- steerQueue: (state as QueueState).steerQueue ?? [],
2291
- });
2292
-
2293
- const textEntry = (id: string, text: string) => ({
2294
- id,
2295
- parts: [{ type: "text" as const, text }],
2296
- });
2297
-
2298
- it("routes appends through run/enqueue and projects the lanes steer-first", async () => {
2299
- const fetchMock = installFetch();
2300
- const { aui } = mountThread({
2301
- converter: queueConverter,
2302
- initialState: {
2303
- messages: [],
2304
- queue: [textEntry("q1", "first")],
2305
- steerQueue: [textEntry("s1", "urgent")],
2306
- } as QueueState,
2307
- });
2308
-
2309
- await waitFor(() =>
2310
- expect(aui().thread().composer().getState().queue).toMatchObject([
2311
- { id: "s1", prompt: "urgent" },
2312
- { id: "q1", prompt: "first" },
2313
- ]),
2314
- );
2315
-
2316
- aui().thread().append("hello");
2317
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2318
- expect(fetchMock.requests[0]!.body.commands).toEqual([
2319
- {
2320
- type: "run/enqueue",
2321
- runId: expect.any(String),
2322
- message: {
2323
- id: expect.any(String),
2324
- role: "user",
2325
- parts: [{ type: "text", text: "hello" }],
2326
- },
2327
- runAnchorMessageId: null,
2328
- },
2329
- ]);
2330
- });
2331
-
2332
- it("steers when the composer sends mid-run", async () => {
2333
- const fetchMock = installFetch();
2334
- const servers: StreamResponse[] = [];
2335
- fetchMock.setHandler(() => {
2336
- const server = createStreamResponse();
2337
- servers.push(server);
2338
- return server.response;
2339
- });
2340
-
2341
- const { aui } = mountThread({ converter: queueConverter });
2342
-
2343
- aui().thread().append("hello");
2344
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2345
- await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
2346
-
2347
- aui().thread().composer().setText("steer me");
2348
- await waitFor(() =>
2349
- expect(aui().thread().getState().composer.text).toBe("steer me"),
2350
- );
2351
- aui().thread().composer().send();
2352
-
2353
- servers[0]!.done();
2354
- await waitFor(() =>
2355
- expect(allCommands(fetchMock.requests)).toContainEqual({
2356
- type: "run/steer",
2357
- runId: expect.any(String),
2358
- message: {
2359
- id: expect.any(String),
2360
- role: "user",
2361
- parts: [{ type: "text", text: "steer me" }],
2362
- },
2363
- runAnchorMessageId: null,
2364
- }),
2365
- );
2366
- });
2367
-
2368
- it("sends item controls as run/* commands with placement", async () => {
2369
- const fetchMock = installFetch();
2370
- const { aui } = mountThread({
2371
- converter: queueConverter,
2372
- runs: true,
2373
- initialState: {
2374
- messages: [],
2375
- queue: [textEntry("q1", "first"), textEntry("q2", "second")],
2376
- steerQueue: [textEntry("s1", "urgent")],
2377
- runs: [
2378
- {
2379
- runId: "run-7",
2380
- status: "running",
2381
- queue: [],
2382
- steerQueue: [],
2383
- dispatching: null,
2384
- error: null,
2385
- },
2386
- ],
2387
- } as QueueState,
2388
- });
2389
-
2390
- await waitFor(() =>
2391
- expect(aui().thread().composer().getState().queue).toHaveLength(3),
2392
- );
2393
-
2394
- aui().thread().composer().queueItem({ id: "q1" }).steer();
2395
- await waitFor(() =>
2396
- expect(allCommands(fetchMock.requests)).toContainEqual({
2397
- type: "run/steer",
2398
- runId: "run-7",
2399
- messageId: "q1",
2400
- insertAfter: null,
2401
- }),
2402
- );
2403
-
2404
- aui()
2405
- .thread()
2406
- .composer()
2407
- .queueItem({ id: "q2" })
2408
- .move({ lane: "queue", insertBefore: "q1" });
2409
- await waitFor(() =>
2410
- expect(allCommands(fetchMock.requests)).toContainEqual({
2411
- type: "run/enqueue",
2412
- runId: "run-7",
2413
- messageId: "q2",
2414
- insertBefore: "q1",
2415
- }),
2416
- );
2417
-
2418
- aui().thread().composer().queueItem({ id: "s1" }).remove();
2419
- await waitFor(() =>
2420
- expect(allCommands(fetchMock.requests)).toContainEqual({
2421
- type: "run/dequeue",
2422
- runId: "run-7",
2423
- messageId: "s1",
2424
- }),
2425
- );
2426
- });
2427
-
2428
- it("throws when steerQueue is projected without queue", () => {
2429
- installFetch();
2430
- expect(() =>
2431
- mountThread({
2432
- converter: (state) => ({
2433
- ...defaultConverter(state),
2434
- steerQueue: [],
2435
- }),
2436
- }),
2437
- ).toThrow(
2438
- "statewire: the converter's steerQueue projection requires the queue projection",
2439
- );
2440
- });
2441
-
2442
- it("throws when the queue projection is combined with capabilities.queue", () => {
2443
- installFetch();
2444
- expect(() =>
2445
- mountThread({
2446
- converter: queueConverter,
2447
- capabilities: { queue: true },
2448
- }),
2449
- ).toThrow(
2450
- "statewire: the converter's queue projection excludes capabilities.queue",
2451
- );
2452
- });
2453
-
2454
- it("throws when the queue projection appears after the first convert", () => {
2455
- installFetch();
2456
- const withQueue: typeof defaultConverter = (state) => ({
2457
- ...defaultConverter(state),
2458
- queue: [],
2459
- });
2460
-
2461
- const captured: { setConverter?: (c: typeof defaultConverter) => void } =
2462
- {};
2463
- const App: FC = () => {
2464
- const [converter, setConverter] = useState(() => defaultConverter);
2465
- captured.setConverter = (c) => setConverter(() => c);
2466
- const aui = useAui({
2467
- thread: AssistantTransportThread<TestState>({
2468
- initialState: INITIAL_STATE,
2469
- api: "https://example.com/api",
2470
- headers: {},
2471
- converter,
2472
- protocol: "assistant-transport",
2473
- }),
2474
- });
2475
- return <AuiProvider value={aui}>{null}</AuiProvider>;
2476
- };
2477
- const { unmount } = render(<App />);
2478
-
2479
- expect(() => act(() => captured.setConverter!(withQueue))).toThrow(
2480
- /queue projection must be stable/,
2481
- );
2482
- unmount();
2483
- });
2484
- });
2485
-
2486
- describe("input requests", () => {
2487
- type InputState = TestState & {
2488
- toolCall?: { id: string; name: string; argsText: string };
2489
- inputRequests?: AssistantTransportThread.InputRequestState[];
2490
- };
2491
-
2492
- const requestConverter = (approval?: {
2493
- id: string;
2494
- }): typeof defaultConverter => {
2495
- const inner = toolCallConverter();
2496
- return (state) => {
2497
- const converted = inner(state);
2498
- return {
2499
- ...converted,
2500
- messages: approval
2501
- ? converted.messages.map((m) =>
2502
- m.id === "a-tool"
2503
- ? ({
2504
- ...m,
2505
- content: [{ ...(m.content[0] as object), approval }],
2506
- } as unknown as typeof m)
2507
- : m,
2508
- )
2509
- : converted.messages,
2510
- inputRequests: (state as InputState).inputRequests ?? [],
2511
- };
2512
- };
2513
- };
2514
-
2515
- const toolCallPart = (aui: () => ReturnType<typeof useAui>) =>
2516
- aui().thread().message({ id: "a-tool" }).part({ toolCallId: "tc1" });
2517
-
2518
- it("routes addToolResult through run/input when a pending tool-call request matches", async () => {
2519
- const fetchMock = installFetch();
2520
- const { aui } = mountThread({
2521
- converter: requestConverter(),
2522
- initialState: {
2523
- messages: [],
2524
- toolCall: { id: "tc1", name: "probe_tool", argsText: "{}" },
2525
- inputRequests: [
2526
- { type: "tool-call", id: "req1", toolCallId: "tc1", response: null },
2527
- ],
2528
- } as InputState,
2529
- });
2530
-
2531
- await waitFor(() =>
2532
- expect(aui().thread().getState().messages).toHaveLength(1),
2533
- );
2534
- toolCallPart(aui).addToolResult({ ok: true });
2535
-
2536
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2537
- expect(fetchMock.requests[0]!.body.commands).toEqual([
2538
- {
2539
- type: "run/input",
2540
- requestId: "req1",
2541
- response: { output: { ok: true } },
2542
- },
2543
- ]);
2544
- });
2545
-
2546
- it("passes isError and artifact through the run/input response", async () => {
2547
- const fetchMock = installFetch();
2548
- const { aui } = mountThread({
2549
- converter: requestConverter(),
2550
- initialState: {
2551
- messages: [],
2552
- toolCall: { id: "tc1", name: "probe_tool", argsText: "{}" },
2553
- inputRequests: [
2554
- { type: "tool-call", id: "req1", toolCallId: "tc1", response: null },
2555
- ],
2556
- } as InputState,
2557
- });
2558
-
2559
- await waitFor(() =>
2560
- expect(aui().thread().getState().messages).toHaveLength(1),
2561
- );
2562
- toolCallPart(aui).addToolResult(
2563
- new ToolResponse({
2564
- result: { reason: "boom" },
2565
- isError: true,
2566
- artifact: { log: "trace" },
2567
- }),
2568
- );
2569
-
2570
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2571
- expect(fetchMock.requests[0]!.body.commands).toEqual([
2572
- {
2573
- type: "run/input",
2574
- requestId: "req1",
2575
- response: {
2576
- output: { reason: "boom" },
2577
- isError: true,
2578
- artifact: { log: "trace" },
2579
- },
2580
- },
2581
- ]);
2582
- });
2583
-
2584
- it("throws without a matching pending request", async () => {
2585
- const fetchMock = installFetch();
2586
- const { aui } = mountThread({
2587
- converter: requestConverter(),
2588
- initialState: {
2589
- messages: [],
2590
- toolCall: { id: "tc1", name: "probe_tool", argsText: "{}" },
2591
- inputRequests: [
2592
- {
2593
- type: "tool-call",
2594
- id: "req1",
2595
- toolCallId: "other",
2596
- response: null,
2597
- },
2598
- ],
2599
- } as InputState,
2600
- });
2601
-
2602
- await waitFor(() =>
2603
- expect(aui().thread().getState().messages).toHaveLength(1),
2604
- );
2605
- expect(() => toolCallPart(aui).addToolResult({ ok: true })).toThrow(
2606
- 'statewire: no tool-call input request for tool call "tc1"',
2607
- );
2608
-
2609
- await new Promise((resolve) => setTimeout(resolve, 20));
2610
- expect(fetchMock.requests).toHaveLength(0);
2611
- });
2612
-
2613
- it("throws on answering a request that already carries a response", async () => {
2614
- installFetch();
2615
- const { aui } = mountThread({
2616
- converter: requestConverter(),
2617
- initialState: {
2618
- messages: [],
2619
- toolCall: { id: "tc1", name: "probe_tool", argsText: "{}" },
2620
- inputRequests: [
2621
- {
2622
- type: "tool-call",
2623
- id: "req1",
2624
- toolCallId: "tc1",
2625
- response: { output: "done" },
2626
- },
2627
- ],
2628
- } as InputState,
2629
- });
2630
-
2631
- await waitFor(() =>
2632
- expect(aui().thread().getState().messages).toHaveLength(1),
2633
- );
2634
- expect(() => toolCallPart(aui).addToolResult({ ok: true })).toThrow(
2635
- 'statewire: input request "req1" is already answered',
2636
- );
2637
- });
2638
-
2639
- it("answers tool approvals via run/input decisions", async () => {
2640
- const fetchMock = installFetch();
2641
- const { aui } = mountThread({
2642
- converter: requestConverter({ id: "req2" }),
2643
- initialState: {
2644
- messages: [],
2645
- toolCall: { id: "tc1", name: "probe_tool", argsText: "{}" },
2646
- inputRequests: [
2647
- {
2648
- type: "tool-approval",
2649
- id: "req2",
2650
- toolCallId: "tc1",
2651
- response: null,
2652
- },
2653
- ],
2654
- } as InputState,
2655
- });
2656
-
2657
- await waitFor(() =>
2658
- expect(aui().thread().getState().messages).toHaveLength(1),
2659
- );
2660
- toolCallPart(aui).respondToToolApproval({
2661
- approved: false,
2662
- reason: "not allowed",
2663
- });
2664
-
2665
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2666
- expect(fetchMock.requests[0]!.body.commands).toEqual([
2667
- {
2668
- type: "run/input",
2669
- requestId: "req2",
2670
- response: { decision: "reject", message: "not allowed" },
2671
- },
2672
- ]);
2673
- });
2674
-
2675
- it("posts frontend tool results as run/input when the host parks a matching request", async () => {
2676
- const fetchMock = installFetch();
2677
- const servers: StreamResponse[] = [];
2678
- fetchMock.setHandler(() => {
2679
- const server = createStreamResponse();
2680
- servers.push(server);
2681
- return server.response;
2682
- });
2683
-
2684
- const { aui } = mountThread({ converter: requestConverter() });
2685
- aui()
2686
- .modelContext()
2687
- .register({
2688
- getModelContext: () => ({
2689
- tools: {
2690
- probe_tool: {
2691
- parameters: { type: "object", properties: {} },
2692
- execute: async () => ({ probed: true }),
2693
- },
2694
- },
2695
- }),
2696
- });
2697
-
2698
- sendCommand(aui, { type: "custom-a" } as never);
2699
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2700
- servers[0]!.emit({
2701
- type: "update-state",
2702
- operations: [
2703
- {
2704
- type: "set",
2705
- path: ["toolCall"],
2706
- value: { id: "tc1", name: "probe_tool", argsText: '{"x":1}' },
2707
- },
2708
- {
2709
- type: "set",
2710
- path: ["inputRequests"],
2711
- value: [
2712
- {
2713
- type: "tool-call",
2714
- id: "req1",
2715
- toolCallId: "tc1",
2716
- response: null,
2717
- },
2718
- ],
2719
- },
2720
- ],
2721
- });
2722
- servers[0]!.done();
2723
-
2724
- await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
2725
- expect(fetchMock.requests[1]!.body.commands).toEqual([
2726
- {
2727
- type: "run/input",
2728
- requestId: "req1",
2729
- response: { output: { probed: true } },
2730
- },
2731
- ]);
2732
- servers[1]!.done();
2733
- });
2734
-
2735
- it("surfaces custom request types through extras.inputRequests", async () => {
2736
- installFetch();
2737
- const { aui } = mountThread({
2738
- converter: requestConverter(),
2739
- initialState: {
2740
- messages: [],
2741
- inputRequests: [
2742
- {
2743
- type: "human-review",
2744
- id: "req9",
2745
- prompt: "check this",
2746
- response: null,
2747
- },
2748
- ],
2749
- } as InputState,
2750
- });
2751
-
2752
- await waitFor(() =>
2753
- expect(
2754
- asAssistantTransportExtras(aui().thread().getState().extras)
2755
- .inputRequests,
2756
- ).toEqual([
2757
- {
2758
- type: "human-review",
2759
- id: "req9",
2760
- prompt: "check this",
2761
- response: null,
2762
- },
2763
- ]),
2764
- );
2765
- });
2766
-
2767
- it("throws when the inputRequests projection appears after the first convert", () => {
2768
- installFetch();
2769
- const withRequests: typeof defaultConverter = (state) => ({
2770
- ...defaultConverter(state),
2771
- inputRequests: [],
2772
- });
2773
-
2774
- const captured: { setConverter?: (c: typeof defaultConverter) => void } =
2775
- {};
2776
- const App: FC = () => {
2777
- const [converter, setConverter] = useState(() => defaultConverter);
2778
- captured.setConverter = (c) => setConverter(() => c);
2779
- const aui = useAui({
2780
- thread: AssistantTransportThread<TestState>({
2781
- initialState: INITIAL_STATE,
2782
- api: "https://example.com/api",
2783
- headers: {},
2784
- converter,
2785
- protocol: "assistant-transport",
2786
- }),
2787
- });
2788
- return <AuiProvider value={aui}>{null}</AuiProvider>;
2789
- };
2790
- const { unmount } = render(<App />);
2791
-
2792
- expect(() => act(() => captured.setConverter!(withRequests))).toThrow(
2793
- /inputRequests projection must be stable/,
2794
- );
2795
- unmount();
2796
- });
2797
- });
2798
-
2799
- describe("runs fold and materialize", () => {
2800
- type RunsTestState = TestState & {
2801
- status?: "ready" | "running";
2802
- runs?: {
2803
- runId: string | null;
2804
- status: string;
2805
- queue: { id: string }[];
2806
- steerQueue: { id: string }[];
2807
- dispatching: {
2808
- trigger: string;
2809
- messages: {
2810
- id: string;
2811
- role: "user";
2812
- parts: { type: "text"; text: string }[];
2813
- }[];
2814
- rollbackTo?: string | null;
2815
- } | null;
2816
- error: null;
2817
- }[];
2818
- };
2819
-
2820
- const runsConverter: AssistantTransportThread.StateConverter<
2821
- RunsTestState
2822
- > = (state) => ({
2823
- messages: state.messages.map(toThreadMessage),
2824
- isRunning: state.status === "running",
2825
- });
2826
-
2827
- const materialize = (draft: RunsTestState): void =>
2828
- runsMaterialize(draft, {
2829
- append: (m) =>
2830
- draft.messages.push({
2831
- id: m.id,
2832
- role: m.role,
2833
- text: m.parts.map((p) => (p.type === "text" ? p.text : "")).join(""),
2834
- }),
2835
- rollback: (to) => {
2836
- if (to === null) {
2837
- draft.messages = [];
2838
- return;
2839
- }
2840
- draft.messages.splice(draft.messages.findIndex((m) => m.id === to) + 1);
2841
- },
2842
- });
2843
-
2844
- const mountRuns = (
2845
- init: RunsTestState = { messages: [], status: "ready", runs: [] },
2846
- ) => {
2847
- const captured: { aui?: ReturnType<typeof useAui> } = {};
2848
- const Capture: FC = () => {
2849
- captured.aui = useAui();
2850
- return null;
2851
- };
2852
- const App: FC = () => {
2853
- const aui = useAui({
2854
- thread: AssistantTransportThread<RunsTestState>({
2855
- initialState: init,
2856
- api: "https://example.com/api",
2857
- headers: {},
2858
- converter: runsConverter,
2859
- runs: true,
2860
- materialize,
2861
- capabilities: { edit: true },
2862
- protocol: "assistant-transport",
2863
- }),
2864
- });
2865
- return (
2866
- <AuiProvider value={aui}>
2867
- <Capture />
2868
- </AuiProvider>
2869
- );
2870
- };
2871
- render(<App />);
2872
- return { aui: () => captured.aui! };
2873
- };
2874
-
2875
- it("projects a pending send through the runs fold and materialize", async () => {
2876
- const fetchMock = installFetch();
2877
- let server!: StreamResponse;
2878
- fetchMock.setHandler(() => {
2879
- server = createStreamResponse();
2880
- return server.response;
2881
- });
2882
-
2883
- const { aui } = mountRuns();
2884
- aui().thread().append("go");
2885
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2886
-
2887
- // The lib fold predicts the dispatch record; materialize renders it. One copy.
2888
- expect(threadTexts(aui)).toEqual(["go"]);
2889
- expect(aui().thread().getState().isRunning).toBe(true);
2890
-
2891
- const sent = fetchMock.requests[0]!.body.commands[0] as {
2892
- message: { id: string };
2893
- };
2894
- server.emit({
2895
- type: "update-state",
2896
- operations: [
2897
- {
2898
- type: "set",
2899
- path: [],
2900
- value: {
2901
- messages: [],
2902
- status: "running",
2903
- runs: [
2904
- {
2905
- runId: "run-1",
2906
- status: "running",
2907
- queue: [],
2908
- steerQueue: [],
2909
- dispatching: {
2910
- trigger: "message-send",
2911
- messages: [
2912
- {
2913
- id: sent.message.id,
2914
- role: "user",
2915
- parts: [{ type: "text", text: "go" }],
2916
- },
2917
- ],
2918
- },
2919
- error: null,
2920
- },
2921
- ],
2922
- },
2923
- },
2924
- ],
2925
- });
2926
-
2927
- // Canonical echo retires the overlay in the same publish: still one copy.
2928
- await waitFor(() => expect(threadTexts(aui)).toEqual(["go"]));
2929
- });
2930
-
2931
- it("rewinds through the materialize fold for a pending edit", async () => {
2932
- const fetchMock = installFetch();
2933
- fetchMock.setHandler(() => createStreamResponse().response);
2934
-
2935
- const { aui } = mountRuns({
2936
- messages: [
2937
- { id: "u1", role: "user", text: "one" },
2938
- { id: "a1", role: "assistant", text: "re one" },
2939
- ],
2940
- status: "ready",
2941
- runs: [],
2942
- });
2943
- sendCommand(aui, {
2944
- type: "run/edit",
2945
- runId: "run-e1",
2946
- message: {
2947
- id: "u1b",
2948
- role: "user",
2949
- parts: [{ type: "text", text: "one'" }],
2950
- },
2951
- sourceId: "u1",
2952
- runAnchorMessageId: null,
2953
- });
2954
-
2955
- await waitFor(() => expect(threadTexts(aui)).toEqual(["one'"]));
2956
- });
2957
-
2958
- it("folds a send into a mount without a top-level status — absent means ready", async () => {
2959
- const fetchMock = installFetch();
2960
- fetchMock.setHandler(() => createStreamResponse().response);
2961
-
2962
- const { aui } = mountRuns({ messages: [], runs: [] });
2963
- aui().thread().append("go");
2964
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2965
-
2966
- expect(threadTexts(aui)).toEqual(["go"]);
2967
- expect(aui().thread().getState().isRunning).toBe(true);
2968
- });
2969
-
2970
- it("creates the runs mount when the canonical state carries none", async () => {
2971
- const fetchMock = installFetch();
2972
- let server!: StreamResponse;
2973
- fetchMock.setHandler(() => {
2974
- server = createStreamResponse();
2975
- return server.response;
2976
- });
2977
-
2978
- const { aui } = mountRuns({ messages: [], runs: [] });
2979
- aui().thread().append("one");
2980
- await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2981
- server.emit({
2982
- type: "update-state",
2983
- operations: [
2984
- {
2985
- type: "set",
2986
- path: [],
2987
- value: { messages: [{ id: "u1", role: "user", text: "one" }] },
2988
- },
2989
- ],
2990
- });
2991
- server.done();
2992
- await waitFor(() =>
2993
- expect(aui().thread().getState().isRunning).toBe(false),
2994
- );
2995
-
2996
- aui().thread().append("two");
2997
- await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
2998
- expect(threadTexts(aui)).toEqual(["one", "two"]);
2999
- expect(aui().thread().getState().isRunning).toBe(true);
3000
- });
3001
- });