@assistant-ui/react-statewire 0.0.2 → 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.
package/src/host.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { useEffect, useRef, useState } from "react";
2
2
  import { resource } from "@assistant-ui/tap";
3
- import type { ResourceElement } from "@assistant-ui/tap";
4
3
  import { createRequestHeaders } from "@assistant-ui/core";
5
4
  import type { ModelContext } from "@assistant-ui/core";
6
5
  import {
@@ -10,15 +9,14 @@ import {
10
9
  } from "assistant-stream";
11
10
  import type { AssistantTransportStateOperation } from "assistant-stream";
12
11
  import { asAsyncIterableStream } from "assistant-stream/utils";
13
- import { applyOps } from "statewire";
14
12
  import type { Statewire } from "statewire";
15
13
  import {
16
14
  CommandExecution,
17
15
  useStatewireCommands,
18
16
  useStatewireEmit,
19
17
  useStatewireState,
20
- } from "statewire/server";
21
- import type { StatewireServer } from "statewire/server";
18
+ } from "statewire/host";
19
+ import type { StatewireHost } from "statewire/host";
22
20
  import { createReplayBoundaryStream } from "./replayBoundaryStream";
23
21
  import { translateStateOp } from "./stateOps";
24
22
  import type {
@@ -69,7 +67,7 @@ export type AssistantTransportHostCommands = {
69
67
 
70
68
  type QueueEntry = {
71
69
  command: AssistantTransportCommand;
72
- execution: StatewireServer.ExecutionResolvers;
70
+ execution: StatewireHost.ExecutionResolvers;
73
71
  };
74
72
 
75
73
  type EntryQueue = {
@@ -79,23 +77,49 @@ type EntryQueue = {
79
77
 
80
78
  const commandsOf = (entries: QueueEntry[]) => entries.map((e) => e.command);
81
79
 
82
- const createHostLoop = (
80
+ type LoopState = {
81
+ queue: EntryQueue;
82
+ activeEntries: QueueEntry[];
83
+ parentId: string | null | undefined;
84
+ resumeRequested: boolean;
85
+ followUpRequested: boolean;
86
+ isReplaying: boolean;
87
+ disposed: boolean;
88
+ abortController: AbortController | null;
89
+ queueVersion: number;
90
+ };
91
+
92
+ const useHostLoop = (
83
93
  getOptions: () => HostOptions,
84
- ctl: StatewireServer.StateCtl,
94
+ ctl: StatewireHost.StateCtl,
95
+ getAgent: () => unknown,
85
96
  ) => {
86
- let agent = getOptions().initialState as unknown;
87
- let queue: EntryQueue = { queued: [], inTransit: [] };
88
- let activeEntries: QueueEntry[] = [];
89
- let parentId: string | null | undefined;
90
- let resumeRequested = false;
91
- let followUpRequested = false;
92
- let isReplaying = false;
93
- let disposed = false;
94
- let abortController: AbortController | null = null;
97
+ const [s] = useState(
98
+ (): LoopState => ({
99
+ queue: { queued: [], inTransit: [] },
100
+ activeEntries: [],
101
+ parentId: undefined,
102
+ resumeRequested: false,
103
+ followUpRequested: false,
104
+ isReplaying: false,
105
+ disposed: false,
106
+ abortController: null,
107
+ queueVersion: 0,
108
+ }),
109
+ );
110
+
111
+ useEffect(() => {
112
+ s.disposed = false;
113
+ return () => {
114
+ s.disposed = true;
115
+ s.followUpRequested = false;
116
+ s.abortController?.abort();
117
+ };
118
+ }, [s]);
95
119
 
96
120
  const setReplaying = (value: boolean) => {
97
- if (isReplaying === value) return;
98
- isReplaying = value;
121
+ if (s.isReplaying === value) return;
122
+ s.isReplaying = value;
99
123
  ctl.apply([{ op: "replace", path: ["isReplaying"], value }]);
100
124
  };
101
125
 
@@ -104,51 +128,44 @@ const createHostLoop = (
104
128
  };
105
129
 
106
130
  const replaceAgent = (next: unknown) => {
107
- agent = next;
108
131
  ctl.apply([{ op: "replace", path: ["agent"], value: next }]);
109
132
  };
110
133
 
111
134
  const updateState = (updater: (state: unknown) => unknown) => {
112
- replaceAgent(updater(agent));
135
+ replaceAgent(updater(getAgent()));
113
136
  };
114
137
 
115
- // A chunk commits atomically — an op error must not leak a partial chunk.
116
- // Ops mirror one-by-one under ["agent"] so untouched slices keep identity.
138
+ // Ops commit one-by-one — an op error leaves the chunk's prefix applied.
117
139
  const applyChunkOps = (
118
140
  operations: readonly AssistantTransportStateOperation[],
119
141
  ) => {
120
- let next = agent;
121
- const translated: Statewire.Op[] = [];
122
142
  for (const operation of operations) {
123
- const op = translateStateOp(next, operation);
124
- next = applyOps(next, [op]).state;
125
- translated.push({ ...op, path: ["agent", ...op.path] });
143
+ const op = translateStateOp(getAgent(), operation);
144
+ if (op === undefined) continue;
145
+ ctl.apply([{ ...op, path: ["agent", ...op.path] }]);
126
146
  }
127
- agent = next;
128
- ctl.apply(translated);
129
147
  };
130
148
 
131
- let queueVersion = 0;
132
149
  const setQueue = (next: EntryQueue) => {
133
- queue = next;
150
+ s.queue = next;
134
151
  getOptions().queueCell.current = {
135
152
  queued: commandsOf(next.queued),
136
153
  inTransit: commandsOf(next.inTransit),
137
154
  };
138
155
  ctl.apply([
139
- { op: "replace", path: ["queueVersion"], value: ++queueVersion },
156
+ { op: "replace", path: ["queueVersion"], value: ++s.queueVersion },
140
157
  ]);
141
158
  };
142
159
 
143
160
  const takeQueuedIntoTransit = (): QueueEntry[] => {
144
- const { queued, inTransit } = queue;
161
+ const { queued, inTransit } = s.queue;
145
162
  if (queued.length === 0) return [];
146
163
  setQueue({ queued: [], inTransit: [...inTransit, ...queued] });
147
164
  return queued;
148
165
  };
149
166
 
150
167
  const drainQueue = (): EntryQueue => {
151
- const drained = queue;
168
+ const drained = s.queue;
152
169
  setQueue({ queued: [], inTransit: [] });
153
170
  return drained;
154
171
  };
@@ -156,15 +173,14 @@ const createHostLoop = (
156
173
  const buildRequestBody = async (
157
174
  o: HostOptions,
158
175
  commands: AssistantTransportCommand[],
176
+ runParentId: string | null | undefined,
159
177
  ) => {
160
- const runParentId = parentId;
161
- parentId = undefined;
162
178
  const bodyValue = typeof o.body === "function" ? await o.body() : o.body;
163
179
  const { modelContext, threadId } = o.getRunContext();
164
180
 
165
181
  const requestBody: Record<string, unknown> = {
166
182
  commands,
167
- state: agent,
183
+ state: getAgent(),
168
184
  system: modelContext.system,
169
185
  tools: modelContext.tools
170
186
  ? toToolsJSONSchema(modelContext.tools)
@@ -185,14 +201,35 @@ const createHostLoop = (
185
201
 
186
202
  const run = async (signal: AbortSignal) => {
187
203
  const o = getOptions();
188
- const isResume = resumeRequested;
189
- resumeRequested = false;
204
+ const isResume = s.resumeRequested;
205
+ s.resumeRequested = false;
190
206
  setReplaying(false);
191
- activeEntries = isResume ? [] : takeQueuedIntoTransit();
192
- if (activeEntries.length === 0 && !isResume) return;
207
+ s.activeEntries = isResume ? [] : takeQueuedIntoTransit();
208
+ if (s.activeEntries.length === 0 && !isResume && s.parentId === undefined)
209
+ return;
210
+
211
+ const runParentId = s.parentId;
212
+ s.parentId = undefined;
213
+ try {
214
+ await runRequest(o, isResume, runParentId, signal);
215
+ } catch (error) {
216
+ if (!signal.aborted && s.parentId === undefined) s.parentId = runParentId;
217
+ throw error;
218
+ }
219
+ };
193
220
 
221
+ const runRequest = async (
222
+ o: HostOptions,
223
+ isResume: boolean,
224
+ runParentId: string | null | undefined,
225
+ signal: AbortSignal,
226
+ ) => {
194
227
  const headers = await createRequestHeaders(o.headers);
195
- const requestBody = await buildRequestBody(o, commandsOf(activeEntries));
228
+ const requestBody = await buildRequestBody(
229
+ o,
230
+ commandsOf(s.activeEntries),
231
+ runParentId,
232
+ );
196
233
 
197
234
  const response = await fetch(isResume ? o.resumeApi! : o.api, {
198
235
  method: "POST",
@@ -211,17 +248,18 @@ const createHostLoop = (
211
248
  }
212
249
 
213
250
  const body = await createReplayBoundaryStream(response, setReplaying);
251
+ const strict = !isResume;
214
252
  const decoder =
215
253
  (o.protocol ?? "data-stream") === "assistant-transport"
216
- ? new AssistantTransportDecoder()
217
- : new DataStreamDecoder();
254
+ ? new AssistantTransportDecoder({ strict })
255
+ : new DataStreamDecoder({ strict });
218
256
 
219
257
  let streamError: string | undefined;
220
258
  let delivered = false;
221
259
 
222
260
  const markDelivered = () => {
223
- for (const entry of activeEntries) entry.execution.ack();
224
- setQueue({ ...queue, inTransit: [] });
261
+ for (const entry of s.activeEntries) entry.execution.ack();
262
+ setQueue({ ...s.queue, inTransit: [] });
225
263
  delivered = true;
226
264
  };
227
265
 
@@ -248,11 +286,11 @@ const createHostLoop = (
248
286
  if (!delivered) markDelivered();
249
287
 
250
288
  // commands that coalesced into a resume run must not starve
251
- if (isResume && queue.queued.length > 0) followUpRequested = true;
289
+ if (isResume && s.queue.queued.length > 0) s.followUpRequested = true;
252
290
  };
253
291
 
254
292
  const resolveActive = () => {
255
- for (const entry of activeEntries.splice(0)) entry.execution.resolve();
293
+ for (const entry of s.activeEntries.splice(0)) entry.execution.resolve();
256
294
  };
257
295
 
258
296
  const settleCancelled = () => {
@@ -287,9 +325,9 @@ const createHostLoop = (
287
325
  };
288
326
 
289
327
  const startRun = () => {
290
- followUpRequested = false;
328
+ s.followUpRequested = false;
291
329
  const ac = new AbortController();
292
- abortController = ac;
330
+ s.abortController = ac;
293
331
  setSending(true);
294
332
 
295
333
  // macrotask: every command admitted this turn coalesces into the take
@@ -298,21 +336,21 @@ const createHostLoop = (
298
336
  await run(ac.signal);
299
337
  resolveActive();
300
338
  } catch (error) {
301
- followUpRequested = false;
339
+ s.followUpRequested = false;
302
340
  // disposed means unmounted mid-run: the abort is ours, no callbacks
303
- if (!disposed) {
341
+ if (!s.disposed) {
304
342
  if (ac.signal.aborted) settleCancelled();
305
343
  else await settleFailed(error as Error);
306
344
  }
307
345
  } finally {
308
- if (disposed) {
309
- abortController = null;
346
+ if (s.disposed) {
347
+ s.abortController = null;
310
348
  } else {
311
349
  getOptions().onFinish?.();
312
- if (followUpRequested) {
350
+ if (s.followUpRequested) {
313
351
  startRun();
314
352
  } else {
315
- abortController = null;
353
+ s.abortController = null;
316
354
  setSending(false);
317
355
  }
318
356
  }
@@ -321,63 +359,49 @@ const createHostLoop = (
321
359
  };
322
360
 
323
361
  const schedule = () => {
324
- if (abortController) {
325
- followUpRequested = true;
362
+ if (s.abortController) {
363
+ s.followUpRequested = true;
326
364
  return;
327
365
  }
328
366
  startRun();
329
367
  };
330
368
 
331
- const handlers = {
369
+ return {
332
370
  send: (command: AssistantTransportCommand, opts?: SendOptions) => {
333
371
  const [execution, resolvers] = CommandExecution.withResolvers();
334
372
  setQueue({
335
- queued: [...queue.queued, { command, execution: resolvers }],
336
- inTransit: queue.inTransit,
373
+ queued: [...s.queue.queued, { command, execution: resolvers }],
374
+ inTransit: s.queue.inTransit,
337
375
  });
338
376
  if (opts?.schedule !== false) schedule();
339
377
  return execution;
340
378
  },
341
379
  setParentId: (id: string | null) => {
342
- parentId = id;
380
+ s.parentId = id;
343
381
  },
344
382
  cancel: () => {
345
- resumeRequested = false;
346
- followUpRequested = false;
347
- abortController?.abort();
383
+ s.resumeRequested = false;
384
+ s.followUpRequested = false;
385
+ s.abortController?.abort();
348
386
  },
349
387
  resume: () => {
350
388
  if (!getOptions().resumeApi)
351
389
  throw new Error("Must pass resumeApi to options to resume runs");
352
390
 
353
- resumeRequested = true;
391
+ s.resumeRequested = true;
354
392
  schedule();
355
393
  },
356
394
  reload: (id: string | null) => {
357
- parentId = id;
395
+ s.parentId = id;
358
396
  schedule();
359
397
  },
360
398
  importState: replaceAgent,
361
399
  };
362
-
363
- return {
364
- handlers,
365
- // Strict-mode effects run setup → cleanup → setup on the same instance;
366
- // arm undoes the cleanup's dispose.
367
- arm: () => {
368
- disposed = false;
369
- },
370
- dispose: () => {
371
- disposed = true;
372
- followUpRequested = false;
373
- abortController?.abort();
374
- },
375
- };
376
400
  };
377
401
 
378
402
  const useAssistantTransportHost = (
379
403
  options: HostOptions,
380
- ): StatewireServer.Transport<AssistantTransportHostState> => {
404
+ ): Statewire<AssistantTransportHostState, AssistantTransportHostCommands> => {
381
405
  const latestOptions = useRef(options);
382
406
  latestOptions.current = options;
383
407
 
@@ -389,25 +413,15 @@ const useAssistantTransportHost = (
389
413
  }));
390
414
  const emit = useStatewireEmit();
391
415
 
392
- const [loop] = useState(() =>
393
- createHostLoop(() => latestOptions.current, ctl),
416
+ const handlers = useHostLoop(
417
+ () => latestOptions.current,
418
+ ctl,
419
+ () => ctl.snapshot().agent,
394
420
  );
395
421
 
396
- useEffect(() => {
397
- loop.arm();
398
- return loop.dispose;
399
- }, [loop]);
400
-
401
- const commands = useStatewireCommands(loop.handlers);
422
+ const commands = useStatewireCommands(handlers);
402
423
 
403
424
  return { state, commands, emit };
404
425
  };
405
426
 
406
- export const AssistantTransportHost = resource(useAssistantTransportHost) as (
407
- options: HostOptions,
408
- ) => ResourceElement<
409
- StatewireServer.Transport<
410
- AssistantTransportHostState,
411
- AssistantTransportHostCommands
412
- >
413
- >;
427
+ export const AssistantTransportHost = resource(useAssistantTransportHost);
package/src/index.ts CHANGED
@@ -1,23 +1,27 @@
1
- export { AssistantTransportThread } from "./AssistantTransportThread";
1
+ import type * as types from "./types";
2
+ import { AssistantTransportThread } from "./AssistantTransportThread";
3
+
4
+ export { AssistantTransportThread };
5
+ export { StatewireThread } from "./StatewireThread";
2
6
  export {
3
7
  useAssistantTransportSendCommand,
4
8
  useAssistantTransportState,
5
9
  } from "./hooks";
6
- export { REPLAY_CONTENT_LENGTH_HEADER } from "./replayBoundaryStream";
7
- export type {
8
- AssistantTransportOptions,
9
- AssistantTransportCommand,
10
- AssistantTransportProtocol,
11
- AssistantTransportState,
12
- AssistantTransportConnectionMetadata,
13
- AssistantTransportStateConverter,
14
- AddMessageCommand,
15
- AddToolResultCommand,
16
- SendCommandsRequestBody,
17
- UserMessage,
18
- AssistantMessage,
19
- UserMessagePart,
20
- TextPart,
21
- ImagePart,
22
- HeadersValue,
23
- } from "./types";
10
+
11
+ export namespace AssistantTransportThread {
12
+ export type Options<T> = types.AssistantTransportOptions<T>;
13
+ export type Command = types.AssistantTransportCommand;
14
+ export type Protocol = types.AssistantTransportProtocol;
15
+ export type State = types.AssistantTransportState;
16
+ export type ConnectionMetadata = types.AssistantTransportConnectionMetadata;
17
+ export type StateConverter<T> = types.AssistantTransportStateConverter<T>;
18
+ export type AddMessageCommand = types.AddMessageCommand;
19
+ export type AddToolResultCommand = types.AddToolResultCommand;
20
+ export type SendCommandsRequestBody = types.SendCommandsRequestBody;
21
+ export type UserMessage = types.UserMessage;
22
+ export type AssistantMessage = types.AssistantMessage;
23
+ export type UserMessagePart = types.UserMessagePart;
24
+ export type TextPart = types.TextPart;
25
+ export type ImagePart = types.ImagePart;
26
+ export type HeadersValue = types.HeadersValue;
27
+ }
@@ -6,8 +6,14 @@ const parseReplayContentLength = (headers: Headers): number => {
6
6
  const raw = headers.get(REPLAY_CONTENT_LENGTH_HEADER);
7
7
  if (raw == null) return 0;
8
8
 
9
- const boundary = Number(raw);
10
- return Number.isSafeInteger(boundary) && boundary > 0 ? boundary : 0;
9
+ const trimmed = raw.trim();
10
+ const boundary = Number(trimmed);
11
+ if (!/^\d+$/.test(trimmed) || !Number.isSafeInteger(boundary)) {
12
+ throw new Error(
13
+ `statewire: invalid ${REPLAY_CONTENT_LENGTH_HEADER} header "${raw}"`,
14
+ );
15
+ }
16
+ return boundary;
11
17
  };
12
18
 
13
19
  // Gates replay bytes until isReplaying:true renders, then releases live bytes after isReplaying:false renders.
@@ -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
  };