@assistant-ui/react-statewire 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1858 @@
1
+ // @vitest-environment jsdom
2
+
3
+ import { render, waitFor } from "@testing-library/react";
4
+ import { StrictMode } 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 { AssistantTransportThread } from "./AssistantTransportThread";
15
+ import {
16
+ useAssistantTransportSendCommand,
17
+ useAssistantTransportState,
18
+ } from "./hooks";
19
+ import type {
20
+ AssistantTransportCommand,
21
+ AssistantTransportConnectionMetadata,
22
+ } from "./types";
23
+ import {
24
+ INITIAL_STATE,
25
+ abortableStream,
26
+ allCommands,
27
+ createStreamResponse,
28
+ defaultConverter,
29
+ emitToolCall,
30
+ installFetch,
31
+ mountThread,
32
+ sendCommand,
33
+ sseEvent,
34
+ threadTexts,
35
+ toolCallConverter,
36
+ } from "./__tests__/testHelpers";
37
+ import type { StreamResponse, TestState } from "./__tests__/testHelpers";
38
+
39
+ afterEach(() => {
40
+ vi.unstubAllGlobals();
41
+ });
42
+
43
+ describe("AssistantTransportThread", () => {
44
+ it("sends appended messages and applies streamed state", async () => {
45
+ const fetchMock = installFetch();
46
+ let server!: StreamResponse;
47
+ fetchMock.setHandler(() => {
48
+ server = createStreamResponse();
49
+ return server.response;
50
+ });
51
+
52
+ const { aui } = mountThread();
53
+ aui().thread().append("hello");
54
+
55
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
56
+ expect(fetchMock.requests[0]!.url).toBe("https://example.com/api");
57
+ expect(fetchMock.requests[0]!.body.commands).toEqual([
58
+ {
59
+ type: "add-message",
60
+ message: { role: "user", parts: [{ type: "text", text: "hello" }] },
61
+ parentId: null,
62
+ sourceId: null,
63
+ },
64
+ ]);
65
+ expect(fetchMock.requests[0]!.body.state).toEqual(INITIAL_STATE);
66
+ expect(fetchMock.requests[0]!.body.threadId).toBeNull();
67
+
68
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["hello"]));
69
+ expect(aui().thread().getState().isRunning).toBe(true);
70
+
71
+ server.emit({
72
+ type: "update-state",
73
+ operations: [
74
+ {
75
+ type: "set",
76
+ path: ["messages"],
77
+ value: [
78
+ { id: "m1", role: "user", text: "hello" },
79
+ { id: "m2", role: "assistant", text: "hi there" },
80
+ ],
81
+ },
82
+ ],
83
+ });
84
+
85
+ await waitFor(() =>
86
+ expect(threadTexts(aui)).toEqual(["hello", "hi there"]),
87
+ );
88
+ server.done();
89
+
90
+ await waitFor(() =>
91
+ expect(aui().thread().getState().isRunning).toBe(false),
92
+ );
93
+ });
94
+
95
+ it("streams append-text deltas into the state", async () => {
96
+ const fetchMock = installFetch();
97
+ let server!: StreamResponse;
98
+ fetchMock.setHandler(() => {
99
+ server = createStreamResponse();
100
+ return server.response;
101
+ });
102
+
103
+ const { aui } = mountThread();
104
+ aui().thread().append("hello");
105
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
106
+
107
+ server.emit({
108
+ type: "update-state",
109
+ operations: [
110
+ {
111
+ type: "set",
112
+ path: ["messages"],
113
+ value: [{ id: "m1", role: "assistant", text: "" }],
114
+ },
115
+ ],
116
+ });
117
+ server.emit({
118
+ type: "update-state",
119
+ operations: [
120
+ { type: "append-text", path: ["messages", "0", "text"], value: "wor" },
121
+ { type: "append-text", path: ["messages", "0", "text"], value: "ld" },
122
+ ],
123
+ });
124
+ server.done();
125
+
126
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["world"]));
127
+ });
128
+
129
+ it("passes pendingCommands, isSending, and stable toolStatuses to the converter", async () => {
130
+ const fetchMock = installFetch();
131
+ let server!: StreamResponse;
132
+ fetchMock.setHandler(() => {
133
+ server = createStreamResponse();
134
+ return server.response;
135
+ });
136
+
137
+ const metas: AssistantTransportConnectionMetadata[] = [];
138
+ const converter: typeof defaultConverter = (state, meta) => {
139
+ metas.push(meta);
140
+ return defaultConverter(state, meta);
141
+ };
142
+
143
+ const { aui } = mountThread({ converter });
144
+ aui().thread().append("hello");
145
+
146
+ await waitFor(() => {
147
+ const meta = metas.at(-1)!;
148
+ expect(meta.isSending).toBe(true);
149
+ expect(meta.pendingCommands).toHaveLength(1);
150
+ expect(meta.pendingCommands[0]).toMatchObject({ type: "add-message" });
151
+ });
152
+
153
+ server.emit({
154
+ type: "update-state",
155
+ operations: [
156
+ {
157
+ type: "set",
158
+ path: ["messages"],
159
+ value: [{ id: "m1", role: "user", text: "hello" }],
160
+ },
161
+ ],
162
+ });
163
+
164
+ await waitFor(() => expect(metas.at(-1)!.pendingCommands).toHaveLength(0));
165
+
166
+ server.done();
167
+ await waitFor(() => expect(metas.at(-1)!.isSending).toBe(false));
168
+
169
+ expect(new Set(metas.map((m) => m.toolStatuses)).size).toBe(1);
170
+ expect(metas[0]!.toolStatuses).toEqual({});
171
+ });
172
+
173
+ it("coalesces two synchronous sends into one request; the empty follow-up run is a no-op", async () => {
174
+ const fetchMock = installFetch();
175
+ const errors: string[] = [];
176
+ const cancels: unknown[] = [];
177
+
178
+ const { aui } = mountThread({
179
+ onError: (error) => {
180
+ errors.push(error.message);
181
+ },
182
+ onCancel: (params) => {
183
+ cancels.push(params.commands);
184
+ },
185
+ });
186
+
187
+ sendCommand(aui, { type: "custom-a" } as never);
188
+ sendCommand(aui, { type: "custom-b" } as never);
189
+
190
+ await waitFor(() =>
191
+ expect(aui().thread().getState().isRunning).toBe(false),
192
+ );
193
+ expect(errors).toEqual([]);
194
+ expect(cancels).toEqual([]);
195
+ expect(fetchMock.requests).toHaveLength(1);
196
+ expect(
197
+ fetchMock.requests[0]!.body.commands.map((c: any) => c.type),
198
+ ).toEqual(["custom-a", "custom-b"]);
199
+ });
200
+
201
+ it("restarts once with commands queued during a run", async () => {
202
+ const fetchMock = installFetch();
203
+ const servers: StreamResponse[] = [];
204
+ fetchMock.setHandler(() => {
205
+ const server = createStreamResponse();
206
+ servers.push(server);
207
+ return server.response;
208
+ });
209
+
210
+ const { aui } = mountThread();
211
+ sendCommand(aui, { type: "custom-a" } as never);
212
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
213
+
214
+ sendCommand(aui, { type: "custom-b" } as never);
215
+ servers[0]!.done();
216
+
217
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
218
+ expect(fetchMock.requests[1]!.body.commands).toEqual([
219
+ { type: "custom-b" },
220
+ ]);
221
+ servers[1]!.done();
222
+ });
223
+
224
+ it("marks commands delivered when a run completes cleanly without state chunks", async () => {
225
+ const fetchMock = installFetch();
226
+ const servers: StreamResponse[] = [];
227
+ fetchMock.setHandler(() => {
228
+ const server = createStreamResponse();
229
+ servers.push(server);
230
+ server.done();
231
+ return server.response;
232
+ });
233
+
234
+ const errors: string[] = [];
235
+ const { aui } = mountThread({
236
+ onError: (error) => {
237
+ errors.push(error.message);
238
+ },
239
+ });
240
+
241
+ sendCommand(aui, {
242
+ type: "add-message",
243
+ message: { role: "user", parts: [{ type: "text", text: "hello" }] },
244
+ parentId: null,
245
+ sourceId: null,
246
+ });
247
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
248
+ await waitFor(() =>
249
+ expect(aui().thread().getState().isRunning).toBe(false),
250
+ );
251
+
252
+ // No update-state chunk arrived, but the run completed cleanly: the
253
+ // command counts as delivered and leaves pending (unlike legacy).
254
+ expect(errors).toEqual([]);
255
+ expect(aui().thread().getState().messages).toEqual([]);
256
+
257
+ sendCommand(aui, { type: "custom-b" } as never);
258
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
259
+ expect(fetchMock.requests[1]!.body.commands).toEqual([
260
+ { type: "custom-b" },
261
+ ]);
262
+ });
263
+
264
+ it("runs onError with in-transit commands, then onCancel with queued commands", async () => {
265
+ const fetchMock = installFetch();
266
+ fetchMock.setHandler(() => new Response("boom", { status: 500 }));
267
+
268
+ const events: string[] = [];
269
+ const { aui } = mountThread({
270
+ onError: (error, { commands }) => {
271
+ events.push(`error:${error.message}:${commands.length}`);
272
+ },
273
+ onCancel: ({ commands, error }) => {
274
+ events.push(`cancel:${commands.length}:${error?.message}`);
275
+ },
276
+ });
277
+
278
+ sendCommand(aui, { type: "custom-a" } as never);
279
+
280
+ await waitFor(() =>
281
+ expect(events).toEqual([
282
+ "error:Status 500: boom:1",
283
+ "cancel:0:Status 500: boom",
284
+ ]),
285
+ );
286
+ await waitFor(() =>
287
+ expect(aui().thread().getState().isRunning).toBe(false),
288
+ );
289
+ });
290
+
291
+ it("supports updateState from onError", async () => {
292
+ const fetchMock = installFetch();
293
+ fetchMock.setHandler(() => new Response("boom", { status: 500 }));
294
+
295
+ const { aui } = mountThread({
296
+ onError: (_error, { updateState }) => {
297
+ updateState((state) => ({
298
+ messages: [
299
+ ...state.messages,
300
+ { id: "err", role: "assistant", text: "request failed" },
301
+ ],
302
+ }));
303
+ },
304
+ });
305
+
306
+ aui().thread().append("hello");
307
+
308
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["request failed"]));
309
+ });
310
+
311
+ it("keeps commands in transit when the first chunk fails to apply — onError receives them", async () => {
312
+ const fetchMock = installFetch();
313
+ const servers: StreamResponse[] = [];
314
+ fetchMock.setHandler(() => {
315
+ const server = createStreamResponse();
316
+ servers.push(server);
317
+ if (servers.length > 1) server.done();
318
+ return server.response;
319
+ });
320
+
321
+ const errored: AssistantTransportCommand[][] = [];
322
+ const { aui } = mountThread({
323
+ onError: (_error, { commands }) => {
324
+ errored.push(commands);
325
+ },
326
+ });
327
+
328
+ sendCommand(aui, { type: "custom-a" } as never);
329
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
330
+
331
+ // The very first chunk is invalid — the legacy accumulator errors the run
332
+ // before any state change surfaces, so markDelivered never fires and
333
+ // onError sees the in-transit command.
334
+ servers[0]!.emit({
335
+ type: "update-state",
336
+ operations: [{ type: "append-text", path: ["messages"], value: "x" }],
337
+ });
338
+ servers[0]!.done();
339
+
340
+ await waitFor(() => expect(errored).toHaveLength(1));
341
+ expect(errored[0]).toEqual([{ type: "custom-a" }]);
342
+ });
343
+
344
+ it("applies update-state chunks atomically — an op error mid-chunk leaves the state untouched", async () => {
345
+ const fetchMock = installFetch();
346
+ const servers: StreamResponse[] = [];
347
+ fetchMock.setHandler(() => {
348
+ const server = createStreamResponse();
349
+ servers.push(server);
350
+ if (servers.length > 1) server.done();
351
+ return server.response;
352
+ });
353
+
354
+ const errors: string[] = [];
355
+ const { aui } = mountThread({
356
+ onError: (error) => {
357
+ errors.push(error.message);
358
+ },
359
+ });
360
+
361
+ sendCommand(aui, { type: "custom-a" } as never);
362
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
363
+
364
+ // Second op is invalid (append-text onto a non-string) — the legacy
365
+ // accumulator errors the run without surfacing the chunk at all.
366
+ servers[0]!.emit({
367
+ type: "update-state",
368
+ operations: [
369
+ {
370
+ type: "set",
371
+ path: ["messages"],
372
+ value: [{ id: "m1", role: "assistant", text: "partial" }],
373
+ },
374
+ { type: "append-text", path: ["messages"], value: "x" },
375
+ ],
376
+ });
377
+ servers[0]!.done();
378
+
379
+ await waitFor(() => expect(errors).toHaveLength(1));
380
+
381
+ // The partially-applied chunk must not leak into the next request body.
382
+ sendCommand(aui, { type: "custom-b" } as never);
383
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
384
+ expect(fetchMock.requests[1]!.body.state).toEqual(INITIAL_STATE);
385
+ expect(threadTexts(aui)).toEqual([]);
386
+ });
387
+
388
+ it("cancels a running request and reports all pending commands", async () => {
389
+ const fetchMock = installFetch();
390
+ fetchMock.setHandler(({ init }) => abortableStream(init).response);
391
+
392
+ const cancelled: AssistantTransportCommand[][] = [];
393
+ const errors: string[] = [];
394
+ const { aui } = mountThread({
395
+ onCancel: ({ commands, error }) => {
396
+ cancelled.push(commands);
397
+ if (error) errors.push(error.message);
398
+ },
399
+ });
400
+
401
+ sendCommand(aui, { type: "custom-a" } as never);
402
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
403
+
404
+ aui().thread().cancelRun();
405
+
406
+ await waitFor(() => expect(cancelled).toHaveLength(1));
407
+ expect(cancelled[0]!.map((c: any) => c.type)).toEqual(["custom-a"]);
408
+ expect(errors).toEqual([]);
409
+ await waitFor(() =>
410
+ expect(aui().thread().getState().isRunning).toBe(false),
411
+ );
412
+ });
413
+
414
+ it("errors when the stream ends without the [DONE] marker", async () => {
415
+ const fetchMock = installFetch();
416
+ let server!: StreamResponse;
417
+ fetchMock.setHandler(() => {
418
+ server = createStreamResponse();
419
+ return server.response;
420
+ });
421
+
422
+ const errors: string[] = [];
423
+ const { aui } = mountThread({
424
+ protocol: "assistant-transport",
425
+ onError: (error) => {
426
+ errors.push(error.message);
427
+ },
428
+ });
429
+
430
+ sendCommand(aui, { type: "custom-a" } as never);
431
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
432
+ server.close();
433
+
434
+ await waitFor(() =>
435
+ expect(errors).toEqual([
436
+ "Stream ended abruptly without receiving [DONE] marker",
437
+ ]),
438
+ );
439
+ });
440
+
441
+ it("surfaces error chunks after the stream completes", async () => {
442
+ const fetchMock = installFetch();
443
+ fetchMock.setHandler(() => {
444
+ const server = createStreamResponse();
445
+ server.emit({ type: "error", error: "kaboom" });
446
+ server.done();
447
+ return server.response;
448
+ });
449
+
450
+ const errors: string[] = [];
451
+ const { aui } = mountThread({
452
+ onError: (error) => {
453
+ errors.push(error.message);
454
+ },
455
+ });
456
+
457
+ sendCommand(aui, { type: "custom-a" } as never);
458
+ await waitFor(() => expect(errors).toEqual(["kaboom"]));
459
+ });
460
+
461
+ it("decodes update-state parts from the default data-stream protocol", async () => {
462
+ const fetchMock = installFetch();
463
+ fetchMock.setHandler(() => {
464
+ const server = createStreamResponse();
465
+ server.push(
466
+ `aui-state:${JSON.stringify([
467
+ {
468
+ type: "set",
469
+ path: ["messages"],
470
+ value: [{ id: "m1", role: "assistant", text: "from data stream" }],
471
+ },
472
+ ])}\n`,
473
+ );
474
+ server.close();
475
+ return server.response;
476
+ });
477
+
478
+ const { aui } = mountThread({ protocol: undefined });
479
+ sendCommand(aui, { type: "custom-a" } as never);
480
+
481
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["from data stream"]));
482
+ });
483
+
484
+ it("skips blank data-stream lines emitted as framing on reconnect", async () => {
485
+ const fetchMock = installFetch();
486
+ const errors: string[] = [];
487
+ fetchMock.setHandler(() => {
488
+ const server = createStreamResponse();
489
+ server.push("\n");
490
+ server.push(
491
+ `aui-state:${JSON.stringify([
492
+ {
493
+ type: "set",
494
+ path: ["messages"],
495
+ value: [{ id: "m1", role: "assistant", text: "hi" }],
496
+ },
497
+ ])}\n`,
498
+ );
499
+ server.push("\n \n");
500
+ server.push(
501
+ `aui-state:${JSON.stringify([
502
+ { type: "append-text", path: ["messages", "0", "text"], value: "!" },
503
+ ])}\n`,
504
+ );
505
+ server.close();
506
+ return server.response;
507
+ });
508
+
509
+ const { aui } = mountThread({
510
+ protocol: undefined,
511
+ onError: (error) => {
512
+ errors.push(error.message);
513
+ },
514
+ });
515
+ sendCommand(aui, { type: "custom-a" } as never);
516
+
517
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["hi!"]));
518
+ expect(errors).toEqual([]);
519
+ });
520
+
521
+ it("skips messages that produce zero parts", async () => {
522
+ const fetchMock = installFetch();
523
+ const { aui } = mountThread();
524
+
525
+ aui().thread().append({ role: "user", content: [] });
526
+
527
+ await new Promise((resolve) => setTimeout(resolve, 20));
528
+ expect(fetchMock.requests).toHaveLength(0);
529
+ expect(aui().thread().getState().messages).toHaveLength(0);
530
+ });
531
+
532
+ it("records parentId from appends that produce zero parts", async () => {
533
+ const fetchMock = installFetch();
534
+ const { aui } = mountThread();
535
+
536
+ aui().thread().append({ role: "user", content: [], parentId: "p1" });
537
+
538
+ await new Promise((resolve) => setTimeout(resolve, 20));
539
+ expect(fetchMock.requests).toHaveLength(0);
540
+
541
+ sendCommand(aui, { type: "custom-a" } as never);
542
+
543
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
544
+ expect(fetchMock.requests[0]!.body.parentId).toBe("p1");
545
+ });
546
+
547
+ it("resumes runs against resumeApi with empty commands", async () => {
548
+ const fetchMock = installFetch();
549
+ fetchMock.setHandler(() => {
550
+ const server = createStreamResponse({
551
+ headers: { "X-Stream-Status": "active" },
552
+ });
553
+ server.done();
554
+ return server.response;
555
+ });
556
+
557
+ const streamStatuses: (string | null)[] = [];
558
+ const { aui } = mountThread({
559
+ resumeApi: "https://example.com/resume",
560
+ onResponse: (response) => {
561
+ streamStatuses.push(response.headers.get("X-Stream-Status"));
562
+ },
563
+ });
564
+
565
+ aui().thread().resumeRun({ parentId: null });
566
+
567
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
568
+ expect(fetchMock.requests[0]!.url).toBe("https://example.com/resume");
569
+ expect(fetchMock.requests[0]!.body.commands).toEqual([]);
570
+ await waitFor(() => expect(streamStatuses).toEqual(["active"]));
571
+ await waitFor(() =>
572
+ expect(aui().thread().getState().isRunning).toBe(false),
573
+ );
574
+ });
575
+
576
+ it("flushes commands coalesced into a resume run in a follow-up run", async () => {
577
+ const fetchMock = installFetch();
578
+ const servers: StreamResponse[] = [];
579
+ fetchMock.setHandler(() => {
580
+ const server = createStreamResponse();
581
+ servers.push(server);
582
+ return server.response;
583
+ });
584
+
585
+ const { aui } = mountThread({
586
+ resumeApi: "https://example.com/resume",
587
+ });
588
+
589
+ sendCommand(aui, { type: "custom-a" } as never);
590
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
591
+
592
+ // Both land while the first run is active and coalesce into one follow-up.
593
+ sendCommand(aui, { type: "custom-b" } as never);
594
+ aui().thread().resumeRun({ parentId: null });
595
+
596
+ servers[0]!.done();
597
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
598
+ expect(fetchMock.requests[1]!.url).toBe("https://example.com/resume");
599
+ expect(fetchMock.requests[1]!.body.commands).toEqual([]);
600
+ servers[1]!.done();
601
+
602
+ // custom-b must not starve in the queue.
603
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(3));
604
+ expect(fetchMock.requests[2]!.url).toBe("https://example.com/api");
605
+ expect(fetchMock.requests[2]!.body.commands).toEqual([
606
+ { type: "custom-b" },
607
+ ]);
608
+ servers[2]!.done();
609
+ });
610
+
611
+ it("throws when resuming without resumeApi", () => {
612
+ installFetch();
613
+ const { aui } = mountThread();
614
+
615
+ expect(() => aui().thread().resumeRun({ parentId: null })).toThrow(
616
+ "Must pass resumeApi to options to resume runs",
617
+ );
618
+ });
619
+
620
+ it("cancel clears a pending resume flag", async () => {
621
+ const fetchMock = installFetch();
622
+ const servers: StreamResponse[] = [];
623
+ fetchMock.setHandler(({ init }) => {
624
+ const server = abortableStream(init);
625
+ servers.push(server);
626
+ return server.response;
627
+ });
628
+
629
+ const { aui } = mountThread({
630
+ resumeApi: "https://example.com/resume",
631
+ });
632
+
633
+ sendCommand(aui, { type: "custom-a" } as never);
634
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
635
+
636
+ // Request a resume while the run is in flight, then cancel everything.
637
+ aui().thread().resumeRun({ parentId: null });
638
+ aui().thread().cancelRun();
639
+ await waitFor(() =>
640
+ expect(aui().thread().getState().isRunning).toBe(false),
641
+ );
642
+
643
+ sendCommand(aui, { type: "custom-b" } as never);
644
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
645
+
646
+ expect(fetchMock.requests[1]!.url).toBe("https://example.com/api");
647
+ expect(fetchMock.requests[1]!.body.commands).toEqual([
648
+ { type: "custom-b" },
649
+ ]);
650
+ servers[1]!.done();
651
+ });
652
+
653
+ it("gates isLoading around the replay boundary", async () => {
654
+ const fetchMock = installFetch();
655
+ const replayEvent = sseEvent({
656
+ type: "update-state",
657
+ operations: [
658
+ {
659
+ type: "set",
660
+ path: ["messages"],
661
+ value: [{ id: "m1", role: "assistant", text: "replayed" }],
662
+ },
663
+ ],
664
+ });
665
+
666
+ let server!: StreamResponse;
667
+ fetchMock.setHandler(() => {
668
+ server = createStreamResponse({
669
+ headers: {
670
+ "Aui-Replay-Content-Length": String(
671
+ new TextEncoder().encode(replayEvent).byteLength,
672
+ ),
673
+ },
674
+ });
675
+ return server.response;
676
+ });
677
+
678
+ const { aui } = mountThread({
679
+ resumeApi: "https://example.com/resume",
680
+ });
681
+
682
+ aui().thread().resumeRun({ parentId: null });
683
+
684
+ await waitFor(() => expect(aui().thread().getState().isLoading).toBe(true));
685
+
686
+ server.push(replayEvent);
687
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["replayed"]));
688
+ await waitFor(() =>
689
+ expect(aui().thread().getState().isLoading).toBe(false),
690
+ );
691
+
692
+ server.emit({
693
+ type: "update-state",
694
+ operations: [
695
+ { type: "append-text", path: ["messages", "0", "text"], value: "!" },
696
+ ],
697
+ });
698
+ server.done();
699
+
700
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["replayed!"]));
701
+ });
702
+
703
+ it("renders the replay boundary before replayed content becomes visible", async () => {
704
+ const fetchMock = installFetch();
705
+ const replayEvent = sseEvent({
706
+ type: "update-state",
707
+ operations: [
708
+ {
709
+ type: "set",
710
+ path: ["messages"],
711
+ value: [{ id: "m1", role: "assistant", text: "replayed" }],
712
+ },
713
+ ],
714
+ });
715
+
716
+ fetchMock.setHandler(() => {
717
+ const server = createStreamResponse({
718
+ headers: {
719
+ "Aui-Replay-Content-Length": String(
720
+ new TextEncoder().encode(replayEvent).byteLength,
721
+ ),
722
+ },
723
+ });
724
+ // All bytes are available immediately — the boundary gating alone must
725
+ // guarantee the loading state renders before replayed content.
726
+ server.push(replayEvent);
727
+ server.emit({
728
+ type: "update-state",
729
+ operations: [
730
+ { type: "append-text", path: ["messages", "0", "text"], value: "!" },
731
+ ],
732
+ });
733
+ server.done();
734
+ return server.response;
735
+ });
736
+
737
+ const records: { isLoading: boolean; texts: string[] }[] = [];
738
+ const { aui } = mountThread({
739
+ resumeApi: "https://example.com/resume",
740
+ });
741
+ const record = () => {
742
+ const state = aui().thread().getState();
743
+ records.push({
744
+ isLoading: state.isLoading,
745
+ texts: state.messages.map((m) =>
746
+ m.parts.flatMap((p) => (p.type === "text" ? [p.text] : [])).join(""),
747
+ ),
748
+ });
749
+ };
750
+ const unsubscribe = aui().subscribe(record);
751
+
752
+ aui().thread().resumeRun({ parentId: null });
753
+
754
+ await waitFor(() =>
755
+ expect(records.at(-1)).toEqual({
756
+ isLoading: false,
757
+ texts: ["replayed!"],
758
+ }),
759
+ );
760
+ unsubscribe();
761
+
762
+ const firstReplayed = records.findIndex((r) =>
763
+ r.texts.join("").includes("replayed"),
764
+ );
765
+ const firstLoading = records.findIndex((r) => r.isLoading);
766
+ expect(firstLoading).toBeGreaterThanOrEqual(0);
767
+ expect(firstLoading).toBeLessThan(firstReplayed);
768
+ // live bytes only render after the boundary flip back to not-loading
769
+ const firstLive = records.findIndex(
770
+ (r) => r.texts.join("") === "replayed!",
771
+ );
772
+ expect(records[firstLive]!.isLoading).toBe(false);
773
+ });
774
+
775
+ it("handles a replay boundary landing mid-multibyte-char and mid-SSE-event", async () => {
776
+ const fetchMock = installFetch();
777
+ const replayEvent = sseEvent({
778
+ type: "update-state",
779
+ operations: [
780
+ {
781
+ type: "set",
782
+ path: ["messages"],
783
+ value: [{ id: "m1", role: "assistant", text: "héllo ✓ wörld" }],
784
+ },
785
+ ],
786
+ });
787
+ const replayBytes = new TextEncoder().encode(replayEvent);
788
+ // Boundary inside the multibyte "✓" (3 bytes) which itself sits mid-event.
789
+ const checkmarkOffset = replayEvent.indexOf("✓");
790
+ const boundary =
791
+ new TextEncoder().encode(replayEvent.slice(0, checkmarkOffset))
792
+ .byteLength + 1;
793
+ expect(boundary).toBeLessThan(replayBytes.byteLength);
794
+
795
+ let server!: StreamResponse;
796
+ fetchMock.setHandler(() => {
797
+ server = createStreamResponse({
798
+ headers: { "Aui-Replay-Content-Length": String(boundary) },
799
+ });
800
+ return server.response;
801
+ });
802
+
803
+ const { aui } = mountThread({
804
+ resumeApi: "https://example.com/resume",
805
+ });
806
+ aui().thread().resumeRun({ parentId: null });
807
+ await waitFor(() => expect(aui().thread().getState().isLoading).toBe(true));
808
+
809
+ // Deliver the replay bytes in a chunk that straddles the boundary.
810
+ server.pushBytes(replayBytes);
811
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["héllo ✓ wörld"]));
812
+ await waitFor(() =>
813
+ expect(aui().thread().getState().isLoading).toBe(false),
814
+ );
815
+
816
+ server.emit({
817
+ type: "update-state",
818
+ operations: [
819
+ { type: "append-text", path: ["messages", "0", "text"], value: " ✔" },
820
+ ],
821
+ });
822
+ server.done();
823
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["héllo ✓ wörld ✔"]));
824
+ });
825
+
826
+ it("treats a zero-length replay header as no replay", async () => {
827
+ const fetchMock = installFetch();
828
+ let server!: StreamResponse;
829
+ const loadingStates: boolean[] = [];
830
+ fetchMock.setHandler(() => {
831
+ server = createStreamResponse({
832
+ headers: { "Aui-Replay-Content-Length": "0" },
833
+ });
834
+ return server.response;
835
+ });
836
+
837
+ const { aui } = mountThread({
838
+ resumeApi: "https://example.com/resume",
839
+ });
840
+ aui().thread().resumeRun({ parentId: null });
841
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
842
+ loadingStates.push(aui().thread().getState().isLoading);
843
+
844
+ server.emit({
845
+ type: "update-state",
846
+ operations: [
847
+ {
848
+ type: "set",
849
+ path: ["messages"],
850
+ value: [{ id: "m1", role: "assistant", text: "live" }],
851
+ },
852
+ ],
853
+ });
854
+ server.done();
855
+
856
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["live"]));
857
+ loadingStates.push(aui().thread().getState().isLoading);
858
+ expect(loadingStates).toEqual([false, false]);
859
+ });
860
+
861
+ it("reads body object getters at request time", async () => {
862
+ const fetchMock = installFetch();
863
+ let dynamic = "before";
864
+ const { aui } = mountThread({
865
+ body: {
866
+ get dynamic() {
867
+ return dynamic;
868
+ },
869
+ },
870
+ });
871
+
872
+ dynamic = "after";
873
+ sendCommand(aui, { type: "custom-a" } as never);
874
+
875
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
876
+ expect(fetchMock.requests[0]!.body.dynamic).toBe("after");
877
+ });
878
+
879
+ it("supports async body functions", async () => {
880
+ const fetchMock = installFetch();
881
+ const { aui } = mountThread({
882
+ body: async () => ({ sessionId: "s1" }),
883
+ });
884
+
885
+ sendCommand(aui, { type: "custom-a" } as never);
886
+
887
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
888
+ expect(fetchMock.requests[0]!.body.sessionId).toBe("s1");
889
+ });
890
+
891
+ it("supports async header functions", async () => {
892
+ const fetchMock = installFetch();
893
+ const { aui } = mountThread({
894
+ headers: async () => ({ authorization: "Bearer token" }),
895
+ });
896
+
897
+ sendCommand(aui, { type: "custom-a" } as never);
898
+
899
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
900
+ const headers = new Headers(fetchMock.requests[0]!.init.headers);
901
+ expect(headers.get("authorization")).toBe("Bearer token");
902
+ expect(headers.get("content-type")).toBe("application/json");
903
+ });
904
+
905
+ it("applies prepareSendCommandsRequest to the request body", async () => {
906
+ const fetchMock = installFetch();
907
+ const { aui } = mountThread({
908
+ prepareSendCommandsRequest: async (body) => ({
909
+ wrapped: { commands: body.commands },
910
+ }),
911
+ });
912
+
913
+ sendCommand(aui, { type: "custom-a" } as never);
914
+
915
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
916
+ expect(fetchMock.requests[0]!.body).toEqual({
917
+ wrapped: { commands: [{ type: "custom-a" }] },
918
+ });
919
+ });
920
+
921
+ it("passes custom user commands through verbatim", async () => {
922
+ const fetchMock = installFetch();
923
+ const { aui } = mountThread();
924
+
925
+ sendCommand(aui, {
926
+ type: "set-model",
927
+ modelId: "gpt-6",
928
+ nested: { a: [1, 2] },
929
+ } as never);
930
+
931
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
932
+ expect(fetchMock.requests[0]!.body.commands).toEqual([
933
+ { type: "set-model", modelId: "gpt-6", nested: { a: [1, 2] } },
934
+ ]);
935
+ });
936
+
937
+ it("sends model context (system, tools, callSettings, config) in the request body", async () => {
938
+ const fetchMock = installFetch();
939
+ const { aui } = mountThread();
940
+
941
+ aui()
942
+ .modelContext()
943
+ .register({
944
+ getModelContext: () => ({
945
+ system: "be helpful",
946
+ tools: {
947
+ probe_tool: {
948
+ parameters: { type: "object", properties: {} },
949
+ },
950
+ },
951
+ callSettings: { temperature: 0.5 },
952
+ config: { modelName: "test-model" },
953
+ }),
954
+ });
955
+
956
+ sendCommand(aui, { type: "custom-a" } as never);
957
+
958
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
959
+ const body = fetchMock.requests[0]!.body;
960
+ expect(body.system).toBe("be helpful");
961
+ expect(body.tools).toEqual({
962
+ probe_tool: { parameters: { type: "object", properties: {} } },
963
+ });
964
+ expect(body.callSettings).toEqual({ temperature: 0.5 });
965
+ expect(body.config).toEqual({ modelName: "test-model" });
966
+ // deprecated top-level spread, matching the legacy runtime
967
+ expect(body.temperature).toBe(0.5);
968
+ expect(body.modelName).toBe("test-model");
969
+ });
970
+
971
+ it("imports external state", async () => {
972
+ installFetch();
973
+ const { aui } = mountThread();
974
+
975
+ aui().thread().importExternalState!({
976
+ messages: [{ id: "m1", role: "assistant", text: "imported" }],
977
+ });
978
+
979
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["imported"]));
980
+ });
981
+
982
+ it("importExternalState preserves queued commands and sends the imported state", async () => {
983
+ const fetchMock = installFetch();
984
+ const servers: StreamResponse[] = [];
985
+ fetchMock.setHandler(() => {
986
+ const server = createStreamResponse();
987
+ servers.push(server);
988
+ if (servers.length > 1) server.done();
989
+ return server.response;
990
+ });
991
+
992
+ const { aui } = mountThread();
993
+
994
+ sendCommand(aui, { type: "custom-a" } as never);
995
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
996
+
997
+ // custom-b queues while the run streams; the import must not clobber it.
998
+ sendCommand(aui, { type: "custom-b" } as never);
999
+ const imported: TestState = {
1000
+ messages: [{ id: "m1", role: "assistant", text: "imported" }],
1001
+ };
1002
+ aui().thread().importExternalState!(imported);
1003
+
1004
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["imported"]));
1005
+
1006
+ servers[0]!.done();
1007
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
1008
+ expect(fetchMock.requests[1]!.body.commands).toEqual([
1009
+ { type: "custom-b" },
1010
+ ]);
1011
+ expect(fetchMock.requests[1]!.body.state).toEqual(imported);
1012
+ });
1013
+
1014
+ it("importExternalState aborts executing tools without leaking their cancellation results", async () => {
1015
+ const fetchMock = installFetch();
1016
+ const servers: StreamResponse[] = [];
1017
+ fetchMock.setHandler(() => {
1018
+ const server = createStreamResponse();
1019
+ servers.push(server);
1020
+ if (servers.length > 1) server.done();
1021
+ return server.response;
1022
+ });
1023
+
1024
+ const metas: AssistantTransportConnectionMetadata[] = [];
1025
+ const { aui } = mountThread({ converter: toolCallConverter(metas) });
1026
+ aui()
1027
+ .modelContext()
1028
+ .register({
1029
+ getModelContext: () => ({
1030
+ tools: {
1031
+ probe_tool: {
1032
+ parameters: { type: "object", properties: {} },
1033
+ execute: () => new Promise(() => {}),
1034
+ },
1035
+ },
1036
+ }),
1037
+ });
1038
+
1039
+ sendCommand(aui, { type: "custom-a" } as never);
1040
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1041
+ emitToolCall(servers[0]!);
1042
+
1043
+ await waitFor(() =>
1044
+ expect(metas.at(-1)!.toolStatuses).toEqual({
1045
+ tc1: { type: "executing" },
1046
+ }),
1047
+ );
1048
+
1049
+ // The imported state no longer contains the tool call.
1050
+ aui().thread().importExternalState!({
1051
+ messages: [{ id: "m1", role: "assistant", text: "restored" }],
1052
+ });
1053
+
1054
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["restored"]));
1055
+ await waitFor(() => expect(metas.at(-1)!.toolStatuses).toEqual({}));
1056
+ await waitFor(() =>
1057
+ expect(aui().thread().getState().isRunning).toBe(false),
1058
+ );
1059
+
1060
+ // Give any stray add-tool-result dispatch a chance to fire.
1061
+ await new Promise((resolve) => setTimeout(resolve, 20));
1062
+ expect(
1063
+ allCommands(fetchMock.requests).filter(
1064
+ (c) => c.type === "add-tool-result",
1065
+ ),
1066
+ ).toEqual([]);
1067
+ });
1068
+
1069
+ it("enables edit and attachments capabilities from options", async () => {
1070
+ installFetch();
1071
+ const attachmentAdapter = {
1072
+ accept: "image/*",
1073
+ add: async () => ({}) as never,
1074
+ remove: async () => {},
1075
+ send: async () => ({}) as never,
1076
+ };
1077
+ const { aui } = mountThread({
1078
+ capabilities: { edit: true },
1079
+ adapters: { attachments: attachmentAdapter },
1080
+ });
1081
+
1082
+ const capabilities = aui().thread().getState().capabilities;
1083
+ expect(capabilities.edit).toBe(true);
1084
+ expect(capabilities.attachments).toBe(true);
1085
+ expect(aui().thread().composer().getState().attachmentAccept).toBe(
1086
+ "image/*",
1087
+ );
1088
+ });
1089
+
1090
+ it("folds completed attachments into the add-message command (CompositeAttachmentAdapter)", async () => {
1091
+ const fetchMock = installFetch();
1092
+ const { aui } = mountThread({
1093
+ adapters: {
1094
+ attachments: new CompositeAttachmentAdapter([
1095
+ new SimpleTextAttachmentAdapter(),
1096
+ ]),
1097
+ },
1098
+ });
1099
+
1100
+ const file = new File(["attached body"], "notes.txt", {
1101
+ type: "text/plain",
1102
+ });
1103
+ await aui().thread().composer().addAttachment(file);
1104
+ aui().thread().composer().setText("see file");
1105
+ await waitFor(() => {
1106
+ const composer = aui().thread().getState().composer;
1107
+ expect(composer.text).toBe("see file");
1108
+ expect(composer.attachments).toHaveLength(1);
1109
+ });
1110
+ aui().thread().composer().send();
1111
+
1112
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1113
+ const command = fetchMock.requests[0]!.body.commands[0];
1114
+ expect(command.type).toBe("add-message");
1115
+ const texts = command.message.parts.map((p: any) => p.text);
1116
+ expect(texts[0]).toBe("see file");
1117
+ expect(texts[1]).toContain("attached body");
1118
+ expect(texts[1]).toContain("notes.txt");
1119
+ });
1120
+
1121
+ it("edits send the edited message's parent as parentId and itself as sourceId", async () => {
1122
+ const fetchMock = installFetch();
1123
+ const { aui } = mountThread({ capabilities: { edit: true } });
1124
+
1125
+ aui().thread().importExternalState!({
1126
+ messages: [
1127
+ { id: "u1", role: "user", text: "one" },
1128
+ { id: "a1", role: "assistant", text: "two" },
1129
+ { id: "u2", role: "user", text: "three" },
1130
+ ],
1131
+ });
1132
+ await waitFor(() =>
1133
+ expect(threadTexts(aui)).toEqual(["one", "two", "three"]),
1134
+ );
1135
+
1136
+ const composer = aui().thread().message({ id: "u2" }).composer();
1137
+ composer.beginEdit();
1138
+ await waitFor(() => expect(composer.getState().isEditing).toBe(true));
1139
+ composer.setText("edited");
1140
+ await waitFor(() => expect(composer.getState().text).toBe("edited"));
1141
+ composer.send();
1142
+
1143
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1144
+ expect(fetchMock.requests[0]!.body.commands).toEqual([
1145
+ {
1146
+ type: "add-message",
1147
+ message: { role: "user", parts: [{ type: "text", text: "edited" }] },
1148
+ parentId: "a1",
1149
+ sourceId: "u2",
1150
+ },
1151
+ ]);
1152
+ expect(fetchMock.requests[0]!.body.parentId).toBe("a1");
1153
+ });
1154
+
1155
+ it("composer sends carry the last message's id as parentId; the run consumes it", async () => {
1156
+ const fetchMock = installFetch();
1157
+ const { aui } = mountThread();
1158
+
1159
+ aui().thread().importExternalState!({
1160
+ messages: [
1161
+ { id: "u1", role: "user", text: "hi" },
1162
+ { id: "a1", role: "assistant", text: "yo" },
1163
+ ],
1164
+ } satisfies TestState);
1165
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["hi", "yo"]));
1166
+
1167
+ aui().thread().composer().setText("again");
1168
+ await waitFor(() =>
1169
+ expect(aui().thread().getState().composer.text).toBe("again"),
1170
+ );
1171
+ aui().thread().composer().send();
1172
+
1173
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1174
+ const body = fetchMock.requests[0]!.body;
1175
+ expect(body.parentId).toBe("a1");
1176
+ expect(body.commands).toEqual([
1177
+ {
1178
+ type: "add-message",
1179
+ message: { role: "user", parts: [{ type: "text", text: "again" }] },
1180
+ parentId: "a1",
1181
+ sourceId: null,
1182
+ },
1183
+ ]);
1184
+
1185
+ await waitFor(() =>
1186
+ expect(aui().thread().getState().isRunning).toBe(false),
1187
+ );
1188
+ sendCommand(aui, { type: "custom-a" } as never);
1189
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
1190
+ expect("parentId" in fetchMock.requests[1]!.body).toBe(false);
1191
+ });
1192
+
1193
+ it("a mid-run append's parentId reaches the follow-up flush", async () => {
1194
+ const fetchMock = installFetch();
1195
+ const servers: StreamResponse[] = [];
1196
+ fetchMock.setHandler(() => {
1197
+ const server = createStreamResponse();
1198
+ servers.push(server);
1199
+ return server.response;
1200
+ });
1201
+
1202
+ const { aui } = mountThread();
1203
+ aui().thread().importExternalState!({
1204
+ messages: [
1205
+ { id: "u1", role: "user", text: "hi" },
1206
+ { id: "a1", role: "assistant", text: "yo" },
1207
+ ],
1208
+ } satisfies TestState);
1209
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["hi", "yo"]));
1210
+
1211
+ aui().thread().append("first");
1212
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1213
+ expect(fetchMock.requests[0]!.body.parentId).toBe("a1");
1214
+
1215
+ servers[0]!.emit({
1216
+ type: "update-state",
1217
+ operations: [
1218
+ {
1219
+ type: "set",
1220
+ path: ["messages"],
1221
+ value: [
1222
+ { id: "u1", role: "user", text: "hi" },
1223
+ { id: "a1", role: "assistant", text: "yo" },
1224
+ { id: "u2", role: "user", text: "first" },
1225
+ { id: "a2", role: "assistant", text: "sure" },
1226
+ ],
1227
+ },
1228
+ ],
1229
+ });
1230
+ await waitFor(() => expect(threadTexts(aui)).toHaveLength(4));
1231
+
1232
+ aui().thread().append("second");
1233
+ servers[0]!.done();
1234
+
1235
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
1236
+ expect(fetchMock.requests[1]!.body.parentId).toBe("a2");
1237
+ servers[1]!.done();
1238
+ });
1239
+
1240
+ it("executes frontend tools and posts add-tool-result in a follow-up run", async () => {
1241
+ const fetchMock = installFetch();
1242
+ const servers: StreamResponse[] = [];
1243
+ fetchMock.setHandler(() => {
1244
+ const server = createStreamResponse();
1245
+ servers.push(server);
1246
+ return server.response;
1247
+ });
1248
+
1249
+ let resolveExecute!: (value: unknown) => void;
1250
+ const executeGate = new Promise((resolve) => {
1251
+ resolveExecute = resolve;
1252
+ });
1253
+
1254
+ const metas: AssistantTransportConnectionMetadata[] = [];
1255
+ const { aui } = mountThread({ converter: toolCallConverter(metas) });
1256
+ aui()
1257
+ .modelContext()
1258
+ .register({
1259
+ getModelContext: () => ({
1260
+ tools: {
1261
+ probe_tool: {
1262
+ parameters: { type: "object", properties: {} },
1263
+ execute: async () => {
1264
+ await executeGate;
1265
+ return { probed: true };
1266
+ },
1267
+ },
1268
+ },
1269
+ }),
1270
+ });
1271
+
1272
+ sendCommand(aui, { type: "custom-a" } as never);
1273
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1274
+ emitToolCall(servers[0]!);
1275
+
1276
+ await waitFor(() =>
1277
+ expect(metas.at(-1)!.toolStatuses).toEqual({
1278
+ tc1: { type: "executing" },
1279
+ }),
1280
+ );
1281
+
1282
+ resolveExecute(undefined);
1283
+
1284
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
1285
+ expect(fetchMock.requests[1]!.body.commands).toEqual([
1286
+ {
1287
+ type: "add-tool-result",
1288
+ toolCallId: "tc1",
1289
+ toolName: "probe_tool",
1290
+ result: { probed: true },
1291
+ isError: false,
1292
+ },
1293
+ ]);
1294
+ servers[1]!.done();
1295
+
1296
+ await waitFor(() => expect(metas.at(-1)!.toolStatuses).toEqual({}));
1297
+ });
1298
+
1299
+ it("resumes human-input interrupts through resumeToolCall", async () => {
1300
+ const fetchMock = installFetch();
1301
+ const servers: StreamResponse[] = [];
1302
+ fetchMock.setHandler(() => {
1303
+ const server = createStreamResponse();
1304
+ servers.push(server);
1305
+ return server.response;
1306
+ });
1307
+
1308
+ const metas: AssistantTransportConnectionMetadata[] = [];
1309
+ const { aui } = mountThread({ converter: toolCallConverter(metas) });
1310
+ aui()
1311
+ .modelContext()
1312
+ .register({
1313
+ getModelContext: () => ({
1314
+ tools: {
1315
+ probe_tool: {
1316
+ parameters: { type: "object", properties: {} },
1317
+ execute: async (_args: unknown, context: any) => {
1318
+ await Promise.resolve();
1319
+ return { answer: await context.human({ q: "proceed?" }) };
1320
+ },
1321
+ },
1322
+ },
1323
+ }),
1324
+ });
1325
+
1326
+ sendCommand(aui, { type: "custom-a" } as never);
1327
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1328
+ emitToolCall(servers[0]!);
1329
+
1330
+ await waitFor(() =>
1331
+ expect(metas.at(-1)!.toolStatuses).toEqual({
1332
+ tc1: {
1333
+ type: "interrupt",
1334
+ payload: { type: "human", payload: { q: "proceed?" } },
1335
+ },
1336
+ }),
1337
+ );
1338
+
1339
+ aui()
1340
+ .thread()
1341
+ .message({ id: "a-tool" })
1342
+ .part({ toolCallId: "tc1" })
1343
+ .resumeToolCall("yes");
1344
+
1345
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
1346
+ expect(fetchMock.requests[1]!.body.commands).toEqual([
1347
+ {
1348
+ type: "add-tool-result",
1349
+ toolCallId: "tc1",
1350
+ toolName: "probe_tool",
1351
+ result: { answer: "yes" },
1352
+ isError: false,
1353
+ },
1354
+ ]);
1355
+ servers[1]!.done();
1356
+ await waitFor(() => expect(metas.at(-1)!.toolStatuses).toEqual({}));
1357
+ });
1358
+
1359
+ it("cancelRun aborts in-flight tool executions", async () => {
1360
+ const fetchMock = installFetch();
1361
+ const servers: StreamResponse[] = [];
1362
+ fetchMock.setHandler(() => {
1363
+ const server = createStreamResponse();
1364
+ servers.push(server);
1365
+ return server.response;
1366
+ });
1367
+
1368
+ const metas: AssistantTransportConnectionMetadata[] = [];
1369
+ const { aui } = mountThread({ converter: toolCallConverter(metas) });
1370
+ aui()
1371
+ .modelContext()
1372
+ .register({
1373
+ getModelContext: () => ({
1374
+ tools: {
1375
+ probe_tool: {
1376
+ parameters: { type: "object", properties: {} },
1377
+ execute: () => new Promise(() => {}),
1378
+ },
1379
+ },
1380
+ }),
1381
+ });
1382
+
1383
+ sendCommand(aui, { type: "custom-a" } as never);
1384
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1385
+ emitToolCall(servers[0]!);
1386
+
1387
+ await waitFor(() =>
1388
+ expect(metas.at(-1)!.toolStatuses).toEqual({
1389
+ tc1: { type: "executing" },
1390
+ }),
1391
+ );
1392
+
1393
+ aui().thread().cancelRun();
1394
+
1395
+ await waitFor(() =>
1396
+ expect(allCommands(fetchMock.requests)).toContainEqual({
1397
+ type: "add-tool-result",
1398
+ toolCallId: "tc1",
1399
+ toolName: "probe_tool",
1400
+ result: "Tool execution was cancelled.",
1401
+ isError: true,
1402
+ }),
1403
+ );
1404
+ servers.at(-1)!.done();
1405
+ await waitFor(() => expect(metas.at(-1)!.toolStatuses).toEqual({}));
1406
+ });
1407
+
1408
+ it("aborts in-flight tool executions when a new user message starts a run", async () => {
1409
+ const fetchMock = installFetch();
1410
+ const servers: StreamResponse[] = [];
1411
+ fetchMock.setHandler(() => {
1412
+ const server = createStreamResponse();
1413
+ servers.push(server);
1414
+ // Follow-up runs complete immediately; only the first run streams.
1415
+ if (servers.length > 1) server.done();
1416
+ return server.response;
1417
+ });
1418
+
1419
+ const metas: AssistantTransportConnectionMetadata[] = [];
1420
+ const { aui } = mountThread({ converter: toolCallConverter(metas) });
1421
+ aui()
1422
+ .modelContext()
1423
+ .register({
1424
+ getModelContext: () => ({
1425
+ tools: {
1426
+ probe_tool: {
1427
+ parameters: { type: "object", properties: {} },
1428
+ execute: () => new Promise(() => {}),
1429
+ },
1430
+ },
1431
+ }),
1432
+ });
1433
+
1434
+ sendCommand(aui, { type: "custom-a" } as never);
1435
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1436
+ emitToolCall(servers[0]!);
1437
+
1438
+ await waitFor(() =>
1439
+ expect(metas.at(-1)!.toolStatuses).toEqual({
1440
+ tc1: { type: "executing" },
1441
+ }),
1442
+ );
1443
+
1444
+ aui().thread().append("next question");
1445
+
1446
+ await waitFor(() => {
1447
+ const commands = allCommands(fetchMock.requests);
1448
+ expect(commands).toContainEqual({
1449
+ type: "add-tool-result",
1450
+ toolCallId: "tc1",
1451
+ toolName: "probe_tool",
1452
+ result: "Tool execution was cancelled.",
1453
+ isError: true,
1454
+ });
1455
+ expect(commands).toContainEqual({
1456
+ type: "add-message",
1457
+ message: {
1458
+ role: "user",
1459
+ parts: [{ type: "text", text: "next question" }],
1460
+ },
1461
+ parentId: "a-tool",
1462
+ sourceId: null,
1463
+ });
1464
+ });
1465
+ await waitFor(() => expect(metas.at(-1)!.toolStatuses).toEqual({}));
1466
+ });
1467
+
1468
+ it("unmounting mid-stream aborts the run without callbacks or crashes", async () => {
1469
+ const fetchMock = installFetch();
1470
+ let server!: StreamResponse;
1471
+ let aborted = false;
1472
+ fetchMock.setHandler(({ init }) => {
1473
+ server = createStreamResponse();
1474
+ init.signal?.addEventListener("abort", () => {
1475
+ aborted = true;
1476
+ server.error(
1477
+ new DOMException("The operation was aborted.", "AbortError"),
1478
+ );
1479
+ });
1480
+ return server.response;
1481
+ });
1482
+
1483
+ const onCancel = vi.fn();
1484
+ const onError = vi.fn();
1485
+ const onFinish = vi.fn();
1486
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
1487
+ try {
1488
+ const { aui, unmount } = mountThread({ onCancel, onError, onFinish });
1489
+ sendCommand(aui, { type: "custom-a" } as never);
1490
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1491
+
1492
+ server.emit({
1493
+ type: "update-state",
1494
+ operations: [
1495
+ {
1496
+ type: "set",
1497
+ path: ["messages"],
1498
+ value: [{ id: "m1", role: "assistant", text: "hi" }],
1499
+ },
1500
+ ],
1501
+ });
1502
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["hi"]));
1503
+
1504
+ unmount();
1505
+
1506
+ await waitFor(() => expect(aborted).toBe(true));
1507
+ await new Promise((resolve) => setTimeout(resolve, 20));
1508
+ expect(onCancel).not.toHaveBeenCalled();
1509
+ expect(onError).not.toHaveBeenCalled();
1510
+ expect(onFinish).not.toHaveBeenCalled();
1511
+ expect(errorSpy).not.toHaveBeenCalled();
1512
+ } finally {
1513
+ errorSpy.mockRestore();
1514
+ }
1515
+ });
1516
+
1517
+ it("runs normally under React StrictMode double-mounting", async () => {
1518
+ const fetchMock = installFetch();
1519
+ let server!: StreamResponse;
1520
+ fetchMock.setHandler(() => {
1521
+ server = createStreamResponse();
1522
+ return server.response;
1523
+ });
1524
+
1525
+ const { aui } = mountThread(undefined, {
1526
+ wrap: (node) => <StrictMode>{node}</StrictMode>,
1527
+ });
1528
+
1529
+ sendCommand(aui, { type: "custom-a" } as never);
1530
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1531
+
1532
+ server.emit({
1533
+ type: "update-state",
1534
+ operations: [
1535
+ {
1536
+ type: "set",
1537
+ path: ["messages"],
1538
+ value: [{ id: "m1", role: "assistant", text: "strict" }],
1539
+ },
1540
+ ],
1541
+ });
1542
+ server.done();
1543
+
1544
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["strict"]));
1545
+ await waitFor(() =>
1546
+ expect(aui().thread().getState().isRunning).toBe(false),
1547
+ );
1548
+ expect(fetchMock.requests).toHaveLength(1);
1549
+ });
1550
+
1551
+ it("keeps message client identity stable when messages are prepended", async () => {
1552
+ const fetchMock = installFetch();
1553
+ let server!: StreamResponse;
1554
+ fetchMock.setHandler(() => {
1555
+ server = createStreamResponse();
1556
+ return server.response;
1557
+ });
1558
+
1559
+ const { aui } = mountThread();
1560
+ sendCommand(aui, { type: "custom-a" } as never);
1561
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1562
+
1563
+ server.emit({
1564
+ type: "update-state",
1565
+ operations: [
1566
+ {
1567
+ type: "set",
1568
+ path: ["messages"],
1569
+ value: [{ id: "m2", role: "assistant", text: "reply" }],
1570
+ },
1571
+ ],
1572
+ });
1573
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["reply"]));
1574
+
1575
+ const before = aui().thread().message({ id: "m2" }).getState();
1576
+ expect(before.branchNumber).toBe(1);
1577
+ expect(before.branchCount).toBe(1);
1578
+
1579
+ // History load prepends the echoed human message; m2 must survive
1580
+ // re-keying (no duplicate, no phantom branch).
1581
+ server.emit({
1582
+ type: "update-state",
1583
+ operations: [
1584
+ {
1585
+ type: "set",
1586
+ path: ["messages"],
1587
+ value: [
1588
+ { id: "m1", role: "user", text: "question" },
1589
+ { id: "m2", role: "assistant", text: "reply" },
1590
+ ],
1591
+ },
1592
+ ],
1593
+ });
1594
+ server.done();
1595
+
1596
+ await waitFor(() =>
1597
+ expect(threadTexts(aui)).toEqual(["question", "reply"]),
1598
+ );
1599
+ const after = aui().thread().message({ id: "m2" }).getState();
1600
+ expect(after.id).toBe("m2");
1601
+ expect(after.branchNumber).toBe(1);
1602
+ expect(after.branchCount).toBe(1);
1603
+ expect(after.parentId).toBe("m1");
1604
+ const ids = aui()
1605
+ .thread()
1606
+ .getState()
1607
+ .messages.map((m) => m.id);
1608
+ expect(ids).toEqual(["m1", "m2"]);
1609
+ });
1610
+
1611
+ it("re-renders state selectors only when the selected slice changes", async () => {
1612
+ const fetchMock = installFetch();
1613
+ let server!: StreamResponse;
1614
+ fetchMock.setHandler(() => {
1615
+ server = createStreamResponse();
1616
+ return server.response;
1617
+ });
1618
+
1619
+ const todoValues: (string[] | undefined)[] = [];
1620
+ const textValues: (string | undefined)[] = [];
1621
+ const TodoProbe: FC = () => {
1622
+ const todos = useAssistantTransportState((s) => (s as TestState).todos);
1623
+ todoValues.push(todos);
1624
+ return null;
1625
+ };
1626
+ const TextProbe: FC = () => {
1627
+ const text = useAssistantTransportState(
1628
+ (s) => (s as TestState).messages[0]?.text,
1629
+ );
1630
+ textValues.push(text);
1631
+ return null;
1632
+ };
1633
+
1634
+ const { aui } = mountThread(
1635
+ { initialState: { messages: [], todos: ["a"] } },
1636
+ {
1637
+ children: (
1638
+ <>
1639
+ <TodoProbe />
1640
+ <TextProbe />
1641
+ </>
1642
+ ),
1643
+ },
1644
+ );
1645
+
1646
+ sendCommand(aui, { type: "custom-a" } as never);
1647
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1648
+
1649
+ server.emit({
1650
+ type: "update-state",
1651
+ operations: [
1652
+ {
1653
+ type: "set",
1654
+ path: ["messages"],
1655
+ value: [{ id: "m1", role: "assistant", text: "" }],
1656
+ },
1657
+ ],
1658
+ });
1659
+
1660
+ await waitFor(() => expect(textValues.at(-1)).toBe(""));
1661
+ const todoRendersBeforeDeltas = todoValues.length;
1662
+ const initialTodos = todoValues.at(-1);
1663
+
1664
+ for (const delta of ["a", "b", "c", "d", "e"]) {
1665
+ server.emit({
1666
+ type: "update-state",
1667
+ operations: [
1668
+ {
1669
+ type: "append-text",
1670
+ path: ["messages", "0", "text"],
1671
+ value: delta,
1672
+ },
1673
+ ],
1674
+ });
1675
+ await waitFor(() => expect(threadTexts(aui).at(-1)).toContain(delta));
1676
+ }
1677
+ server.done();
1678
+
1679
+ // Every flushed batch reached the converter and the text selector.
1680
+ await waitFor(() => expect(textValues.at(-1)).toBe("abcde"));
1681
+
1682
+ // The untouched slice kept its identity — structural sharing means the
1683
+ // todos selector saw no new value and did not re-render for the deltas.
1684
+ expect(todoValues.at(-1)).toBe(initialTodos);
1685
+ expect(todoValues.length).toBe(todoRendersBeforeDeltas);
1686
+ });
1687
+
1688
+ it("throws a descriptive error when transport hooks run against a non-transport thread", () => {
1689
+ installFetch();
1690
+ const errors: string[] = [];
1691
+ const Probe: FC = () => {
1692
+ try {
1693
+ useAssistantTransportState();
1694
+ } catch (error) {
1695
+ errors.push((error as Error).message);
1696
+ }
1697
+ return null;
1698
+ };
1699
+ const App: FC = () => {
1700
+ const aui = useAui({
1701
+ thread: ExternalThread({ messages: [] }),
1702
+ });
1703
+ return (
1704
+ <AuiProvider value={aui}>
1705
+ <Probe />
1706
+ </AuiProvider>
1707
+ );
1708
+ };
1709
+ render(<App />);
1710
+ expect(errors.at(0)).toMatch(/AssistantTransportThread/);
1711
+ });
1712
+
1713
+ it("sends threadId null when the thread list item lookup throws", async () => {
1714
+ const fetchMock = installFetch();
1715
+
1716
+ const BrokenThreads = resource(
1717
+ () =>
1718
+ ({
1719
+ getState: () => ({}),
1720
+ item: () => {
1721
+ throw new Error("no current item");
1722
+ },
1723
+ }) as never,
1724
+ );
1725
+
1726
+ const captured: { aui?: ReturnType<typeof useAui> } = {};
1727
+ const Capture: FC = () => {
1728
+ captured.aui = useAui();
1729
+ return null;
1730
+ };
1731
+ const App: FC = () => {
1732
+ const aui = useAui({
1733
+ thread: AssistantTransportThread<TestState>({
1734
+ initialState: INITIAL_STATE,
1735
+ api: "https://example.com/api",
1736
+ headers: {},
1737
+ converter: defaultConverter,
1738
+ protocol: "assistant-transport",
1739
+ }),
1740
+ threads: BrokenThreads() as never,
1741
+ });
1742
+ return (
1743
+ <AuiProvider value={aui}>
1744
+ <Capture />
1745
+ </AuiProvider>
1746
+ );
1747
+ };
1748
+ render(<App />);
1749
+
1750
+ captured.aui!.thread().append("hello");
1751
+
1752
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1753
+ expect(fetchMock.requests[0]!.body.threadId).toBeNull();
1754
+ });
1755
+
1756
+ it("exposes state and sendCommand through the public hooks", async () => {
1757
+ const fetchMock = installFetch();
1758
+
1759
+ const captured: {
1760
+ state?: TestState;
1761
+ send?: (command: AssistantTransportCommand) => void;
1762
+ } = {};
1763
+ const HookCapture: FC = () => {
1764
+ captured.state = useAssistantTransportState() as TestState;
1765
+ captured.send = useAssistantTransportSendCommand();
1766
+ return null;
1767
+ };
1768
+ mountThread(undefined, { children: <HookCapture /> });
1769
+
1770
+ await waitFor(() => expect(captured.state).toEqual(INITIAL_STATE));
1771
+
1772
+ captured.send!({ type: "custom-a" } as never);
1773
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1774
+ expect(fetchMock.requests[0]!.body.commands).toEqual([
1775
+ { type: "custom-a" },
1776
+ ]);
1777
+ });
1778
+
1779
+ it("derives tool part status from the message status (legacy parity)", async () => {
1780
+ type S = TestState & { toolCall?: { id: string; result?: string } };
1781
+ const converter = (
1782
+ state: S,
1783
+ meta: AssistantTransportConnectionMetadata,
1784
+ ) => {
1785
+ const tc = state.toolCall;
1786
+ return {
1787
+ messages: tc
1788
+ ? [
1789
+ {
1790
+ id: "a1",
1791
+ role: "assistant",
1792
+ createdAt: new Date(0),
1793
+ content: [
1794
+ { type: "text", text: "let me check" },
1795
+ {
1796
+ type: "tool-call",
1797
+ toolCallId: tc.id,
1798
+ toolName: "probe_tool",
1799
+ args: {},
1800
+ argsText: "{}",
1801
+ ...(tc.result !== undefined && { result: tc.result }),
1802
+ },
1803
+ ],
1804
+ attachments: [],
1805
+ metadata: { custom: {} },
1806
+ status: tc.result
1807
+ ? { type: "complete", reason: "stop" }
1808
+ : { type: "running" },
1809
+ } as never,
1810
+ ]
1811
+ : [],
1812
+ isRunning: meta.isSending,
1813
+ };
1814
+ };
1815
+ const fetchMock = installFetch();
1816
+ const server = createStreamResponse();
1817
+ fetchMock.setHandler(() => server.response);
1818
+
1819
+ const { aui } = mountThread({ converter });
1820
+ aui().thread().append("go");
1821
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1822
+
1823
+ server.emit({
1824
+ type: "update-state",
1825
+ operations: [{ type: "set", path: ["toolCall"], value: { id: "tc1" } }],
1826
+ });
1827
+ await waitFor(() =>
1828
+ expect(aui().thread().getState().messages).toHaveLength(1),
1829
+ );
1830
+ const part = () =>
1831
+ aui().thread().message({ id: "a1" }).part({ toolCallId: "tc1" });
1832
+ expect(part().getState().status).toEqual({ type: "running" });
1833
+
1834
+ server.emit({
1835
+ type: "update-state",
1836
+ operations: [
1837
+ { type: "set", path: ["toolCall"], value: { id: "tc1", result: "ok" } },
1838
+ ],
1839
+ });
1840
+ server.done();
1841
+ await waitFor(() =>
1842
+ expect(part().getState().status).toEqual({ type: "complete" }),
1843
+ );
1844
+ });
1845
+
1846
+ it("dispatches a synchronous composer setText + send sequence", async () => {
1847
+ const fetchMock = installFetch();
1848
+ const { aui } = mountThread();
1849
+
1850
+ aui().thread().composer().setText("hello");
1851
+ aui().thread().composer().send();
1852
+
1853
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1854
+ expect(fetchMock.requests[0]!.body.commands[0].message.parts).toEqual([
1855
+ { type: "text", text: "hello" },
1856
+ ]);
1857
+ });
1858
+ });