@assistant-ui/react-statewire 0.29.0 → 0.30.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.
@@ -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,
@@ -28,7 +35,7 @@ import type {
28
35
  import { toToolsJSONSchema } from "assistant-stream";
29
36
  import type { ReadonlyJSONValue } from "assistant-stream/utils";
30
37
  import { DEFAULT_PROTOCOL, useStatewire } from "statewire";
31
- import type { Statewire, StatewireClient } 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 => {
@@ -139,34 +150,43 @@ const useStatewireThread = (
139
150
  ),
140
151
  );
141
152
 
142
- const { state, commands, connection, invoke, isBusy, failed, discardFailed } =
143
- useStatewire<unknown, AnyCommands>({
144
- transport: options.transport,
145
- onError: (error) => latest.current.onError?.(error),
146
- storage: options.storage,
147
- initialState: options.initialState,
148
- ...(options.protocol !== undefined && { protocol: options.protocol }),
149
- optimistic: (draft, command, ctx) => {
150
- runsOptimistic(draft, command, ctx);
151
- latest.current.optimistic?.(draft, command, ctx);
152
- },
153
- materialize: (draft: {}) => latest.current.materialize?.(draft),
154
- onCommandChange: (update, ctx) => {
155
- if (update.status === "applied" || update.status === "settled")
156
- retire(update.params[0]);
157
- latest.current.onCommandChange?.(update, ctx);
158
- },
159
- onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),
160
- onConnectionChange: (connection) =>
161
- latest.current.onConnectionChange?.(connection),
162
- failureCovered: (state, entry) => {
163
- const command = failedRunCommand(entry);
164
- if (command === undefined) return false;
165
- const messages = (state as { messages?: readonly { id: string }[] })
166
- .messages;
167
- return messages?.some((m) => m.id === command.message.id) ?? false;
168
- },
169
- });
153
+ const {
154
+ state,
155
+ commands,
156
+ connection,
157
+ documents,
158
+ invoke,
159
+ setContext,
160
+ isBusy,
161
+ failed,
162
+ discardFailed,
163
+ } = useStatewire<unknown, AnyCommands>({
164
+ transport: options.transport,
165
+ onError: (error) => latest.current.onError?.(error),
166
+ storage: options.storage,
167
+ initialState: options.initialState,
168
+ ...(options.protocol !== undefined && { protocol: options.protocol }),
169
+ optimistic: (draft, command, ctx) => {
170
+ runsOptimistic(draft, command, ctx);
171
+ latest.current.optimistic?.(draft, command, ctx);
172
+ },
173
+ materialize: (draft: {}) => latest.current.materialize?.(draft),
174
+ onCommandChange: (update, ctx) => {
175
+ if (update.status === "applied" || update.status === "settled")
176
+ retire(update.params[0]);
177
+ latest.current.onCommandChange?.(update, ctx);
178
+ },
179
+ onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),
180
+ onConnectionChange: (connection) =>
181
+ latest.current.onConnectionChange?.(connection),
182
+ failureCovered: (state, entry) => {
183
+ const command = failedRunCommand(entry);
184
+ if (command === undefined) return false;
185
+ const messages = (state as { messages?: readonly { id: string }[] })
186
+ .messages;
187
+ return messages?.some((m) => m.id === command.message.id) ?? false;
188
+ },
189
+ });
170
190
 
171
191
  const discarded = useRef(new WeakSet<StatewireClient.FailedCommand>());
172
192
  // Effects can replay before the updated failed lane reaches the binding.
@@ -183,35 +203,28 @@ const useStatewireThread = (
183
203
  }, [failed, discardFailed]);
184
204
 
185
205
  const clientRef = useAssistantClientRef();
186
- const invokeRef = useRef(invoke);
187
- invokeRef.current = invoke;
188
- const [syncState] = useState(() => ({ lastSent: undefined as unknown }));
206
+ const contextRef = useRef(setContext);
207
+ contextRef.current = setContext;
189
208
  const { contextSync } = options;
190
- const contextProtocol = `${options.protocol ?? DEFAULT_PROTOCOL}/context`;
191
- // The context document dies with its attach: resend on every connect.
192
- const connected = connection.status === "connected";
209
+ const contextProtocol = options.protocol ?? DEFAULT_PROTOCOL;
193
210
  useEffect(() => {
194
211
  if (contextSync === undefined) return;
195
- if (!connected) {
196
- syncState.lastSent = undefined;
197
- return;
198
- }
199
212
  const modelContext = (clientRef.current ?? clientRef.parent).modelContext();
213
+ let lastSent: string | undefined;
200
214
  const send = () => {
201
215
  const value = ambientContextOf(modelContext.getModelContext());
202
216
  const key = JSON.stringify(value);
203
- if (key === syncState.lastSent) return;
204
- syncState.lastSent = key;
205
- void invokeRef.current(contextProtocol, "set", [value]);
217
+ if (key === lastSent) return;
218
+ contextRef.current(contextProtocol, value);
219
+ lastSent = key;
206
220
  };
207
- send();
208
- if (!modelContext.subscribe) {
221
+ if (!modelContext.subscribe)
209
222
  throw new Error(
210
223
  "statewire: contextSync requires a subscribable model context",
211
224
  );
212
- }
225
+ send();
213
226
  return modelContext.subscribe(send);
214
- }, [contextSync, connected, contextProtocol, clientRef, syncState]);
227
+ }, [contextSync, contextProtocol, clientRef]);
215
228
 
