@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,581 @@
1
+ // @vitest-environment jsdom
2
+
3
+ // Runs the SAME wire transcript through the legacy useAssistantTransportRuntime
4
+ // and the statewire re-implementation, then diffs the converged UI state and
5
+ // the request bodies both produced.
6
+
7
+ import { render, waitFor } from "@testing-library/react";
8
+ import type { FC } from "react";
9
+ import { afterEach, describe, expect, it, vi } from "vitest";
10
+ import { AuiProvider, useAui } from "@assistant-ui/store";
11
+ import {
12
+ AssistantRuntimeProvider,
13
+ useAssistantTransportRuntime,
14
+ } from "@assistant-ui/react";
15
+ import type { ExternalThreadMessage } from "@assistant-ui/react";
16
+ import { AssistantTransportThread } from "./AssistantTransportThread";
17
+ import type {
18
+ AssistantTransportOptions,
19
+ AssistantTransportStateConverter,
20
+ } from "./types";
21
+ import { sseEvent } from "./__tests__/testHelpers";
22
+
23
+ type TestState = {
24
+ messages: { id: string; role: "user" | "assistant"; text: string }[];
25
+ };
26
+
27
+ const INITIAL_STATE: TestState = { messages: [] };
28
+
29
+ const converter: AssistantTransportStateConverter<TestState> = (
30
+ state,
31
+ meta,
32
+ ) => ({
33
+ messages: [
34
+ ...state.messages.map(
35
+ (m) =>
36
+ ({
37
+ id: m.id,
38
+ role: m.role,
39
+ createdAt: new Date(0),
40
+ content: [{ type: "text", text: m.text }],
41
+ attachments: [],
42
+ metadata: { custom: {} },
43
+ ...(m.role === "assistant" && {
44
+ status: { type: "complete", reason: "stop" },
45
+ }),
46
+ }) as unknown as ExternalThreadMessage,
47
+ ),
48
+ ...meta.pendingCommands.flatMap((c, i) =>
49
+ c.type === "add-message" && c.message.role === "user"
50
+ ? [
51
+ {
52
+ id: `optimistic-${i}`,
53
+ role: "user",
54
+ createdAt: new Date(0),
55
+ content: [
56
+ {
57
+ type: "text",
58
+ text:
59
+ c.message.parts.find((p) => p.type === "text")?.text ?? "",
60
+ },
61
+ ],
62
+ attachments: [],
63
+ metadata: { custom: {} },
64
+ } as unknown as ExternalThreadMessage,
65
+ ]
66
+ : [],
67
+ ),
68
+ ],
69
+ isRunning: meta.isSending,
70
+ });
71
+
72
+ type RecordedRequest = { url: string; body: Record<string, any> };
73
+
74
+ // Scripted server: request N gets transcript N, streamed whole.
75
+ const installScriptedFetch = (transcript: string[][]) => {
76
+ const requests: RecordedRequest[] = [];
77
+ vi.stubGlobal(
78
+ "fetch",
79
+ async (url: RequestInfo | URL, init: RequestInit = {}) => {
80
+ const index = requests.length;
81
+ requests.push({
82
+ url: String(url),
83
+ body: JSON.parse(init.body as string),
84
+ });
85
+ const events = transcript[index] ?? ["data: [DONE]\n\n"];
86
+ const encoder = new TextEncoder();
87
+ const stream = new ReadableStream<Uint8Array>({
88
+ async start(controller) {
89
+ for (const event of events) {
90
+ controller.enqueue(encoder.encode(event));
91
+ await new Promise((resolve) => setTimeout(resolve, 0));
92
+ }
93
+ controller.close();
94
+ },
95
+ });
96
+ return new Response(stream, { status: 200 });
97
+ },
98
+ );
99
+ return requests;
100
+ };
101
+
102
+ const TRANSCRIPT: string[][] = [
103
+ [
104
+ sseEvent({
105
+ type: "update-state",
106
+ operations: [
107
+ {
108
+ type: "set",
109
+ path: ["messages"],
110
+ value: [
111
+ { id: "h1", role: "user", text: "hello" },
112
+ { id: "a1", role: "assistant", text: "" },
113
+ ],
114
+ },
115
+ ],
116
+ }),
117
+ sseEvent({
118
+ type: "update-state",
119
+ operations: [
120
+ { type: "append-text", path: ["messages", "1", "text"], value: "Hi " },
121
+ {
122
+ type: "append-text",
123
+ path: ["messages", "1", "text"],
124
+ value: "there!",
125
+ },
126
+ ],
127
+ }),
128
+ "data: [DONE]\n\n",
129
+ ],
130
+ ];
131
+
132
+ type Observed = {
133
+ texts: string[];
134
+ ids: string[];
135
+ isRunning: boolean;
136
+ };
137
+
138
+ afterEach(() => {
139
+ vi.unstubAllGlobals();
140
+ });
141
+
142
+ const observeLegacy = async (): Promise<{
143
+ requests: RecordedRequest[];
144
+ result: Observed;
145
+ }> => {
146
+ const requests = installScriptedFetch(TRANSCRIPT);
147
+ const captured: {
148
+ runtime?: ReturnType<typeof useAssistantTransportRuntime>;
149
+ } = {};
150
+ const App: FC = () => {
151
+ captured.runtime = useAssistantTransportRuntime<TestState>({
152
+ initialState: INITIAL_STATE,
153
+ api: "https://example.com/api",
154
+ protocol: "assistant-transport",
155
+ headers: {},
156
+ converter,
157
+ });
158
+ return (
159
+ <AssistantRuntimeProvider runtime={captured.runtime}>
160
+ {null}
161
+ </AssistantRuntimeProvider>
162
+ );
163
+ };
164
+ render(<App />);
165
+
166
+ // The remote thread list mounts the real thread asynchronously; appending
167
+ // against the placeholder throws, so retry until the real thread is live.
168
+ await waitFor(() => {
169
+ captured.runtime!.thread.append("hello");
170
+ });
171
+ await waitFor(() => expect(requests).toHaveLength(1));
172
+ await waitFor(() => {
173
+ const state = captured.runtime!.thread.getState();
174
+ expect(state.isRunning).toBe(false);
175
+ expect(state.messages).toHaveLength(2);
176
+ });
177
+
178
+ const state = captured.runtime!.thread.getState();
179
+ return {
180
+ requests,
181
+ result: {
182
+ texts: state.messages.map((m) =>
183
+ m.content.flatMap((p) => (p.type === "text" ? [p.text] : [])).join(""),
184
+ ),
185
+ ids: state.messages.map((m) => m.id),
186
+ isRunning: state.isRunning,
187
+ },
188
+ };
189
+ };
190
+
191
+ const observeNew = async (): Promise<{
192
+ requests: RecordedRequest[];
193
+ result: Observed;
194
+ }> => {
195
+ const requests = installScriptedFetch(TRANSCRIPT);
196
+ const captured: { aui?: ReturnType<typeof useAui> } = {};
197
+ const Capture: FC = () => {
198
+ captured.aui = useAui();
199
+ return null;
200
+ };
201
+ const options: AssistantTransportOptions<TestState> = {
202
+ initialState: INITIAL_STATE,
203
+ api: "https://example.com/api",
204
+ protocol: "assistant-transport",
205
+ headers: {},
206
+ converter,
207
+ };
208
+ const App: FC = () => {
209
+ const aui = useAui({
210
+ thread: AssistantTransportThread<TestState>(options),
211
+ });
212
+ return (
213
+ <AuiProvider value={aui}>
214
+ <Capture />
215
+ </AuiProvider>
216
+ );
217
+ };
218
+ render(<App />);
219
+
220
+ captured.aui!.thread().append("hello");
221
+ await waitFor(() => expect(requests).toHaveLength(1));
222
+ await waitFor(() => {
223
+ const state = captured.aui!.thread().getState();
224
+ expect(state.isRunning).toBe(false);
225
+ expect(state.messages).toHaveLength(2);
226
+ });
227
+
228
+ const state = captured.aui!.thread().getState();
229
+ return {
230
+ requests,
231
+ result: {
232
+ texts: state.messages.map((m) =>
233
+ m.parts.flatMap((p) => (p.type === "text" ? [p.text] : [])).join(""),
234
+ ),
235
+ ids: state.messages.map((m) => m.id),
236
+ isRunning: state.isRunning,
237
+ },
238
+ };
239
+ };
240
+
241
+ // ---------------------------------------------------------------------------
242
+ // Extended transcript: composer sends, a frontend tool round, and the error
243
+ // path — compared for identical requests, callback sequences, and states.
244
+ // ---------------------------------------------------------------------------
245
+
246
+ type ToolState = TestState & {
247
+ toolCall?: { id: string; name: string; argsText: string } | null;
248
+ note?: string;
249
+ };
250
+
251
+ const toolConverter: AssistantTransportStateConverter<ToolState> = (
252
+ state,
253
+ meta,
254
+ ) => {
255
+ const base = converter(state, meta);
256
+ if (!state.toolCall) return base;
257
+ return {
258
+ ...base,
259
+ messages: [
260
+ ...base.messages,
261
+ {
262
+ id: "a-tool",
263
+ role: "assistant",
264
+ createdAt: new Date(0),
265
+ content: [
266
+ {
267
+ type: "tool-call",
268
+ toolCallId: state.toolCall.id,
269
+ toolName: state.toolCall.name,
270
+ args: JSON.parse(state.toolCall.argsText),
271
+ argsText: state.toolCall.argsText,
272
+ },
273
+ ],
274
+ attachments: [],
275
+ metadata: { custom: {} },
276
+ status: { type: "requires-action", reason: "tool-call" },
277
+ } as unknown as ExternalThreadMessage,
278
+ ],
279
+ isRunning: meta.isSending,
280
+ };
281
+ };
282
+
283
+ const TOOL_TRANSCRIPT: string[][] = [
284
+ [
285
+ sseEvent({
286
+ type: "update-state",
287
+ operations: [
288
+ {
289
+ type: "set",
290
+ path: ["messages"],
291
+ value: [
292
+ { id: "h1", role: "user", text: "hello" },
293
+ { id: "a1", role: "assistant", text: "sure" },
294
+ ],
295
+ },
296
+ {
297
+ type: "set",
298
+ path: ["toolCall"],
299
+ value: { id: "tc1", name: "probe_tool", argsText: '{"x":1}' },
300
+ },
301
+ ],
302
+ }),
303
+ "data: [DONE]\n\n",
304
+ ],
305
+ [
306
+ sseEvent({
307
+ type: "update-state",
308
+ operations: [
309
+ { type: "set", path: ["toolCall"], value: null },
310
+ {
311
+ type: "set",
312
+ path: ["messages"],
313
+ value: [
314
+ { id: "h1", role: "user", text: "hello" },
315
+ { id: "a1", role: "assistant", text: "sure" },
316
+ { id: "a2", role: "assistant", text: "done" },
317
+ ],
318
+ },
319
+ ],
320
+ }),
321
+ "data: [DONE]\n\n",
322
+ ],
323
+ // Request 3 (composer "fail") is answered with a 500 by the fetch stub.
324
+ ];
325
+
326
+ type CallbackEvent =
327
+ | { type: "finish" }
328
+ | { type: "error"; message: string; commands: unknown }
329
+ | { type: "cancel"; commands: unknown; errorMessage: string | undefined };
330
+
331
+ const installToolScriptedFetch = (transcript: string[][]) => {
332
+ const requests: RecordedRequest[] = [];
333
+ vi.stubGlobal(
334
+ "fetch",
335
+ async (url: RequestInfo | URL, init: RequestInit = {}) => {
336
+ const index = requests.length;
337
+ requests.push({
338
+ url: String(url),
339
+ body: JSON.parse(init.body as string),
340
+ });
341
+ const events = transcript[index];
342
+ if (!events) {
343
+ // A macrotask of latency so the legacy runtime commits its queue
344
+ // renders first — it reads render-captured queue state in onError,
345
+ // while the re-implementation reads live state.
346
+ await new Promise((resolve) => setTimeout(resolve, 10));
347
+ return new Response("boom", { status: 500 });
348
+ }
349
+ const encoder = new TextEncoder();
350
+ const stream = new ReadableStream<Uint8Array>({
351
+ async start(controller) {
352
+ for (const event of events) {
353
+ controller.enqueue(encoder.encode(event));
354
+ await new Promise((resolve) => setTimeout(resolve, 0));
355
+ }
356
+ controller.close();
357
+ },
358
+ });
359
+ return new Response(stream, { status: 200 });
360
+ },
361
+ );
362
+ return requests;
363
+ };
364
+
365
+ // Inferred literal type — structurally satisfies both the legacy and the new
366
+ // options types under exactOptionalPropertyTypes.
367
+ const toolOptions = (events: CallbackEvent[]) => ({
368
+ initialState: { messages: [] } as ToolState,
369
+ api: "https://example.com/api",
370
+ protocol: "assistant-transport" as const,
371
+ headers: {},
372
+ converter: toolConverter,
373
+ onFinish: () => {
374
+ events.push({ type: "finish" });
375
+ },
376
+ onError: (
377
+ error: Error,
378
+ params: {
379
+ commands: unknown;
380
+ updateState: (updater: (s: ToolState) => ToolState) => void;
381
+ },
382
+ ) => {
383
+ events.push({
384
+ type: "error",
385
+ message: error.message,
386
+ commands: params.commands,
387
+ });
388
+ params.updateState((s) => ({ ...s, note: "err" }));
389
+ },
390
+ onCancel: (params: { commands: unknown; error?: Error }) => {
391
+ events.push({
392
+ type: "cancel",
393
+ commands: params.commands,
394
+ errorMessage: params.error?.message,
395
+ });
396
+ },
397
+ });
398
+
399
+ const PROBE_TOOL = {
400
+ probe_tool: {
401
+ parameters: { type: "object" as const, properties: {} },
402
+ execute: async () => ({ probed: true }),
403
+ },
404
+ };
405
+
406
+ type ToolObserved = {
407
+ requests: RecordedRequest[];
408
+ events: CallbackEvent[];
409
+ texts: string[];
410
+ ids: string[];
411
+ isRunning: boolean;
412
+ wireState: unknown;
413
+ };
414
+
415
+ const observeLegacyToolRun = async (): Promise<ToolObserved> => {
416
+ const requests = installToolScriptedFetch(TOOL_TRANSCRIPT);
417
+ const events: CallbackEvent[] = [];
418
+ const captured: {
419
+ runtime?: ReturnType<typeof useAssistantTransportRuntime>;
420
+ } = {};
421
+ const App: FC = () => {
422
+ captured.runtime = useAssistantTransportRuntime<ToolState>(
423
+ toolOptions(events),
424
+ );
425
+ return (
426
+ <AssistantRuntimeProvider runtime={captured.runtime}>
427
+ {null}
428
+ </AssistantRuntimeProvider>
429
+ );
430
+ };
431
+ render(<App />);
432
+
433
+ captured.runtime!.registerModelContextProvider({
434
+ getModelContext: () => ({ tools: PROBE_TOOL }),
435
+ });
436
+
437
+ await waitFor(() => {
438
+ captured.runtime!.thread.composer.setText("hello");
439
+ captured.runtime!.thread.composer.send();
440
+ });
441
+ await waitFor(() => expect(requests).toHaveLength(2), { timeout: 3000 });
442
+ await waitFor(() => {
443
+ const state = captured.runtime!.thread.getState();
444
+ expect(state.isRunning).toBe(false);
445
+ expect(state.messages).toHaveLength(3);
446
+ });
447
+
448
+ captured.runtime!.thread.composer.setText("fail");
449
+ captured.runtime!.thread.composer.send();
450
+ await waitFor(() =>
451
+ expect(events.filter((e) => e.type === "cancel")).toHaveLength(1),
452
+ );
453
+ await waitFor(() =>
454
+ expect(captured.runtime!.thread.getState().isRunning).toBe(false),
455
+ );
456
+
457
+ const state = captured.runtime!.thread.getState();
458
+ return {
459
+ requests,
460
+ events,
461
+ texts: state.messages.map((m) =>
462
+ m.content.flatMap((p) => (p.type === "text" ? [p.text] : [])).join(""),
463
+ ),
464
+ ids: state.messages.map((m) => m.id),
465
+ isRunning: state.isRunning,
466
+ wireState: (state.extras as { state: unknown }).state,
467
+ };
468
+ };
469
+
470
+ const observeNewToolRun = async (): Promise<ToolObserved> => {
471
+ const requests = installToolScriptedFetch(TOOL_TRANSCRIPT);
472
+ const events: CallbackEvent[] = [];
473
+ const captured: { aui?: ReturnType<typeof useAui> } = {};
474
+ const Capture: FC = () => {
475
+ captured.aui = useAui();
476
+ return null;
477
+ };
478
+ const options = toolOptions(events);
479
+ const App: FC = () => {
480
+ const aui = useAui({
481
+ thread: AssistantTransportThread<ToolState>(options),
482
+ });
483
+ return (
484
+ <AuiProvider value={aui}>
485
+ <Capture />
486
+ </AuiProvider>
487
+ );
488
+ };
489
+ render(<App />);
490
+
491
+ captured
492
+ .aui!.modelContext()
493
+ .register({ getModelContext: () => ({ tools: PROBE_TOOL }) });
494
+
495
+ captured.aui!.thread().composer().setText("hello");
496
+ await waitFor(() =>
497
+ expect(captured.aui!.thread().getState().composer.text).toBe("hello"),
498
+ );
499
+ captured.aui!.thread().composer().send();
500
+ await waitFor(() => expect(requests).toHaveLength(2), { timeout: 3000 });
501
+ await waitFor(() => {
502
+ const state = captured.aui!.thread().getState();
503
+ expect(state.isRunning).toBe(false);
504
+ expect(state.messages).toHaveLength(3);
505
+ });
506
+
507
+ captured.aui!.thread().composer().setText("fail");
508
+ await waitFor(() =>
509
+ expect(captured.aui!.thread().getState().composer.text).toBe("fail"),
510
+ );
511
+ captured.aui!.thread().composer().send();
512
+ await waitFor(() =>
513
+ expect(events.filter((e) => e.type === "cancel")).toHaveLength(1),
514
+ );
515
+ await waitFor(() =>
516
+ expect(captured.aui!.thread().getState().isRunning).toBe(false),
517
+ );
518
+
519
+ const state = captured.aui!.thread().getState();
520
+ return {
521
+ requests,
522
+ events,
523
+ texts: state.messages.map((m) =>
524
+ m.parts.flatMap((p) => (p.type === "text" ? [p.text] : [])).join(""),
525
+ ),
526
+ ids: state.messages.map((m) => m.id),
527
+ isRunning: state.isRunning,
528
+ wireState: (state.extras as { state: unknown }).state,
529
+ };
530
+ };
531
+
532
+ describe("legacy diff", () => {
533
+ it("produces the same converged state and request bodies as the legacy runtime", async () => {
534
+ const legacy = await observeLegacy();
535
+ vi.unstubAllGlobals();
536
+ const modern = await observeNew();
537
+
538
+ expect(modern.result).toEqual(legacy.result);
539
+
540
+ expect(legacy.requests).toHaveLength(1);
541
+ expect(modern.requests).toHaveLength(1);
542
+ const [legacyBody, modernBody] = [
543
+ legacy.requests[0]!.body,
544
+ modern.requests[0]!.body,
545
+ ];
546
+ expect(modernBody.commands).toEqual(legacyBody.commands);
547
+ expect(modernBody.state).toEqual(legacyBody.state);
548
+ expect(modernBody.system).toEqual(legacyBody.system);
549
+ expect(modernBody.tools).toEqual(legacyBody.tools);
550
+ expect(modernBody.parentId).toEqual(legacyBody.parentId);
551
+ });
552
+
553
+ it("matches the legacy runtime through a tool-call round and the error path", async () => {
554
+ const legacy = await observeLegacyToolRun();
555
+ vi.unstubAllGlobals();
556
+ const modern = await observeNewToolRun();
557
+
558
+ expect(modern.requests).toHaveLength(3);
559
+ expect(legacy.requests).toHaveLength(3);
560
+ for (let i = 0; i < 3; i++) {
561
+ const [legacyBody, modernBody] = [
562
+ legacy.requests[i]!.body,
563
+ modern.requests[i]!.body,
564
+ ];
565
+ expect(modern.requests[i]!.url).toEqual(legacy.requests[i]!.url);
566
+ expect(modernBody.commands).toEqual(legacyBody.commands);
567
+ expect(modernBody.state).toEqual(legacyBody.state);
568
+ // deliberate divergence (sw-73): the tool-result follow-up does not
569
+ // repeat the parentId the first run already consumed
570
+ if (i === 1) expect("parentId" in modernBody).toBe(false);
571
+ else expect(modernBody.parentId).toEqual(legacyBody.parentId);
572
+ expect(modernBody.tools).toEqual(legacyBody.tools);
573
+ }
574
+
575
+ expect(modern.events).toEqual(legacy.events);
576
+ expect(modern.texts).toEqual(legacy.texts);
577
+ expect(modern.ids).toEqual(legacy.ids);
578
+ expect(modern.isRunning).toEqual(legacy.isRunning);
579
+ expect(modern.wireState).toEqual(legacy.wireState);
580
+ });
581
+ });
@@ -0,0 +1,65 @@
1
+ export const REPLAY_CONTENT_LENGTH_HEADER = "Aui-Replay-Content-Length";
2
+
3
+ const waitForRender = () => new Promise<void>((r) => setTimeout(r, 0));
4
+
5
+ const parseReplayContentLength = (headers: Headers): number => {
6
+ const raw = headers.get(REPLAY_CONTENT_LENGTH_HEADER);
7
+ if (raw == null) return 0;
8
+
9
+ const boundary = Number(raw);
10
+ return Number.isSafeInteger(boundary) && boundary > 0 ? boundary : 0;
11
+ };
12
+
13
+ // Gates replay bytes until isReplaying:true renders, then releases live bytes after isReplaying:false renders.
14
+ export const createReplayBoundaryStream = async (
15
+ response: Response,
16
+ setReplaying: (value: boolean) => void,
17
+ ): Promise<ReadableStream<Uint8Array<ArrayBuffer>>> => {
18
+ const body = response.body!;
19
+ let remaining = parseReplayContentLength(response.headers);
20
+
21
+ if (remaining <= 0) {
22
+ return body;
23
+ }
24
+
25
+ setReplaying(true);
26
+ await waitForRender();
27
+
28
+ // Let replay bytes drain before rendering live mode, then render live mode before releasing live bytes.
29
+ const finishReplay = async () => {
30
+ remaining = 0;
31
+ await waitForRender();
32
+ setReplaying(false);
33
+ await waitForRender();
34
+ };
35
+
36
+ // TS's Transformer type predates the spec's cancel hook.
37
+ const transformer: Transformer<
38
+ Uint8Array<ArrayBuffer>,
39
+ Uint8Array<ArrayBuffer>
40
+ > & { cancel: () => void } = {
41
+ async transform(chunk, controller) {
42
+ if (remaining === 0) {
43
+ controller.enqueue(chunk);
44
+ return;
45
+ }
46
+ const replayPart = chunk.subarray(0, remaining);
47
+ remaining -= replayPart.byteLength;
48
+ controller.enqueue(replayPart);
49
+ if (remaining > 0) return;
50
+ await finishReplay();
51
+ if (replayPart.byteLength < chunk.byteLength) {
52
+ controller.enqueue(chunk.subarray(replayPart.byteLength));
53
+ }
54
+ },
55
+ async flush() {
56
+ if (remaining > 0) await finishReplay();
57
+ },
58
+ cancel() {
59
+ if (remaining > 0) setReplaying(false);
60
+ remaining = 0;
61
+ },
62
+ };
63
+
64
+ return body.pipeThrough(new TransformStream(transformer));
65
+ };