@assistant-ui/react-statewire 0.29.1 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -641,21 +641,14 @@ describe("StatewireThread", () => {
641
641
  });
642
642
 
643
643
  describe("contextSync: command-send", () => {
644
- const contextValueOf = (command: {
645
- protocol: string;
646
- method: string;
647
- params: unknown[];
648
- }) => {
649
- expect([command.protocol, command.method]).toEqual([
650
- "default/context",
651
- "set",
652
- ]);
653
- return command.params[0] as Record<string, unknown>;
644
+ const contextValueOf = (entry: { protocol: string; value: unknown }) => {
645
+ expect(entry.protocol).toBe("default");
646
+ return entry.value as Record<string, unknown>;
654
647
  };
655
648
 
656
649
  it("sends the ambient model context on connect and on every change", async () => {
657
650
  const mock = createMockTransport<ServerState>(INITIAL_STATE, "default", {
658
- ephemeral: ["context"],
651
+ ephemeral: [],
659
652
  });
660
653
  const { aui } = mountThread({
661
654
  transport: mock.transport,
@@ -663,28 +656,28 @@ describe("StatewireThread", () => {
663
656
  contextSync: "command-send",
664
657
  });
665
658
 
666
- await waitFor(() => expect(mock.commands).toHaveLength(1));
667
- const initial = contextValueOf(mock.commands[0]!);
659
+ await waitFor(() => expect(mock.contexts).toHaveLength(1));
660
+ const initial = contextValueOf(mock.contexts[0]!);
668
661
  expect(initial["system"]).toBeUndefined();
669
662
 
670
663
  aui()
671
664
  .modelContext()
672
665
  .register({ getModelContext: () => ({ system: "be nice" }) });
673
666
 
674
- await waitFor(() => expect(mock.commands).toHaveLength(2));
675
- expect(contextValueOf(mock.commands[1]!)["system"]).toBe("be nice");
667
+ await waitFor(() => expect(mock.contexts).toHaveLength(2));
668
+ expect(contextValueOf(mock.contexts[1]!)["system"]).toBe("be nice");
676
669
  });
677
670
 
678
671
  it("skips resends while the serialized context is unchanged", async () => {
679
672
  const mock = createMockTransport<ServerState>(INITIAL_STATE, "default", {
680
- ephemeral: ["context"],
673
+ ephemeral: [],
681
674
  });
682
675
  const { aui } = mountThread({
683
676
  transport: mock.transport,
684
677
  converter,
685
678
  contextSync: "command-send",
686
679
  });
687
- await waitFor(() => expect(mock.commands).toHaveLength(1));
680
+ await waitFor(() => expect(mock.contexts).toHaveLength(1));
688
681
 
689
682
  // notifies subscribers without changing the merged context
690
683
  aui()
@@ -694,43 +687,81 @@ describe("StatewireThread", () => {
694
687
  .modelContext()
695
688
  .register({ getModelContext: () => ({ system: "be nice" }) });
696
689
 
697
- await waitFor(() => expect(mock.commands).toHaveLength(2));
698
- expect(contextValueOf(mock.commands[1]!)["system"]).toBe("be nice");
690
+ await waitFor(() => expect(mock.contexts).toHaveLength(2));
691
+ expect(contextValueOf(mock.contexts[1]!)["system"]).toBe("be nice");
699
692
  });
700
693
 
701
- it("keeps a set the hello did not negotiate off the wire and re-sends it once the lane is negotiated", async () => {
702
- const lanes: string[] = [];
703
- const mock = createMockTransport<ServerState>(INITIAL_STATE, "default", {
704
- ephemeral: lanes,
705
- });
694
+ it("restores native context on reconnect without an ephemeral command lane", async () => {
695
+ const mock = createMockTransport<ServerState>(INITIAL_STATE);
706
696
  const { aui } = mountThread({
707
697
  transport: mock.transport,
708
698
  converter,
709
699
  contextSync: "command-send",
710
700
  });
711
- await waitFor(() => expect(threadStatus(aui())).toBe("ready"));
712
- await new Promise((r) => setTimeout(r, 20));
713
- expect(mock.commands).toEqual([]);
714
-
715
- lanes.push("context");
701
+ await waitFor(() => expect(mock.contexts).toHaveLength(1));
702
+ aui()
703
+ .modelContext()
704
+ .register({ getModelContext: () => ({ system: "be nice" }) });
705
+ await waitFor(() => expect(mock.contexts).toHaveLength(2));
716
706
  act(() =>
717
707
  asStatewireExtras(aui().thread().getState().extras).reconnect(),
718
708
  );
719
- await waitFor(() => expect(mock.attached).toBe(true));
720
- await new Promise((r) => setTimeout(r, 20));
721
- // notifies subscribers without changing the merged context
722
- aui()
709
+ await waitFor(() => expect(mock.contexts).toHaveLength(3));
710
+ expect(contextValueOf(mock.contexts[2]!)).toEqual({ system: "be nice" });
711
+ expect(mock.commands).toEqual([]);
712
+ });
713
+
714
+ it("holds run sends while the model context is rejected, until a valid one replaces it", async () => {
715
+ const mock = createMockTransport<ServerState>(INITIAL_STATE);
716
+ const errors: Error[] = [];
717
+ const { aui } = mountThread({
718
+ transport: mock.transport,
719
+ converter,
720
+ contextSync: "command-send",
721
+ onError: (error) => {
722
+ errors.push(error);
723
+ },
724
+ });
725
+ await waitFor(() => expect(mock.contexts).toHaveLength(1));
726
+
727
+ const unregister = aui()
723
728
  .modelContext()
724
- .register({ getModelContext: () => ({}) });
729
+ .register({ getModelContext: () => ({ system: "x".repeat(70_000) }) });
730
+ expect(errors).toHaveLength(1);
731
+ expect(errors[0]!.message).toContain("context entry too large");
732
+
733
+ aui().thread().composer().setText("hello");
734
+ aui().thread().composer().send();
735
+ await waitFor(() =>
736
+ expect(aui().thread().composer().getState().text).toBe("hello"),
737
+ );
738
+ expect(errors).toHaveLength(2);
739
+ expect(errors[1]!.cause).toBe(errors[0]);
740
+ await new Promise((r) => setTimeout(r, 20));
741
+ expect(mock.commands).toEqual([]);
742
+ expect(mock.contexts).toHaveLength(1);
743
+
744
+ unregister();
745
+ await waitFor(() => expect(mock.contexts).toHaveLength(2));
746
+ expect(contextValueOf(mock.contexts[1]!)).toEqual({});
725
747
 
726
- await waitFor(() => expect(mock.commands).toHaveLength(1));
727
- expect(contextValueOf(mock.commands[0]!)).toEqual({});
748
+ aui().thread().composer().send();
749
+ await waitFor(() =>
750
+ expect(mock.commands).toMatchObject([
751
+ {
752
+ method: "run/enqueue",
753
+ params: [{ message: { parts: [{ type: "text", text: "hello" }] } }],
754
+ },
755
+ ]),
756
+ );
757
+ expect(errors).toHaveLength(2);
728
758
  });
729
759
 
730
760
  it("stays off the wire without the option", async () => {
731
761
  const mock = createMockTransport<ServerState>(INITIAL_STATE);
732
762
  const { aui } = mountThread({ transport: mock.transport, converter });
733
763
  await waitFor(() => expect(threadStatus(aui())).toBe("ready"));
764
+ expect(mock.contexts).toEqual([]);
734
765
  expect(mock.commands).toEqual([]);
735
766
  });
736
767
  });
@@ -978,6 +1009,87 @@ describe("StatewireThread", () => {
978
1009
  );
979
1010
  });
980
1011
 
1012
+ it("keeps settled messages' state across streamed tokens and targets the latest live run", async () => {
1013
+ const streaming = (text: string, run: ServerRun): ServerState => ({
1014
+ messages: [
1015
+ { id: "h1", role: "user", text: "first" },
1016
+ { id: "a1", role: "assistant", text: "settled" },
1017
+ { id: "h2", role: "user", text: "second" },
1018
+ { id: "a2", role: "assistant", text },
1019
+ ],
1020
+ status: "running",
1021
+ runs: [run],
1022
+ });
1023
+ const run1 = runEntry({ status: "running", runId: "run-1" });
1024
+ const mock = createMockTransport<ServerState>(streaming("", run1));
1025
+ // keeps unchanged messages' identity, as a production converter does
1026
+ const converted = new Map<string, ReturnType<typeof toThreadMessage>>();
1027
+ const { aui } = mountThread({
1028
+ transport: mock.transport,
1029
+ converter: (state) => ({
1030
+ messages: state.messages.map((m) => {
1031
+ const key = JSON.stringify(m);
1032
+ if (!converted.has(key)) converted.set(key, toThreadMessage(m));
1033
+ return converted.get(key)!;
1034
+ }),
1035
+ }),
1036
+ capabilities: { edit: true },
1037
+ });
1038
+ await waitFor(() => expect(threadTexts(aui)).toHaveLength(4));
1039
+ const rows = () =>
1040
+ [0, 1, 2, 3].map((index) =>
1041
+ aui().thread().message({ index }).getState(),
1042
+ );
1043
+
1044
+ const before = rows();
1045
+ const token = (text: string) =>
1046
+ mock.sendEnvelope({
1047
+ ops: [{ op: "replace", path: ["messages", 3, "text"], value: text }],
1048
+ });
1049
+ await token("Hel");
1050
+ await token("Hello");
1051
+ await waitFor(() => expect(threadTexts(aui)[3]).toBe("Hello"));
1052
+ const after = rows();
1053
+ for (const index of [0, 1, 2]) expect(after[index]).toBe(before[index]);
1054
+ expect(after[3]).not.toBe(before[3]);
1055
+
1056
+ await mock.setState(
1057
+ streaming(
1058
+ "Hello",
1059
+ runEntry({
1060
+ status: "running",
1061
+ runId: "run-2",
1062
+ queue: [textEntry("q1", "queued")],
1063
+ }),
1064
+ ),
1065
+ );
1066
+ await waitFor(() =>
1067
+ expect(aui().thread().composer().getState().queue).toHaveLength(1),
1068
+ );
1069
+ const sent = () =>
1070
+ mock.commands.map(({ method, params }) => ({
1071
+ method,
1072
+ runId: (params[0] as { runId: string }).runId,
1073
+ }));
1074
+
1075
+ aui().thread().composer().setText("steer me");
1076
+ aui().thread().composer().send();
1077
+ aui().thread().composer().queueItem({ id: "q1" }).steer();
1078
+ const composer = aui().thread().message({ id: "h1" }).composer();
1079
+ composer.beginEdit();
1080
+ await waitFor(() => expect(composer.getState().isEditing).toBe(true));
1081
+ composer.setText("better first");
1082
+ composer.send();
1083
+
1084
+ await waitFor(() =>
1085
+ expect(sent()).toEqual([
1086
+ { method: "run/steer", runId: "run-2" },
1087
+ { method: "run/steer", runId: "run-2" },
1088
+ { method: "run/edit", runId: "run-2" },
1089
+ ]),
1090
+ );
1091
+ });
1092
+
981
1093
  it("dispatches run/continue from resumeRun under the continue capability", async () => {
982
1094
  const server = createServer();
983
1095
  const { aui } = mountThread({
@@ -156,6 +156,7 @@ const useStatewireThread = (
156
156
  connection,
157
157
  documents,
158
158
  invoke,
159
+ setContext,
159
160
  isBusy,
160
161
  failed,
161
162
  discardFailed,
@@ -202,45 +203,58 @@ const useStatewireThread = (
202
203
  }, [failed, discardFailed]);
203
204
 
204
205
  const clientRef = useAssistantClientRef();
205
- const invokeRef = useRef(invoke);
206
- invokeRef.current = invoke;
207
- const [syncState] = useState(() => ({ lastSent: undefined as unknown }));
206
+ const contextRef = useRef(setContext);
207
+ contextRef.current = setContext;
208
+ const contextFailure = useRef<Error | undefined>(undefined);
208
209
  const { contextSync } = options;
209
- const contextProtocol = `${options.protocol ?? DEFAULT_PROTOCOL}/context`;
210
- // The context document dies with its attach: resend on every connect.
211
- const connected = connection.status === "connected";
210
+ const contextProtocol = options.protocol ?? DEFAULT_PROTOCOL;
212
211
  useEffect(() => {
213
212
  if (contextSync === undefined) return;
214
- if (!connected) {
215
- syncState.lastSent = undefined;
216
- return;
217
- }
218
213
  const modelContext = (clientRef.current ?? clientRef.parent).modelContext();
214
+ let lastSent: string | undefined;
219
215
  const send = () => {
220
216
  const value = ambientContextOf(modelContext.getModelContext());
221
217
  const key = JSON.stringify(value);
222
- if (key === syncState.lastSent) return;
223
- syncState.lastSent = key;
224
- const forget = () => {
225
- if (syncState.lastSent === key) syncState.lastSent = undefined;
226
- };
218
+ if (key === lastSent) return;
227
219
  try {
228
- invokeRef.current(contextProtocol, "set", [value]).catch(forget);
229
- } catch {
230
- forget();
220
+ contextRef.current(contextProtocol, value);
221
+ } catch (error) {
222
+ contextFailure.current = error as Error;
223
+ lastSent = undefined;
224
+ latest.current.onError?.(error as Error);
225
+ return;
231
226
  }
227
+ contextFailure.current = undefined;
228
+ lastSent = key;
232
229
  };
233
- send();
234
- if (!modelContext.subscribe) {
230
+ if (!modelContext.subscribe)
235
231
  throw new Error(
236
232
  "statewire: contextSync requires a subscribable model context",
237
233
  );
238
- }
234
+ send();
239
235
  return modelContext.subscribe(send);
240
- }, [contextSync, connected, contextProtocol, clientRef, syncState]);
236
+ }, [contextSync, contextProtocol, clientRef]);
237
+
238
+ const [heldByContext] = useState(
239
+ () =>
240
+ (command: StatewireThread.Command): Error | undefined =>
241
+ contextFailure.current !== undefined &&
242
+ (command.type === "run/enqueue" ||
243
+ command.type === "run/steer" ||
244
+ command.type === "run/edit")
245
+ ? new Error("statewire: the model context was rejected", {
246
+ cause: contextFailure.current,
247
+ })
248
+ : undefined,
249
+ );
241
250
 
242
251
  const dispatch = useCallback(
243
252
  (command: StatewireThread.Command) => {
253
+ const held = heldByContext(command);
254
+ if (held !== undefined) {
255
+ latest.current.onError?.(held);
256
+ return Promise.reject(held);
257
+ }
244
258
  setPending((prev) => [...prev, command]);
245
259
  const settled = commands[command.type]!(command);
246
260
  settled.catch((error: Error) => {
@@ -249,7 +263,7 @@ const useStatewireThread = (
249
263
  });
250
264
  return settled;
251
265
  },
252
- [commands, retire],
266
+ [commands, retire, heldByContext],
253
267
  );
254
268
 
255
269
  const threadRef = useRef<ClientOutput<"thread"> | null>(null);
@@ -382,17 +396,22 @@ const useStatewireThread = (
382
396
  const messages = converted.messages;
383
397
  const liveRunId = runs.runId;
384
398
 
399
+ // ExternalThread rebuilds every message's state when `queue` or a message
400
+ // handler changes identity, so these read the latest pass instead of closing over it.
401
+ const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;
402
+ const pass = { messages, runId: liveRunId, inputRequests, dispatch };
403
+ const live = useRef(pass);
404
+ live.current = pass;
385
405
  const queue = useMemo(
386
406
  () =>
387
407
  createRunQueueAdapter(
388
- messages,
389
- liveRunId,
408
+ () => live.current,
390
409
  runs.queue,
391
410
  runs.steerQueue,
392
411
  dispatch,
393
412
  dispatchSend,
394
413
  ),
395
- [messages, liveRunId, runs, dispatch, dispatchSend],
414
+ [runs.queue, runs.steerQueue, dispatch, dispatchSend],
396
415
  );
397
416
 
398
417
  const branches = useMemo(
@@ -400,8 +419,6 @@ const useStatewireThread = (
400
419
  [messages, dispatch],
401
420
  );
402
421
 
403
- const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;
404
-
405
422
  const extras = useMemo((): StatewireThread.Extras => {
406
423
  const takeFailed = (messageId: string): StatewireClient.FailedCommand => {
407
424
  const entry = failed.find(
@@ -431,6 +448,8 @@ const useStatewireThread = (
431
448
  liveRunId,
432
449
  failedRunCommand(entry)!,
433
450
  );
451
+ const held = heldByContext(command);
452
+ if (held !== undefined) throw held;
434
453
  retrying.current.add(messageId);
435
454
  const release = () => {
436
455
  retrying.current.delete(messageId);
@@ -454,6 +473,7 @@ const useStatewireThread = (
454
473
  };
455
474
  }, [
456
475
  dispatch,
476
+ heldByContext,
457
477
  connection,
458
478
  documents,
459
479
  invoke,
@@ -489,9 +509,22 @@ const useStatewireThread = (
489
509
  dispatch(resolveReloadCommand(messages, parentId, liveRunId));
490
510
  };
491
511
 
492
- const handleEdit = (message: AppendMessage) => {
493
- dispatch(resolveEditCommand(messages, message, liveRunId));
494
- };
512
+ const [messageHandlers] = useState(() => ({
513
+ onEdit: (message: AppendMessage) => {
514
+ const { messages, runId, dispatch } = live.current;
515
+ dispatch(resolveEditCommand(messages, message, runId));
516
+ },
517
+ onAddToolResult: (toolOptions: AddToolResultOptions) => {
518
+ const { inputRequests, runId, dispatch } = live.current;
519
+ return dispatch(
520
+ resolveToolResultInput(inputRequests, toolOptions, runId),
521
+ );
522
+ },
523
+ onRespondToToolApproval: (approval: RespondToToolApprovalOptions) => {
524
+ const { inputRequests, runId, dispatch } = live.current;
525
+ return dispatch(resolveToolApprovalInput(inputRequests, approval, runId));
526
+ },
527
+ }));
495
528
 
496
529
  const thread = useResource(
497
530
  ExternalThread({
@@ -504,7 +537,7 @@ const useStatewireThread = (
504
537
  feedbackAdapter: options.adapters?.feedback,
505
538
  onNew: handleAppend,
506
539
  queue,
507
- ...(options.capabilities?.edit && { onEdit: handleEdit }),
540
+ ...(options.capabilities?.edit && { onEdit: messageHandlers.onEdit }),
508
541
  ...(options.capabilities?.continue && {
509
542
  onResume: () =>
510
543
  dispatch({
@@ -514,10 +547,8 @@ const useStatewireThread = (
514
547
  }),
515
548
  ...(options.capabilities?.reload && { onReload: handleReload }),
516
549
  ...(options.capabilities?.unstable_switchBranch && { branches }),
517
- onAddToolResult: (toolOptions: AddToolResultOptions) =>
518
- dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),
519
- onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>
520
- dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),
550
+ onAddToolResult: messageHandlers.onAddToolResult,
551
+ onRespondToToolApproval: messageHandlers.onRespondToToolApproval,
521
552
  onCancel: () => {
522
553
  const payload = latest.current.stopPayload?.();
523
554
  if (
@@ -971,8 +1002,8 @@ export namespace StatewireThread {
971
1002
  materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;
972
1003
  /**
973
1004
  * "command-send" mirrors the client's ambient model context (system,
974
- * tools, callSettings, config) to the server over the command channel —
975
- * on connect and whenever it changes. Requires a remote transport.
1005
+ * tools, callSettings, config) to native protocol context, restored on
1006
+ * each attachment and updated whenever it changes.
976
1007
  */
977
1008
  contextSync?: "command-send" | undefined;
978
1009
  /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */