@assistant-ui/react-statewire 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +1,38 @@
1
- import { describe, expect, it } from "vitest";
1
+ import { describe, expect, it, vi } from "vitest";
2
2
  import type { AssistantTransportStateOperation } from "assistant-stream";
3
- import { applyOps } from "statewire";
4
3
  import { translateStateOp } from "./stateOps";
4
+ import type { TranslatedOp } from "./stateOps";
5
+
6
+ const applyTranslated = (state: unknown, op: TranslatedOp): unknown => {
7
+ if (op.op === "add" && op.path.length === 1) {
8
+ const offset = op.path[0] as number;
9
+ if (typeof state === "string") {
10
+ return (
11
+ state.slice(0, offset) + (op.value as string) + state.slice(offset)
12
+ );
13
+ }
14
+ const list = state as unknown[];
15
+ return [...list.slice(0, offset), op.value, ...list.slice(offset)];
16
+ }
17
+ if (op.path.length === 0) return op.value;
18
+ const [key, ...rest] = op.path as [string | number, ...(string | number)[]];
19
+ if (Array.isArray(state)) {
20
+ const idx = key as number;
21
+ const next = [...state];
22
+ next[idx] = applyTranslated(state[idx], { ...op, path: rest });
23
+ return next;
24
+ }
25
+ const obj = state as Record<string, unknown>;
26
+ return { ...obj, [key]: applyTranslated(obj[key], { ...op, path: rest }) };
27
+ };
5
28
 
6
29
  const apply = (
7
30
  state: unknown,
8
31
  ops: readonly AssistantTransportStateOperation[],
9
32
  ) => {
10
33
  for (const op of ops) {
11
- state = applyOps(state, [translateStateOp(state, op)]).state;
34
+ const translated = translateStateOp(state, op);
35
+ if (translated !== undefined) state = applyTranslated(state, translated);
12
36
  }
13
37
  return state;
14
38
  };
@@ -111,15 +135,31 @@ describe("translateStateOp", () => {
111
135
  ).toThrow("Invalid path: [b]");
112
136
  });
113
137
 
114
- it("throws on unsafe path segments", () => {
115
- expect(() =>
116
- apply({}, [{ type: "set", path: ["__proto__"], value: 1 }]),
117
- ).toThrow("Unsafe gorp path segment: __proto__");
118
- });
119
-
120
- it("throws on unsafe vivified segments", () => {
121
- expect(() =>
122
- apply({}, [{ type: "set", path: ["a", "constructor"], value: 1 }]),
123
- ).toThrow("Unsafe gorp path segment: constructor");
138
+ it("warns and strips ops with unsafe path segments", () => {
139
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
140
+ try {
141
+ expect(
142
+ apply({ a: 1 }, [{ type: "set", path: ["__proto__"], value: 1 }]),
143
+ ).toEqual({ a: 1 });
144
+ expect(warn).toHaveBeenCalledWith(
145
+ 'statewire: stripped op with unsafe path segment "__proto__"',
146
+ );
147
+ } finally {
148
+ warn.mockRestore();
149
+ }
150
+ });
151
+
152
+ it("warns and strips ops with unsafe vivified segments", () => {
153
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
154
+ try {
155
+ expect(
156
+ apply({}, [{ type: "set", path: ["a", "constructor"], value: 1 }]),
157
+ ).toEqual({});
158
+ expect(warn).toHaveBeenCalledWith(
159
+ 'statewire: stripped op with unsafe path segment "constructor"',
160
+ );
161
+ } finally {
162
+ warn.mockRestore();
163
+ }
124
164
  });
125
165
  });
package/src/stateOps.ts CHANGED
@@ -1,19 +1,10 @@
1
1
  import type { AssistantTransportStateOperation } from "assistant-stream";
2
2
  import type { Statewire } from "statewire";
3
3
 
