@assistant-ui/react-statewire 0.28.1 → 0.29.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.
@@ -1,4 +1,11 @@
1
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
1
+ import {
2
+ useCallback,
3
+ useEffect,
4
+ useMemo,
5
+ useRef,
6
+ useState,
7
+ useSyncExternalStore,
8
+ } from "react";
2
9
  import {
3
10
  resource,
4
11
  useResource,
@@ -27,8 +34,8 @@ import type {
27
34
  } from "@assistant-ui/core";
28
35
  import { toToolsJSONSchema } from "assistant-stream";
29
36
  import type { ReadonlyJSONValue } from "assistant-stream/utils";
30
- import { useStatewire } from "statewire";
31
- import type { Statewire, StatewireClient } from "statewire";
37
+ import { DEFAULT_PROTOCOL, useStatewire } from "statewire";
38
+ import type { Statewire, StatewireClient, StatewireDocuments } from "statewire";
32
39
  import {
33
40
  createBranchCommandAdapter,
34
41
  createRunQueueAdapter,
@@ -46,6 +53,10 @@ import { runsOptimistic } from "./runsOptimistic";
46
53
 
47
54
  type AnyCommands = Record<string, (...args: any[]) => unknown>;
48
55
 
56
+ const NO_DOCUMENTS: ReadonlyMap<number, StatewireDocuments.Document> =
57
+ new Map();
58
+ const noopSubscribe = () => () => {};
59
+
49
60
  export const symbolStatewireExtras = Symbol("statewire-extras");
50
61
 
51
62
  export const asStatewireExtras = (extras: unknown): StatewireThread.Extras => {
@@ -143,7 +154,8 @@ const useStatewireThread = (
143
154
  state,
144
155
  commands,
145
156
  connection,
146
- setContext,
157
+ documents,
158
+ invoke,
147
159
  isBusy,
148
160
  failed,
149
161
  discardFailed,
@@ -190,19 +202,33 @@ const useStatewireThread = (
190
202
  }, [failed, discardFailed]);
191
203
 
192
204
  const clientRef = useAssistantClientRef();
193
- const setContextRef = useRef(setContext);
194
- setContextRef.current = setContext;
205
+ const invokeRef = useRef(invoke);
206
+ invokeRef.current = invoke;
195
207
  const [syncState] = useState(() => ({ lastSent: undefined as unknown }));
196
208
  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";
197
212
  useEffect(() => {
198
213
  if (contextSync === undefined) return;
214
+ if (!connected) {
215
+ syncState.lastSent = undefined;
216
+ return;
217
+ }
199
218
  const modelContext = (clientRef.current ?? clientRef.parent).modelContext();
200
219
  const send = () => {
201
220
  const value = ambientContextOf(modelContext.getModelContext());
202
221
  const key = JSON.stringify(value);
203
222
  if (key === syncState.lastSent) return;
204
223
  syncState.lastSent = key;
205
- setContextRef.current(value);
224
+ const forget = () => {
225
+ if (syncState.lastSent === key) syncState.lastSent = undefined;
226
+ };
227
+ try {
228
+ invokeRef.current(contextProtocol, "set", [value]).catch(forget);
229
+ } catch {
230
+ forget();
231
+ }
206
232
  };
207
233
  send();
208
234
  if (!modelContext.subscribe) {
@@ -211,7 +237,7 @@ const useStatewireThread = (
211
237
  );
212
238
  }
213
239
  return modelContext.subscribe(send);
214
- }, [contextSync, clientRef, syncState]);
240
+ }, [contextSync, connected, contextProtocol, clientRef, syncState]);
215
241
 
216
242
  const dispatch = useCallback(
217
243
  (command: StatewireThread.Command) => {
@@ -305,6 +331,9 @@ const useStatewireThread = (
305
331
  : {
306
332
  runId: entry.runId,
307
333
  ...(entry.epoch !== undefined && { epoch: entry.epoch }),
334
+ ...(entry.stopReason !== undefined && {
335
+ stopReason: entry.stopReason,
336
+ }),
308
337
  queue: entry.queue,
309
338
  steerQueue: entry.steerQueue,
310
339
  ...(entry.dispatching !== undefined && {
@@ -327,14 +356,22 @@ const useStatewireThread = (
327
356
  }, [state, connection, failed]);
328
357
 
329
358
  const { converter } = options;
359
+ const mounted = useSyncExternalStore(
360
+ documents?.subscribe ?? noopSubscribe,
361
+ () => documents?.list() ?? NO_DOCUMENTS,
362
+ () => documents?.list() ?? NO_DOCUMENTS,
363
+ );
330
364
  const metadata = useMemo(
331
365
  (): StatewireThread.ConnectionMetadata => ({
332
366
  pendingCommands: [...pending],
333
367
  isSending: pending.length > 0,
334
368
  connection,
335
369
  runs,
370
+ documents,
371
+ mounted,
372
+ invoke,
336
373
  }),
337
- [pending, connection, runs],
374
+ [pending, connection, runs, documents, mounted, invoke],
338
375
  );
339
376
  const converted = useMemo(
340
377
  (): StatewireThread.State => converter(state, metadata),
@@ -378,7 +415,10 @@ const useStatewireThread = (
378
415
  [symbolStatewireExtras]: true,
379
416
  sendCommand: dispatch,
380
417
  reconnect: connection.reconnect,
381
- state,
418
+ connection,
419
+ documents,
420
+ invoke,
421
+ state: converted.state === undefined ? state : converted.state,
382
422
  status,
383
423
  isBusy,
384
424
  inputRequests,
@@ -414,8 +454,11 @@ const useStatewireThread = (
414
454
  };
415
455
  }, [
416
456
  dispatch,
417
- connection.reconnect,
457
+ connection,
458
+ documents,
459
+ invoke,
418
460
  state,
461
+ converted.state,
419
462
  status,
420
463
  isBusy,
421
464
  inputRequests,
@@ -587,6 +630,16 @@ export namespace StatewireThread {
587
630
  /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */
588
631
  sendCommand: (command: Command) => Promise<unknown>;
589
632
  reconnect: () => void;
633
+ connection: StatewireClient.ConnectionState;
634
+ /** The mounted documents, or `undefined` on a transport without documents. */
635
+ documents: StatewireDocuments.Source | undefined;
636
+ /** Sends a statement on a negotiated protocol lane. */
637
+ invoke: (
638
+ protocol: string,
639
+ method: string,
640
+ params: readonly unknown[],
641
+ ) => Promise<unknown>;
642
+ /** The converter's `state` when it returns one, else the replicated state. */
590
643
  state: unknown;
591
644
  status: ThreadStatus;
592
645
  /** Negation of the server's broadcast idle level (a transport without idle is always busy). */
@@ -740,6 +793,7 @@ export namespace StatewireThread {
740
793
  export type RunQueueItem = {
741
794
  readonly id: string;
742
795
  readonly parts: readonly (TextPart | FilePart)[];
796
+ readonly metadata?: Record<string, unknown>;
743
797
  };
744
798
 
745
799
  /** Run subsystem status replicated by the host. */
@@ -807,6 +861,8 @@ export namespace StatewireThread {
807
861
  readonly runId: string | null;
808
862
  /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */
809
863
  readonly epoch?: number;
864
+ /** The reason carried by `run/stop`; persists through error/stop, cleared at the next dispatch. */
865
+ readonly stopReason?: string | null;
810
866
  readonly status: RunStatus;
811
867
  readonly queue: readonly RunsQueueEntry[];
812
868
  readonly steerQueue: readonly RunsQueueEntry[];
@@ -843,6 +899,8 @@ export namespace StatewireThread {
843
899
  readonly runId: string | null;
844
900
  /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */
845
901
  readonly epoch?: number;
902
+ /** The reason carried by `run/stop`; persists through error/stop, cleared at the next dispatch. */
903
+ readonly stopReason?: string | null;
846
904
  readonly queue: readonly RunsQueueEntry[];
847
905
  readonly steerQueue: readonly RunsQueueEntry[];
848
906
  /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */
@@ -865,9 +923,17 @@ export namespace StatewireThread {
865
923
  connection: StatewireClient.ConnectionState;
866
924
  /** The typed runs read. */
867
925
  runs: Runs;
926
+ documents: StatewireDocuments.Source | undefined;
927
+ /** The mounted documents as of this pass; a new map whenever one changes. */
928
+ mounted: ReadonlyMap<number, StatewireDocuments.Document>;
929
+ invoke: (
930
+ protocol: string,
931
+ method: string,
932
+ params: readonly unknown[],
933
+ ) => Promise<unknown>;
868
934
  };
869
935
 
870
- /** Converter output: app-owned keys only — the lib projects the run mounts itself. */
936
+ /** Converter output: app-owned keys only — the lib projects the run mounts itself; `state` replaces the replicated state on the extras and thread. */
871
937
  export type State = {
872
938
  readonly messages: readonly ThreadMessage[];
873
939
  readonly state?: ReadonlyJSONValue;
@@ -174,21 +174,24 @@ describe("LocalStorageSession", () => {
174
174
 
175
175
  const record = {
176
176
  clientId: "c-1",
177
- nextSeq: 3,
178
- commands: [
179
- {
180
- seq: 2,
181
- protocol: "default",
182
- method: "run/steer",
183
- params: [{ text: "hi" }],
184
- meta: { requestId: "r-2" },
177
+ lanes: {
178
+ default: {
179
+ nextSeq: 3,
180
+ commands: [
181
+ {
182
+ seq: 2,
183
+ method: "run/steer",
184
+ params: [{ text: "hi" }],
185
+ meta: { requestId: "r-2" },
186
+ },
187
+ ],
185
188
  },
186
- ],
189
+ },
187
190
  };
188
191
  root.getValue().save(record);
189
192
  expect(JSON.parse(localStorage.getItem(`${SESSION_PREFIX}t1`)!)).toEqual({
190
193
  ...record,
191
- statewireStorageVersion: 2,
194
+ statewireStorageVersion: 3,
192
195
  savedAt: expect.any(Number),
193
196
  });
194
197
  expect(root.getValue().load()).toEqual(record);
@@ -239,11 +242,7 @@ describe("LocalStorageSession", () => {
239
242
 
240
243
  it("derives the storage key through the key callback", () => {
241
244
  const root = mountSession({ threadId: "t1", key: (id) => `user-42:${id}` });
242
- root.getValue().save({
243
- clientId: "c-1",
244
- nextSeq: 1,
245
- commands: [],
246
- });
245
+ root.getValue().save({ clientId: "c-1", lanes: {} });
247
246
  expect(localStorage.getItem(`${SESSION_PREFIX}user-42:t1`)).not.toBeNull();
248
247
  expect(localStorage.getItem(`${SESSION_PREFIX}t1`)).toBeNull();
249
248
  root.unmount();
@@ -188,7 +188,7 @@ const useLocalStorageSession = ({
188
188
  threadId,
189
189
  migrate,
190
190
  key = (id) => id,
191
- legacyProtocol,
191
+ protocol,
192
192
  retention,
193
193
  onError,
194
194
  }: LocalStorageSession.Options): StatewireClient.SessionStorage => {
@@ -222,7 +222,7 @@ const useLocalStorageSession = ({
222
222
  key: key(threadId),
223
223
  namespace: SESSION_PREFIX,
224
224
  ...(migrate === undefined ? {} : { migrate }),
225
- ...(legacyProtocol === undefined ? {} : { legacyProtocol }),
225
+ ...(protocol === undefined ? {} : { protocol }),
226
226
  ...(retention === undefined ? {} : { retention }),
227
227
  ...(onError === undefined ? {} : { onError }),
228
228
  }),
@@ -248,7 +248,7 @@ export const LocalStorageSession = resource(useLocalStorageSession);
248
248
 
249
249
  export namespace LocalStorageSession {
250
250
  export type Options = {
251
- legacyProtocol?: KeyValueSessionStorage.Options["legacyProtocol"];
251
+ protocol?: KeyValueSessionStorage.Options["protocol"];
252
252
  retention?: KeyValueSessionStorage.Options["retention"];
253
253
  onError?: KeyValueSessionStorage.Options["onError"];
254
254
  /** Upgrade incompatible queued commands, or return null to discard the saved session. */
@@ -0,0 +1,31 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import type { AppendMessage } from "@assistant-ui/core";
3
+ import { toWireMessage } from "./runCommands";
4
+
5
+ const append = (metadata?: AppendMessage["metadata"]): AppendMessage =>
6
+ ({
7
+ role: "user",
8
+ content: [{ type: "text", text: "hi" }],
9
+ attachments: [],
10
+ createdAt: new Date(0),
11
+ parentId: null,
12
+ sourceId: null,
13
+ runConfig: undefined,
14
+ ...(metadata !== undefined && { metadata }),
15
+ }) as unknown as AppendMessage;
16
+
17
+ describe("toWireMessage", () => {
18
+ it("copies metadata.custom onto the wire message", () => {
19
+ expect(toWireMessage(append({ custom: { source: "tab" } }), "m1")).toEqual({
20
+ id: "m1",
21
+ role: "user",
22
+ parts: [{ type: "text", text: "hi" }],
23
+ metadata: { source: "tab" },
24
+ });
25
+ expect(toWireMessage(append(), "m1")).toEqual({
26
+ id: "m1",
27
+ role: "user",
28
+ parts: [{ type: "text", text: "hi" }],
29
+ });
30
+ });
31
+ });
@@ -43,7 +43,14 @@ export const toWireMessage = (
43
43
  ];
44
44
  if (parts.length === 0)
45
45
  throw new Error("statewire: cannot send an empty message");
46
- return { id, role: "user", parts };
46
+ return {
47
+ id,
48
+ role: "user",
49
+ parts,
50
+ ...(message.metadata?.custom !== undefined && {
51
+ metadata: JSON.parse(JSON.stringify(message.metadata.custom)),
52
+ }),
53
+ };
47
54
  };
48
55
 
49
56
  const toQueueItemState = (item: StatewireThread.RunQueueItem) => ({