216
229
  const dispatch = useCallback(
217
230
  (command: StatewireThread.Command) => {
@@ -330,14 +343,22 @@ const useStatewireThread = (
330
343
  }, [state, connection, failed]);
331
344
 
332
345
  const { converter } = options;
346
+ const mounted = useSyncExternalStore(
347
+ documents?.subscribe ?? noopSubscribe,
348
+ () => documents?.list() ?? NO_DOCUMENTS,
349
+ () => documents?.list() ?? NO_DOCUMENTS,
350
+ );
333
351
  const metadata = useMemo(
334
352
  (): StatewireThread.ConnectionMetadata => ({
335
353
  pendingCommands: [...pending],
336
354
  isSending: pending.length > 0,
337
355
  connection,
338
356
  runs,
357
+ documents,
358
+ mounted,
359
+ invoke,
339
360
  }),
340
- [pending, connection, runs],
361
+ [pending, connection, runs, documents, mounted, invoke],
341
362
  );
342
363
  const converted = useMemo(
343
364
  (): StatewireThread.State => converter(state, metadata),
@@ -381,7 +402,10 @@ const useStatewireThread = (
381
402
  [symbolStatewireExtras]: true,
382
403
  sendCommand: dispatch,
383
404
  reconnect: connection.reconnect,
384
- state,
405
+ connection,
406
+ documents,
407
+ invoke,
408
+ state: converted.state === undefined ? state : converted.state,
385
409
  status,
386
410
  isBusy,
387
411
  inputRequests,
@@ -417,8 +441,11 @@ const useStatewireThread = (
417
441
  };
418
442
  }, [
419
443
  dispatch,
420
- connection.reconnect,
444
+ connection,
445
+ documents,
446
+ invoke,
421
447
  state,
448
+ converted.state,
422
449
  status,
423
450
  isBusy,
424
451
  inputRequests,
@@ -590,6 +617,16 @@ export namespace StatewireThread {
590
617
  /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */
591
618
  sendCommand: (command: Command) => Promise<unknown>;
592
619
  reconnect: () => void;
620
+ connection: StatewireClient.ConnectionState;
621
+ /** The mounted documents, or `undefined` on a transport without documents. */
622
+ documents: StatewireDocuments.Source | undefined;
623
+ /** Sends a statement on a negotiated protocol lane. */
624
+ invoke: (
625
+ protocol: string,
626
+ method: string,
627
+ params: readonly unknown[],
628
+ ) => Promise<unknown>;
629
+ /** The converter's `state` when it returns one, else the replicated state. */
593
630
  state: unknown;
594
631
  status: ThreadStatus;
595
632
  /** Negation of the server's broadcast idle level (a transport without idle is always busy). */
@@ -743,6 +780,7 @@ export namespace StatewireThread {
743
780
  export type RunQueueItem = {
744
781
  readonly id: string;
745
782
  readonly parts: readonly (TextPart | FilePart)[];
783
+ readonly metadata?: Record<string, unknown>;
746
784
  };
747
785
 
748
786
  /** Run subsystem status replicated by the host. */
@@ -872,9 +910,17 @@ export namespace StatewireThread {
872
910
  connection: StatewireClient.ConnectionState;
873
911
  /** The typed runs read. */
874
912
  runs: Runs;
913
+ documents: StatewireDocuments.Source | undefined;
914
+ /** The mounted documents as of this pass; a new map whenever one changes. */
915
+ mounted: ReadonlyMap<number, StatewireDocuments.Document>;
916
+ invoke: (
917
+ protocol: string,
918
+ method: string,
919
+ params: readonly unknown[],
920
+ ) => Promise<unknown>;
875
921
  };
876
922
 
877
- /** Converter output: app-owned keys only — the lib projects the run mounts itself. */
923
+ /** Converter output: app-owned keys only — the lib projects the run mounts itself; `state` replaces the replicated state on the extras and thread. */
878
924
  export type State = {
879
925
  readonly messages: readonly ThreadMessage[];
880
926
  readonly state?: ReadonlyJSONValue;
@@ -912,8 +958,8 @@ export namespace StatewireThread {
912
958
  materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;
913
959
  /**
914
960
  * "command-send" mirrors the client's ambient model context (system,
915
- * tools, callSettings, config) to the server over the command channel —
916
- * on connect and whenever it changes. Requires a remote transport.
961
+ * tools, callSettings, config) to native protocol context, restored on
962
+ * each attachment and updated whenever it changes.
917
963
  */
918
964
  contextSync?: "command-send" | undefined;
919
965
  /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */
@@ -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) => ({