4
- export type TranslatedOp = Extract<
5
- Statewire.Op,
6
- { op: "replace" | "add" | "append" }
7
- >;
4
+ export type TranslatedOp = Extract<Statewire.Op, { op: "replace" | "add" }>;
8
5
 
9
6
  const UNSAFE_SEGMENTS = new Set(["__proto__", "constructor", "prototype"]);
10
7
 
11
- const assertSafeSegment = (segment: string) => {
12
- if (UNSAFE_SEGMENTS.has(segment)) {
13
- throw new Error(`Unsafe gorp path segment: ${segment}`);
14
- }
15
- };
16
-
17
8
  const assertStringTarget = (
18
9
  current: unknown,
19
10
  op: AssistantTransportStateOperation,
@@ -32,7 +23,6 @@ const vivified = (
32
23
  if (op.type === "append-text") assertStringTarget(undefined, op);
33
24
  let value: unknown = op.value;
34
25
  for (let i = segments.length - 1; i >= from; i--) {
35
- assertSafeSegment(segments[i]!);
36
26
  value = { [segments[i]!]: value };
37
27
  }
38
28
  return value;
@@ -40,12 +30,17 @@ const vivified = (
40
30
 
41
31
  // Expresses a gorp `update-state` op as a statewire op against the current
42
32
  // state, replicating GorpStreamAccumulator's path semantics — including its
43
- // errors.
33
+ // errors. Ops with unsafe path segments are stripped with a warning.
44
34
  export const translateStateOp = (
45
35
  root: unknown,
46
36
  op: AssistantTransportStateOperation,
47
- ): TranslatedOp => {
37
+ ): TranslatedOp | undefined => {
48
38
  const segments = op.path;
39
+ const unsafe = segments.find((segment) => UNSAFE_SEGMENTS.has(segment));
40
+ if (unsafe !== undefined) {
41
+ console.warn(`statewire: stripped op with unsafe path segment "${unsafe}"`);
42
+ return undefined;
43
+ }
49
44
  const path: (string | number)[] = [];
50
45
  let node: unknown = root;
51
46
 
@@ -57,7 +52,6 @@ export const translateStateOp = (
57
52
  throw new Error(`Invalid path: [${segments.slice(i).join(", ")}]`);
58
53
  }
59
54
  const key = segments[i]!;
60
- assertSafeSegment(key);
61
55
  const last = i === segments.length - 1;
62
56
 
63
57
  if (Array.isArray(node)) {
@@ -74,8 +68,13 @@ export const translateStateOp = (
74
68
  const insert = idx === node.length;
75
69
  if (last) {
76
70
  if (op.type === "append-text") {
77
- assertStringTarget(insert ? undefined : node[idx], op);
78
- return { op: "append", path: [...path, idx], value: op.value };
71
+ const current = insert ? undefined : node[idx];
72
+ assertStringTarget(current, op);
73
+ return {
74
+ op: "add",
75
+ path: [...path, idx, (current as string).length],
76
+ value: op.value,
77
+ };
79
78
  }
80
79
  return {
81
80
  op: insert ? "add" : "replace",
@@ -98,8 +97,13 @@ export const translateStateOp = (
98
97
  const obj = node as Record<string, unknown>;
99
98
  if (last) {
100
99
  if (op.type === "append-text") {
101
- assertStringTarget(Object.hasOwn(obj, key) ? obj[key] : undefined, op);
102
- return { op: "append", path: [...path, key], value: op.value };
100
+ const current = Object.hasOwn(obj, key) ? obj[key] : undefined;
101
+ assertStringTarget(current, op);
102
+ return {
103
+ op: "add",
104
+ path: [...path, key, (current as string).length],
105
+ value: op.value,
106
+ };
103
107
  }
104
108
  return { op: "replace", path: [...path, key], value: op.value };
105
109
  }
@@ -116,7 +120,7 @@ export const translateStateOp = (
116
120
 
117
121
  if (op.type === "append-text") {
118
122
  assertStringTarget(node, op);
119
- return { op: "append", path: [], value: op.value };
123
+ return { op: "add", path: [(node as string).length], value: op.value };
120
124
  }
121
125
  return { op: "replace", path: [], value: op.value };
122
126
  };
@@ -341,7 +341,7 @@ describe("AssistantTransportThread", () => {
341
341
  expect(errored[0]).toEqual([{ type: "custom-a" }]);
342
342
  });
343
343
 
344
- it("applies update-state chunks atomically — an op error mid-chunk leaves the state untouched", async () => {
344
+ it("applies chunk ops one-by-one — an op error mid-chunk keeps the applied prefix", async () => {
345
345
  const fetchMock = installFetch();
346
346
  const servers: StreamResponse[] = [];
347
347
  fetchMock.setHandler(() => {
@@ -361,8 +361,8 @@ describe("AssistantTransportThread", () => {
361
361
  sendCommand(aui, { type: "custom-a" } as never);
362
362
  await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
363
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.
364
+ // Second op is invalid (append-text onto a non-string) — the run errors,
365
+ // but the ops before it stay applied.
366
366
  servers[0]!.emit({
367
367
  type: "update-state",
368
368
  operations: [
@@ -378,11 +378,13 @@ describe("AssistantTransportThread", () => {
378
378
 
379
379
  await waitFor(() => expect(errors).toHaveLength(1));
380
380
 
381
- // The partially-applied chunk must not leak into the next request body.
381
+ // The applied prefix carries into the next request body.
382
382
  sendCommand(aui, { type: "custom-b" } as never);
383
383
  await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
384
- expect(fetchMock.requests[1]!.body.state).toEqual(INITIAL_STATE);
385
- expect(threadTexts(aui)).toEqual([]);
384
+ expect(fetchMock.requests[1]!.body.state).toEqual({
385
+ messages: [{ id: "m1", role: "assistant", text: "partial" }],
386
+ });
387
+ expect(threadTexts(aui)).toEqual(["partial"]);
386
388
  });
387
389
 
388
390
  it("cancels a running request and reports all pending commands", async () => {
@@ -438,6 +440,48 @@ describe("AssistantTransportThread", () => {
438
440
  );
439
441
  });
440
442
 
443
+ it("decodes resume runs leniently — unknown events and a missing [DONE] still apply valid chunks", async () => {
444
+ const fetchMock = installFetch();
445
+ fetchMock.setHandler(() => {
446
+ const server = createStreamResponse();
447
+ server.push("event: custom\ndata: {}\n\n");
448
+ server.emit({
449
+ type: "update-state",
450
+ operations: [
451
+ {
452
+ type: "set",
453
+ path: ["messages"],
454
+ value: [{ id: "m1", role: "assistant", text: "recovered" }],
455
+ },
456
+ ],
457
+ });
458
+ server.close();
459
+ return server.response;
460
+ });
461
+
462
+ const errors: string[] = [];
463
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
464
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
465
+ try {
466
+ const { aui } = mountThread({
467
+ resumeApi: "https://example.com/resume",
468
+ onError: (error) => {
469
+ errors.push(error.message);
470
+ },
471
+ });
472
+ aui().thread().resumeRun({ parentId: null });
473
+
474
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["recovered"]));
475
+ await waitFor(() =>
476
+ expect(aui().thread().getState().isRunning).toBe(false),
477
+ );
478
+ expect(errors).toEqual([]);
479
+ } finally {
480
+ warnSpy.mockRestore();
481
+ errorSpy.mockRestore();
482
+ }
483
+ });
484
+
441
485
  it("surfaces error chunks after the stream completes", async () => {
442
486
  const fetchMock = installFetch();
443
487
  fetchMock.setHandler(() => {
@@ -858,6 +902,31 @@ describe("AssistantTransportThread", () => {
858
902
  expect(loadingStates).toEqual([false, false]);
859
903
  });
860
904
 
905
+ it("surfaces an invalid replay header via onError", async () => {
906
+ const fetchMock = installFetch();
907
+ fetchMock.setHandler(() => {
908
+ const server = createStreamResponse({
909
+ headers: { "Aui-Replay-Content-Length": "garbage" },
910
+ });
911
+ return server.response;
912
+ });
913
+
914
+ const errors: string[] = [];
915
+ const { aui } = mountThread({
916
+ resumeApi: "https://example.com/resume",
917
+ onError: (error) => {
918
+ errors.push(error.message);
919
+ },
920
+ });
921
+ aui().thread().resumeRun({ parentId: null });
922
+
923
+ await waitFor(() =>
924
+ expect(errors).toEqual([
925
+ 'statewire: invalid Aui-Replay-Content-Length header "garbage"',
926
+ ]),
927
+ );
928
+ });
929
+
861
930
  it("reads body object getters at request time", async () => {
862
931
  const fetchMock = installFetch();
863
932
  let dynamic = "before";
@@ -1856,3 +1925,74 @@ describe("AssistantTransportThread", () => {
1856
1925
  ]);
1857
1926
  });
1858
1927
  });
1928
+
1929
+ describe("reload", () => {
1930
+ const completeFirstTurn = async (
1931
+ fetchMock: ReturnType<typeof installFetch>,
1932
+ aui: () => ReturnType<typeof useAui>,
1933
+ ) => {
1934
+ let server!: StreamResponse;
1935
+ fetchMock.setHandler(() => {
1936
+ server = createStreamResponse();
1937
+ return server.response;
1938
+ });
1939
+ aui().thread().append("hello");
1940
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
1941
+ server.emit({
1942
+ type: "update-state",
1943
+ operations: [
1944
+ {
1945
+ type: "set",
1946
+ path: ["messages"],
1947
+ value: [
1948
+ { id: "m1", role: "user", text: "hello" },
1949
+ { id: "m2", role: "assistant", text: "hi" },
1950
+ ],
1951
+ },
1952
+ ],
1953
+ });
1954
+ server.done();
1955
+ await waitFor(() =>
1956
+ expect(aui().thread().getState().isRunning).toBe(false),
1957
+ );
1958
+ };
1959
+
1960
+ it("regenerates from idle with an empty queue", async () => {
1961
+ const fetchMock = installFetch();
1962
+ const { aui } = mountThread();
1963
+ await completeFirstTurn(fetchMock, aui);
1964
+
1965
+ aui().thread().message({ id: "m2" }).reload();
1966
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
1967
+ expect(fetchMock.requests[1]!.body.commands).toEqual([]);
1968
+ expect(fetchMock.requests[1]!.body.parentId).toBe("m1");
1969
+ });
1970
+
1971
+ it("keeps the parentId for the next run when the reload run fails", async () => {
1972
+ const fetchMock = installFetch();
1973
+ const { aui } = mountThread();
1974
+ await completeFirstTurn(fetchMock, aui);
1975
+
1976
+ fetchMock.setHandler(() => new Response(null, { status: 500 }));
1977
+ aui().thread().message({ id: "m2" }).reload();
1978
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
1979
+ await waitFor(() =>
1980
+ expect(aui().thread().getState().isRunning).toBe(false),
1981
+ );
1982
+ expect(fetchMock.requests[1]!.body.parentId).toBe("m1");
1983
+
1984
+ fetchMock.setHandler(() => {
1985
+ const server = createStreamResponse();
1986
+ server.done();
1987
+ return server.response;
1988
+ });
1989
+ sendCommand(aui, {
1990
+ type: "add-message",
1991
+ message: { role: "user", parts: [{ type: "text", text: "retry" }] },
1992
+ parentId: null,
1993
+ sourceId: null,
1994
+ });
1995
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(3));
1996
+ expect(fetchMock.requests[2]!.body.parentId).toBe("m1");
1997
+ });
1998
+ });
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 AgentbaseAI Inc.
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.