@assistant-ui/react-statewire 0.29.0 → 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.
package/README.md CHANGED
@@ -11,7 +11,7 @@ pnpm add @assistant-ui/react-statewire statewire @assistant-ui/core @assistant-u
11
11
  ## Use
12
12
 
13
13
  ```tsx
14
- import { AuiProvider, useAui } from "@assistant-ui/store";
14
+ import { AuiConfig, AuiProvider } from "@assistant-ui/store";
15
15
  import { StatewireThread } from "@assistant-ui/react-statewire";
16
16
  import { LocalStorageComposerDrafts } from "@assistant-ui/react-statewire/local-storage";
17
17
  import { StatewireHttp } from "statewire";
@@ -23,9 +23,9 @@ const thread = StatewireThread<ServerState>({
23
23
  capabilities: { edit: true, reload: true },
24
24
  storage: { composer: LocalStorageComposerDrafts({ threadId }) },
25
25
  });
26
- const aui = useAui({ thread });
26
+ const config = AuiConfig({ thread });
27
27
  return (
28
- <AuiProvider value={aui}>
28
+ <AuiProvider config={config}>
29
29
  <Thread />
30
30
  </AuiProvider>
31
31
  );
@@ -1,6 +1,6 @@
1
1
  import { ResourceElement } from "@assistant-ui/tap";
2
2
  import { ClientOutput } from "@assistant-ui/store";
3
- import { Statewire, StatewireClient } from "statewire";
3
+ import { Statewire, StatewireClient, StatewireDocuments } from "statewire";
4
4
  import { Assistant, AttachmentAdapter, CompleteAttachment, FeedbackAdapter, SpeechSynthesisAdapter, ThreadMessage } from "@assistant-ui/core";
5
5
  import { ReadonlyJSONValue } from "assistant-stream/utils";
6
6
  //#region src/StatewireThread.d.ts
@@ -26,6 +26,12 @@ declare namespace StatewireThread {
26
26
  /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */
27
27
  sendCommand: (command: Command) => Promise<unknown>;
28
28
  reconnect: () => void;
29
+ connection: StatewireClient.ConnectionState;
30
+ /** The mounted documents, or `undefined` on a transport without documents. */
31
+ documents: StatewireDocuments.Source | undefined;
32
+ /** Sends a statement on a negotiated protocol lane. */
33
+ invoke: (protocol: string, method: string, params: readonly unknown[]) => Promise<unknown>;
34
+ /** The converter's `state` when it returns one, else the replicated state. */
29
35
  state: unknown;
30
36
  status: ThreadStatus;
31
37
  /** Negation of the server's broadcast idle level (a transport without idle is always busy). */
@@ -144,6 +150,7 @@ declare namespace StatewireThread {
144
150
  export type RunQueueItem = {
145
151
  readonly id: string;
146
152
  readonly parts: readonly (TextPart | FilePart)[];
153
+ readonly metadata?: Record<string, unknown>;
147
154
  };
148
155
  /** Run subsystem status replicated by the host. */
149
156
  export type RunStatus = "running" | "stopped" | "error" | "input-required";
@@ -248,8 +255,12 @@ declare namespace StatewireThread {
248
255
  connection: StatewireClient.ConnectionState;
249
256
  /** The typed runs read. */
250
257
  runs: Runs;
258
+ documents: StatewireDocuments.Source | undefined;
259
+ /** The mounted documents as of this pass; a new map whenever one changes. */
260
+ mounted: ReadonlyMap<number, StatewireDocuments.Document>;
261
+ invoke: (protocol: string, method: string, params: readonly unknown[]) => Promise<unknown>;
251
262
  };
252
- /** Converter output: app-owned keys only — the lib projects the run mounts itself. */
263
+ /** Converter output: app-owned keys only — the lib projects the run mounts itself; `state` replaces the replicated state on the extras and thread. */
253
264
  export type State = {
254
265
  readonly messages: readonly ThreadMessage[];
255
266
  readonly state?: ReadonlyJSONValue;
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cAgDa;cAEA,oBAAqB,oBAAkB,gBAAgB;cAkgBvD,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C,UAAU,KAAK,gBAAgB,UAAU;;cAGzC;aACD;aACA,sBAAsB;;;cAIrB;IACV,QAAQ;IACR,MAAM,OAAO;IACb;;cAGU;KACT;;IAED,cAAc,SAAS,YAAY;IACnC;IACA;IACA,QAAQ;;IAER;IACA,wBAAwB;IACxB,MAAM;;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;;aAED,kBAAkB;;aAElB,eAAe;;;cAId;;aAED;;aAEA;;aAEA;aACA,gBAAgB;aAChB,qBAAqB;;aAErB,cAAc;aACd,WAAW;;aAEX,eAAe;;aAEf,yBAAyB;;aAEzB,QAAQ;;aAER,iBAAiB;;cAGhB;IACV,iBAAiB;IACjB;;IAEA,YAAY,gBAAgB;;IAE5B,MAAM;IACN,WAAW,mBAAmB;;IAE9B,SAAS,oBAAoB,mBAAmB;IAChD,SACE,kBACA,gBACA,+BACG;;;cAIK;aACD,mBAAmB;aACnB,QAAQ;;cAGP,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;;;;;cAMO;aACD;cACC,cAAc;;cAGd,QAAQ;IAClB,WAAW,UAAU;;IAErB,cAAc;;IAEd;IACA,WAAW,eAAe;;IAE1B,aACI,gBAAgB,WACd,GACA,mBAAmB;;IAIzB,cAAc,gBAAgB,YAAY,YAAY;;;;;;IAMtD;;IAEA,qBAAqB;;IAErB,oBAEM,QAAQ,UAAU,cAChB,mBAAmB,2BAErB;MAAO,OAAO,YAAY;;;IAIhC,kBACM,OAAO,YAAY,IAAI;MAAO,SAAS,UAAU;;;IAGvD,uBACM,YAAY,gBAAgB;IAElC,YAAY,OAAO;IACnB;MAEM;;MAEA;;MAEA;;MAEA;;;;;;;;IASN;MAEM,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB,gBAAgB;;IAGhD;MAEM,cAAc;MACd,SAAS;MACT,WAAW;;;;;;YAOT;cACE;MACR,YAAY,gBAAgB;MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB;MAC1B,qBAAqB,gBAAgB"}
@@ -1,13 +1,15 @@
1
1
  import { createBranchCommandAdapter, createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, retryCommand, sendFields, toWireMessage } from "./runCommands.js";
2
2
  import { resolveToolApprovalInput, resolveToolResultInput } from "./inputRequests.js";
3
3
  import { runsOptimistic } from "./runsOptimistic.js";
4
- import { useCallback, useEffect, useMemo, useRef, useState } from "@assistant-ui/tap/react-shim";
4
+ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "@assistant-ui/tap/react-shim";
5
5
  import { resource, useResource, useResources, withKey } from "@assistant-ui/tap";
6
6
  import { ExternalThread } from "@assistant-ui/core/store";
7
7
  import { forwardTransformScopes, useAssistantClientRef } from "@assistant-ui/store";
8
8
  import { toToolsJSONSchema } from "assistant-stream";
9
9
  import { DEFAULT_PROTOCOL, useStatewire } from "statewire";
10
10
  //#region src/StatewireThread.ts
11
+ const NO_DOCUMENTS = /* @__PURE__ */ new Map();
12
+ const noopSubscribe = () => () => {};
11
13
  const symbolStatewireExtras = Symbol("statewire-extras");
12
14
  const asStatewireExtras = (extras) => {
13
15
  if (typeof extras !== "object" || extras == null || !(symbolStatewireExtras in extras)) throw new Error("This method can only be called when you are using StatewireThread");
@@ -40,7 +42,7 @@ const useStatewireThread = (options) => {
40
42
  const retrying = useRef(/* @__PURE__ */ new Set());
41
43
  const [pending, setPending] = useState([]);
42
44
  const [retire] = useState(() => (command) => setPending((prev) => prev.includes(command) ? prev.filter((c) => c !== command) : prev));
43
- const { state: state_1, commands, connection: connection_0, invoke, isBusy, failed, discardFailed } = useStatewire({
45
+ const { state: state_1, commands, connection: connection_0, documents, invoke, isBusy, failed, discardFailed } = useStatewire({
44
46
  transport: options.transport,
45
47
  onError: (error) => latest.current.onError?.(error),
46
48
  storage: options.storage,
@@ -89,7 +91,14 @@ const useStatewireThread = (options) => {
89
91
  const key = JSON.stringify(value);
90
92
  if (key === syncState.lastSent) return;
91
93
  syncState.lastSent = key;
92
- invokeRef.current(contextProtocol, "set", [value]);
94
+ const forget = () => {
95
+ if (syncState.lastSent === key) syncState.lastSent = void 0;
96
+ };
97
+ try {
98
+ invokeRef.current(contextProtocol, "set", [value]).catch(forget);
99
+ } catch {
100
+ forget();
101
+ }
93
102
  };
94
103
  send();
95
104
  if (!modelContext.subscribe) throw new Error("statewire: contextSync requires a subscribable model context");
@@ -174,15 +183,22 @@ const useStatewireThread = (options) => {
174
183
  failed
175
184
  ]);
176
185
  const { converter } = options;
186
+ const mounted = useSyncExternalStore(documents?.subscribe ?? noopSubscribe, () => documents?.list() ?? NO_DOCUMENTS, () => documents?.list() ?? NO_DOCUMENTS);
177
187
  const metadata = useMemo(() => ({
178
188
  pendingCommands: [...pending],
179
189
  isSending: pending.length > 0,
180
190
  connection: connection_0,
181
- runs
191
+ runs,
192
+ documents,
193
+ mounted,
194
+ invoke
182
195
  }), [
183
196
  pending,
184
197
  connection_0,
185
- runs
198
+ runs,
199
+ documents,
200
+ mounted,
201
+ invoke
186
202
  ]);
187
203
  const converted = useMemo(() => converter(state_1, metadata), [
188
204
  converter,
@@ -210,7 +226,10 @@ const useStatewireThread = (options) => {
210
226
  [symbolStatewireExtras]: true,
211
227
  sendCommand: dispatch,
212
228
  reconnect: connection_0.reconnect,
213
- state: state_1,
229
+ connection: connection_0,
230
+ documents,
231
+ invoke,
232
+ state: converted.state === void 0 ? state_1 : converted.state,
214
233
  status,
215
234
  isBusy,
216
235
  inputRequests,
@@ -240,8 +259,11 @@ const useStatewireThread = (options) => {
240
259
  };
241
260
  }, [
242
261
  dispatch,
243
- connection_0.reconnect,
262
+ connection_0,
263
+ documents,
264
+ invoke,
244
265
  state_1,
266
+ converted.state,
245
267
  status,
246
268
  isBusy,
247
269
  inputRequests,
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","useResources","withKey","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","CompleteAttachment","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","DEFAULT_PROTOCOL","useStatewire","Statewire","StatewireClient","createBranchCommandAdapter","createRunQueueAdapter","resolveEditCommand","retryCommand","resolveReloadCommand","sendFields","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","symbolStatewireExtras","Symbol","asStatewireExtras","extras","StatewireThread","Extras","Error","NO_INPUT_REQUESTS","InputRequestState","RESTING_RUNS","Runs","runId","queue","steerQueue","failed","failedRunCommand","entry","FailedCommand","RunEnqueueCommand","RunSteerCommand","RunEditCommand","message","UserMessage","command","undefined","params","ReturnType","presentStatus","status","ThreadStatus","connection","ConnectionState","reason","cause","code","ambientContextOf","context","system","tools","callSettings","config","useStatewireThread","options","Options","latest","current","retrying","Set","pending","setPending","Command","retire","prev","includes","filter","c","state","commands","invoke","isBusy","discardFailed","transport","onError","error","storage","initialState","protocol","optimistic","draft","ctx","materialize","onCommandChange","update","onStateChange","onConnectionChange","failureCovered","messages","id","some","m","discarded","WeakSet","has","add","clientRef","invokeRef","syncState","lastSent","contextSync","contextProtocol","connected","modelContext","parent","send","value","getModelContext","key","JSON","stringify","subscribe","dispatch","settled","type","catch","threadRef","dispatchSend","sourceId","text","content","flatMap","part","join","setText","composer","next","popRetracted","retracted","Promise","Array","isArray","length","composerApi","getState","texts","item","RunsQueueEntry","messageId","push","parts","Boolean","runs","entries","RunState","failedEntries","failure","RunsFailedEntry","sendFailure","epoch","stopReason","dispatching","stopping","nextDispatch","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","converted","State","liveRunId","branches","takeFailed","find","f","sendCommand","reconnect","retryFailed","release","delete","then","popFailed","p","handleAppend","crypto","randomUUID","handleReload","parentId","handleEdit","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","unstable_switchBranch","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","composerStorage","read","isEmpty","attachment","addAttachment","name","contentType","draftText","composerAttachments","draftAttachments","map","file","_file","record","draftSync","writingFor","isBaseline","clear","write","T","UserCommands","Commands","Transport","ComposerDraft","ComposerStorage","TextPart","FilePart","mediaType","url","filename","role","Placement","insertAfter","insertBefore","RunSendCommand","TType","runAnchorMessageId","RunDequeueCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","BranchMetadata","siblings","SwitchBranchCommand","branchId","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","SendFailure","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","RunsError","MaterializeEffects","append","rollback","to","RunsState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","session","SessionStorage","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","messageSwitchBranch","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n resource,\n useResource,\n useResources,\n withKey,\n} from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/core/store\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/core/store\";\nimport type { Assistant } from \"@assistant-ui/core\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n CompleteAttachment,\n FeedbackAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n SpeechSynthesisAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { DEFAULT_PROTOCOL, useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport {\n createBranchCommandAdapter,\n createRunQueueAdapter,\n resolveEditCommand,\n retryCommand,\n resolveReloadCommand,\n sendFields,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nexport const symbolStatewireExtras = Symbol(\"statewire-extras\");\n\nexport const asStatewireExtras = (extras: unknown): StatewireThread.Extras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolStatewireExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using StatewireThread\",\n );\n\n return extras as StatewireThread.Extras;\n};\n\nconst NO_INPUT_REQUESTS: readonly StatewireThread.InputRequestState[] = [];\n\nconst RESTING_RUNS: StatewireThread.Runs = {\n runId: null,\n queue: [],\n steerQueue: [],\n failed: [],\n};\n\n/** The failed run sends the thread can project: enqueue/steer/edit invocations carrying a message. */\nconst failedRunCommand = (\n entry: StatewireClient.FailedCommand,\n):\n | ((\n | StatewireThread.RunEnqueueCommand\n | StatewireThread.RunSteerCommand\n | StatewireThread.RunEditCommand\n ) & { message: StatewireThread.UserMessage })\n | undefined => {\n if (\n entry.command !== \"run/enqueue\" &&\n entry.command !== \"run/steer\" &&\n entry.command !== \"run/edit\"\n )\n return undefined;\n const command = entry.params[0] as\n | { message?: StatewireThread.UserMessage }\n | undefined;\n if (command?.message === undefined) return undefined;\n return command as ReturnType<typeof failedRunCommand>;\n};\n\n// Derived presentation while the connection can't vouch for progress:\n// live-claiming \"running\" reads as evicted/disconnected; facts pass through.\nconst presentStatus = (\n status: StatewireThread.ThreadStatus,\n connection: StatewireClient.ConnectionState,\n): StatewireThread.ThreadStatus =>\n status !== \"running\" ||\n connection.status === \"connected\" ||\n (connection.status === \"standby\" && connection.reason === \"idle\")\n ? status\n : connection.status === \"retrying\" &&\n connection.cause === \"reconnect\" &&\n connection.code === \"evicted\"\n ? \"evicted\"\n : \"disconnected\";\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n const retrying = useRef(new Set<string>());\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const { state, commands, connection, invoke, isBusy, failed, discardFailed } =\n useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n onError: (error) => latest.current.onError?.(error),\n storage: options.storage,\n initialState: options.initialState,\n ...(options.protocol !== undefined && { protocol: options.protocol }),\n optimistic: (draft, command, ctx) => {\n runsOptimistic(draft, command, ctx);\n latest.current.optimistic?.(draft, command, ctx);\n },\n materialize: (draft: {}) => latest.current.materialize?.(draft),\n onCommandChange: (update, ctx) => {\n if (update.status === \"applied\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n failureCovered: (state, entry) => {\n const command = failedRunCommand(entry);\n if (command === undefined) return false;\n const messages = (state as { messages?: readonly { id: string }[] })\n .messages;\n return messages?.some((m) => m.id === command.message.id) ?? false;\n },\n });\n\n const discarded = useRef(new WeakSet<StatewireClient.FailedCommand>());\n // Effects can replay before the updated failed lane reaches the binding.\n useEffect(() => {\n for (const entry of failed) {\n if (\n failedRunCommand(entry) === undefined &&\n !discarded.current.has(entry)\n ) {\n discarded.current.add(entry);\n discardFailed(entry);\n }\n }\n }, [failed, discardFailed]);\n\n const clientRef = useAssistantClientRef();\n const invokeRef = useRef(invoke);\n invokeRef.current = invoke;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n const contextProtocol = `${options.protocol ?? DEFAULT_PROTOCOL}/context`;\n // The context document dies with its attach: resend on every connect.\n const connected = connection.status === \"connected\";\n useEffect(() => {\n if (contextSync === undefined) return;\n if (!connected) {\n syncState.lastSent = undefined;\n return;\n }\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n void invokeRef.current(contextProtocol, \"set\", [value]);\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, connected, contextProtocol, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n // The stop verdict carries the run's retracted items; the stopping client\n // dequeues them into an empty composer. Other clients see them queued.\n const popRetracted = async (\n retracted: unknown,\n runId: string | null,\n ): Promise<void> => {\n if (!Array.isArray(retracted) || retracted.length === 0 || runId === null)\n return;\n const composerApi = threadRef.current!.composer();\n if (composerApi.getState().text !== \"\") return;\n const texts: string[] = [];\n for (const item of retracted as StatewireThread.RunsQueueEntry[]) {\n try {\n await dispatch({ type: \"run/dequeue\", runId, messageId: item.id });\n } catch {\n continue; // rejected dequeue: the item stays queued\n }\n texts.push(\n item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n );\n }\n if (texts.length === 0) return;\n const setText = composerApi.setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => [prev, ...texts].filter(Boolean).join(\"\\n\\n\"));\n };\n\n const { status, runs } = useMemo((): {\n status: StatewireThread.ThreadStatus;\n runs: StatewireThread.Runs;\n } => {\n const entries = (\n state as { runs?: readonly StatewireThread.RunState[] } | undefined\n )?.runs;\n const entry = entries?.[0];\n const failedEntries = failed.flatMap(\n (failure): StatewireThread.RunsFailedEntry[] => {\n const command = failedRunCommand(failure);\n return command === undefined\n ? []\n : [{ ...command.message, sendFailure: failure.failure }];\n },\n );\n return {\n status: presentStatus(\n entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n connection,\n ),\n runs:\n entry === undefined && failedEntries.length === 0\n ? RESTING_RUNS\n : {\n ...(entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n ...(entry.epoch !== undefined && { epoch: entry.epoch }),\n ...(entry.stopReason !== undefined && {\n stopReason: entry.stopReason,\n }),\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && {\n stopping: entry.stopping,\n }),\n ...(entry.nextDispatch !== undefined && {\n nextDispatch: entry.nextDispatch,\n }),\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n ...(entry.error !== undefined && { error: entry.error }),\n }),\n failed: failedEntries,\n },\n };\n }, [state, connection, failed]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n runs,\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n (): StatewireThread.State => converter(state, metadata),\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const liveRunId = runs.runId;\n\n const queue = useMemo(\n () =>\n createRunQueueAdapter(\n messages,\n liveRunId,\n runs.queue,\n runs.steerQueue,\n dispatch,\n dispatchSend,\n ),\n [messages, liveRunId, runs, dispatch, dispatchSend],\n );\n\n const branches = useMemo(\n () => createBranchCommandAdapter(messages, dispatch),\n [messages, dispatch],\n );\n\n const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo((): StatewireThread.Extras => {\n const takeFailed = (messageId: string): StatewireClient.FailedCommand => {\n const entry = failed.find(\n (f) => failedRunCommand(f)?.message.id === messageId,\n );\n if (entry === undefined)\n throw new Error(`statewire: unknown failed entry \"${messageId}\"`);\n return entry;\n };\n return {\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n retryFailed: (messageId) => {\n if (retrying.current.has(messageId)) return;\n const entry = takeFailed(messageId);\n const command = retryCommand(\n messages,\n liveRunId,\n failedRunCommand(entry)!,\n );\n retrying.current.add(messageId);\n const release = () => {\n retrying.current.delete(messageId);\n };\n try {\n discardFailed(entry);\n void dispatch(command).then(release, release);\n } catch (error) {\n release();\n throw error;\n }\n },\n discardFailed: (messageId) => discardFailed(takeFailed(messageId)),\n popFailed: (messageId) => {\n const entry = takeFailed(messageId);\n discardFailed(entry);\n return failedRunCommand(entry)!\n .message.parts.flatMap((p) => (p.type === \"text\" ? [p.text] : []))\n .join(\"\\n\\n\");\n },\n };\n }, [\n dispatch,\n connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n failed,\n discardFailed,\n messages,\n liveRunId,\n ]);\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message, liveRunId)\n : {\n type: \"run/steer\",\n ...sendFields(\n messages,\n liveRunId,\n toWireMessage(message, crypto.randomUUID()),\n ),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId, liveRunId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message, liveRunId));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning: status === \"running\",\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\n onNew: handleAppend,\n queue,\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () =>\n dispatch({\n type: \"run/continue\",\n ...(liveRunId !== null && { runId: liveRunId }),\n }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(options.capabilities?.unstable_switchBranch && { branches }),\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n const runId = runs.runId;\n void commands[\"run/stop\"]!({\n ...payload,\n runId,\n ...(runs.epoch !== undefined && { epoch: runs.epoch }),\n })\n .then((retracted) => popRetracted(retracted, runId))\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n\n const composerStorage = useResources(\n options.storage?.composer !== undefined\n ? [withKey(\"composer\", options.storage.composer)]\n : [],\n )[0];\n\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n const composer = threadRef.current!.composer();\n const draft = storage.read();\n if (draft === undefined || !composer.getState().isEmpty) return;\n composer.setText(draft.text);\n for (const attachment of draft.attachments) {\n composer\n .addAttachment({\n id: attachment.id,\n type: attachment.type,\n name: attachment.name,\n ...(attachment.contentType !== undefined && {\n contentType: attachment.contentType,\n }),\n content: attachment.content,\n })\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n }\n }, [composerStorage]);\n\n const { text: draftText, attachments: composerAttachments } =\n thread.getState().composer;\n const draftAttachments = useMemo(\n () =>\n composerAttachments\n .filter(\n (attachment): attachment is CompleteAttachment =>\n attachment.status.type === \"complete\",\n )\n .map(({ file: _file, ...record }) => record),\n [composerAttachments],\n );\n const [draftSync] = useState(() => ({ writingFor: undefined as unknown }));\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n // First run per storage is the baseline, not a change: never clear the\n // stored draft the restore effect is about to load.\n const isBaseline = draftSync.writingFor !== storage;\n draftSync.writingFor = storage;\n if (draftText === \"\" && draftAttachments.length === 0) {\n if (!isBaseline) storage.clear();\n return;\n }\n storage.write({ text: draftText, attachments: draftAttachments });\n }, [draftSync, composerStorage, draftText, draftAttachments]);\n\n return thread;\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\n\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n /** A composer draft as persisted: the text plus the completed attachments. */\n export type ComposerDraft = {\n readonly text: string;\n readonly attachments: readonly CompleteAttachment[];\n };\n\n /** Composer draft storage seam; `write` must persist synchronously in the caller's flow. */\n export type ComposerStorage = {\n read(): ComposerDraft | undefined;\n write(draft: ComposerDraft): void;\n clear(): void;\n };\n\n export type Extras = {\n [symbolStatewireExtras]: true;\n /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */\n sendCommand: (command: Command) => Promise<unknown>;\n reconnect: () => void;\n state: unknown;\n status: ThreadStatus;\n /** Negation of the server's broadcast idle level (a transport without idle is always busy). */\n isBusy: boolean;\n inputRequests: readonly InputRequestState[];\n runs: Runs;\n /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */\n retryFailed: (messageId: string) => void;\n /** Removes the failed entry; keyed by the entry's message id. */\n discardFailed: (messageId: string) => void;\n /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */\n popFailed: (messageId: string) => string;\n };\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n type RunSendCommand<TType extends \"run/enqueue\" | \"run/steer\"> = {\n readonly type: TType;\n /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: UserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunEnqueueCommand = RunSendCommand<\"run/enqueue\">;\n\n export type RunSteerCommand = RunSendCommand<\"run/steer\">;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly runId: string;\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n readonly runId?: string;\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly runId?: string;\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state; a present `response` key marks the entry answered. */\n export type InputRequestState = InputRequest & {\n readonly response?: InputResponse;\n /** The answer's `run/input` meta; absent when the answer carried none. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** Per-message branch metadata read from `metadata.custom.branch`: the message's own branch id and the fan-out's branch ids in creation order (own id included). */\n export type BranchMetadata = {\n readonly id: number;\n readonly siblings: readonly number[];\n };\n\n export type SwitchBranchCommand = {\n readonly type: \"message/switch-branch\";\n readonly branchId: number;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus = \"running\" | \"stopped\" | \"error\" | \"input-required\";\n\n /** The thread's status: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status; `\"evicted\"` and `\"disconnected\"` are client-derived from the connection, never replicated. */\n export type ThreadStatus =\n | \"loading\"\n | \"ready\"\n | \"evicted\"\n | \"disconnected\"\n | RunStatus;\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */\n export type RunsFailedEntry = RunsQueueEntry & {\n readonly sendFailure: StatewireClient.SendFailure;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** The run-starting op's meta; present only when carried. */\n readonly rootMeta?: ReadonlyJSONValue;\n /** Present when input outcomes ride the dispatch; visible until applied. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The stopping window: present while a stop of the live run is underway; `\"message-edit\"` / `\"message-reload\"` pair with `nextDispatch`. */\n export type RunsStopping = {\n readonly reason: \"stop\" | \"message-edit\" | \"message-reload\";\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */\n readonly epoch?: number;\n /** The reason carried by `run/stop`; persists through error/stop, cleared at the next dispatch. */\n readonly stopReason?: string | null;\n readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: \"ready\" | RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the state with unsettled commands folded in, resting defaults while no entry is live. */\n export type Runs = {\n /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */\n readonly epoch?: number;\n /** The reason carried by `run/stop`; persists through error/stop, cleared at the next dispatch. */\n readonly stopReason?: string | null;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */\n readonly failed: readonly RunsFailedEntry[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `connected`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\n runs: Runs;\n };\n\n /** Converter output: app-owned keys only — the lib projects the run mounts itself. */\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n /** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */\n initialState: T;\n /** Application protocol for optimistic commands; must match the transport's protocol. */\n protocol?: string | undefined;\n converter: StateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, applied, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n /** The host supports `message/switch-branch` (thread-global branch switching driven by `metadata.custom.branch`). */\n unstable_switchBranch?: boolean | undefined;\n }\n | undefined;\n /**\n * Durable drafts: the mounted composer storage restores on mount, mirrors\n * every change, and clears when the draft is consumed. The session storage\n * holds this thread's lane identity and its un-durable commands, which\n * resend under their original seqs on the next mount.\n */\n storage?:\n | {\n composer?: ResourceElement<ComposerStorage> | undefined;\n session?: ResourceElement<StatewireClient.SessionStorage> | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/core\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n messageSwitchBranch: StatewireThread.SwitchBranchCommand;\n }\n }\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;AAgDA,MAAa4C,wBAAwBC,OAAO,kBAAkB;AAE9D,MAAaC,qBAAqBC,WAA4C;CAC5E,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEH,yBAAyBG,SAE3B,MAAM,IAAIG,MACR,mEACF;CAEF,OAAOH;AACT;AAEA,MAAMI,oBAAkE,CAAA;AAExE,MAAME,eAAqC;CACzCE,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,QAAQ,CAAA;AACV;;AAGA,MAAMC,oBACJC,UAOe;CACf,IACEA,MAAMO,YAAY,iBAClBP,MAAMO,YAAY,eAClBP,MAAMO,YAAY,YAElB,OAAOC,KAAAA;CACT,MAAMD,UAAUP,MAAMS,OAAO;CAG7B,IAAIF,SAASF,YAAYG,KAAAA,GAAW,OAAOA,KAAAA;CAC3C,OAAOD;AACT;AAIA,MAAMI,iBACJC,QACAE,eAEAF,WAAW,aACXE,WAAWF,WAAW,eACrBE,WAAWF,WAAW,aAAaE,WAAWE,WAAW,SACtDJ,SACAE,WAAWF,WAAW,cACpBE,WAAWG,UAAU,eACrBH,WAAWI,SAAS,YACpB,YACA;AAER,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWb,KAAAA,KAAa,EAAEa,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQE,UAAUd,KAAAA,KAAa,EACjCc,OAAOzD,kBAAkBuD,QAAQE,KAAK,EACxC;CACA,GAAIF,QAAQG,iBAAiBf,KAAAA,KAAa,EACxCe,cAAcH,QAAQG,aACxB;CACA,GAAIH,QAAQI,WAAWhB,KAAAA,KAAa,EAAEgB,QAAQJ,QAAQI,OAAO;AAC/D;AAEA,MAAMC,sBACJC,YA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,eAAejJ;EAC5CgJ,UAAUC,aAAajJ;EACvB,IAAIyI,cAAc,MAAME,iBAAiBnF,WAAW,GAAG;GACrD,IAAI,CAAC0F,YAAYlJ,UAAQmJ,MAAM;GAC/B;EACF;EACAnJ,UAAQoJ,MAAM;GAAEzG,MAAM8F;GAAW5B,aAAa8B;EAAiB,CAAC;CAClE,GAAG;EAACK;EAAWd;EAAiBO;EAAWE;CAAgB,CAAC;CAE5D,OAAOlC;AACT;AAEA,MAAarK,mBACXsC,YAEAjF,SAASgF,kBAAkB,CAAC,CAACC,OAAuC;AAoatEzE,uBACEwE,oBACA3E,eAAe0D,KAAAA,CAAkB,CAAC,CAACsQ,IACrC"}
1
+ {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","resource","useResource","useResources","withKey","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","CompleteAttachment","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","DEFAULT_PROTOCOL","useStatewire","Statewire","StatewireClient","StatewireDocuments","createBranchCommandAdapter","createRunQueueAdapter","resolveEditCommand","retryCommand","resolveReloadCommand","sendFields","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","NO_DOCUMENTS","ReadonlyMap","Document","Map","noopSubscribe","symbolStatewireExtras","Symbol","asStatewireExtras","extras","StatewireThread","Extras","Error","NO_INPUT_REQUESTS","InputRequestState","RESTING_RUNS","Runs","runId","queue","steerQueue","failed","failedRunCommand","entry","FailedCommand","RunEnqueueCommand","RunSteerCommand","RunEditCommand","message","UserMessage","command","undefined","params","ReturnType","presentStatus","status","ThreadStatus","connection","ConnectionState","reason","cause","code","ambientContextOf","context","system","tools","callSettings","config","useStatewireThread","options","Options","latest","current","retrying","Set","pending","setPending","Command","retire","prev","includes","filter","c","state","commands","documents","invoke","isBusy","discardFailed","transport","onError","error","storage","initialState","protocol","optimistic","draft","ctx","materialize","onCommandChange","update","onStateChange","onConnectionChange","failureCovered","messages","id","some","m","discarded","WeakSet","has","add","clientRef","invokeRef","syncState","lastSent","contextSync","contextProtocol","connected","modelContext","parent","send","value","getModelContext","key","JSON","stringify","forget","catch","subscribe","dispatch","settled","type","threadRef","dispatchSend","sourceId","text","content","flatMap","part","join","setText","composer","next","popRetracted","retracted","Promise","Array","isArray","length","composerApi","getState","texts","item","RunsQueueEntry","messageId","push","parts","Boolean","runs","entries","RunState","failedEntries","failure","RunsFailedEntry","sendFailure","epoch","stopReason","dispatching","stopping","nextDispatch","inputRequests","converter","mounted","list","metadata","ConnectionMetadata","pendingCommands","isSending","converted","State","liveRunId","branches","takeFailed","find","f","sendCommand","reconnect","retryFailed","release","delete","then","popFailed","p","handleAppend","crypto","randomUUID","handleReload","parentId","handleEdit","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","unstable_switchBranch","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","composerStorage","read","isEmpty","attachment","addAttachment","name","contentType","draftText","composerAttachments","draftAttachments","map","file","_file","record","draftSync","writingFor","isBaseline","clear","write","T","UserCommands","Commands","Transport","ComposerDraft","ComposerStorage","Source","method","TextPart","FilePart","mediaType","url","filename","role","Placement","insertAfter","insertBefore","RunSendCommand","TType","runAnchorMessageId","RunDequeueCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","BranchMetadata","siblings","SwitchBranchCommand","branchId","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","SendFailure","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","RunsError","MaterializeEffects","append","rollback","to","RunsState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","session","SessionStorage","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","messageSwitchBranch","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport {\n resource,\n useResource,\n useResources,\n withKey,\n} from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/core/store\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/core/store\";\nimport type { Assistant } from \"@assistant-ui/core\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n CompleteAttachment,\n FeedbackAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n SpeechSynthesisAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { DEFAULT_PROTOCOL, useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient, StatewireDocuments } from \"statewire\";\nimport {\n createBranchCommandAdapter,\n createRunQueueAdapter,\n resolveEditCommand,\n retryCommand,\n resolveReloadCommand,\n sendFields,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nconst NO_DOCUMENTS: ReadonlyMap<number, StatewireDocuments.Document> =\n new Map();\nconst noopSubscribe = () => () => {};\n\nexport const symbolStatewireExtras = Symbol(\"statewire-extras\");\n\nexport const asStatewireExtras = (extras: unknown): StatewireThread.Extras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolStatewireExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using StatewireThread\",\n );\n\n return extras as StatewireThread.Extras;\n};\n\nconst NO_INPUT_REQUESTS: readonly StatewireThread.InputRequestState[] = [];\n\nconst RESTING_RUNS: StatewireThread.Runs = {\n runId: null,\n queue: [],\n steerQueue: [],\n failed: [],\n};\n\n/** The failed run sends the thread can project: enqueue/steer/edit invocations carrying a message. */\nconst failedRunCommand = (\n entry: StatewireClient.FailedCommand,\n):\n | ((\n | StatewireThread.RunEnqueueCommand\n | StatewireThread.RunSteerCommand\n | StatewireThread.RunEditCommand\n ) & { message: StatewireThread.UserMessage })\n | undefined => {\n if (\n entry.command !== \"run/enqueue\" &&\n entry.command !== \"run/steer\" &&\n entry.command !== \"run/edit\"\n )\n return undefined;\n const command = entry.params[0] as\n | { message?: StatewireThread.UserMessage }\n | undefined;\n if (command?.message === undefined) return undefined;\n return command as ReturnType<typeof failedRunCommand>;\n};\n\n// Derived presentation while the connection can't vouch for progress:\n// live-claiming \"running\" reads as evicted/disconnected; facts pass through.\nconst presentStatus = (\n status: StatewireThread.ThreadStatus,\n connection: StatewireClient.ConnectionState,\n): StatewireThread.ThreadStatus =>\n status !== \"running\" ||\n connection.status === \"connected\" ||\n (connection.status === \"standby\" && connection.reason === \"idle\")\n ? status\n : connection.status === \"retrying\" &&\n connection.cause === \"reconnect\" &&\n connection.code === \"evicted\"\n ? \"evicted\"\n : \"disconnected\";\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n const retrying = useRef(new Set<string>());\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const {\n state,\n commands,\n connection,\n documents,\n invoke,\n isBusy,\n failed,\n discardFailed,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n onError: (error) => latest.current.onError?.(error),\n storage: options.storage,\n initialState: options.initialState,\n ...(options.protocol !== undefined && { protocol: options.protocol }),\n optimistic: (draft, command, ctx) => {\n runsOptimistic(draft, command, ctx);\n latest.current.optimistic?.(draft, command, ctx);\n },\n materialize: (draft: {}) => latest.current.materialize?.(draft),\n onCommandChange: (update, ctx) => {\n if (update.status === \"applied\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n failureCovered: (state, entry) => {\n const command = failedRunCommand(entry);\n if (command === undefined) return false;\n const messages = (state as { messages?: readonly { id: string }[] })\n .messages;\n return messages?.some((m) => m.id === command.message.id) ?? false;\n },\n });\n\n const discarded = useRef(new WeakSet<StatewireClient.FailedCommand>());\n // Effects can replay before the updated failed lane reaches the binding.\n useEffect(() => {\n for (const entry of failed) {\n if (\n failedRunCommand(entry) === undefined &&\n !discarded.current.has(entry)\n ) {\n discarded.current.add(entry);\n discardFailed(entry);\n }\n }\n }, [failed, discardFailed]);\n\n const clientRef = useAssistantClientRef();\n const invokeRef = useRef(invoke);\n invokeRef.current = invoke;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n const contextProtocol = `${options.protocol ?? DEFAULT_PROTOCOL}/context`;\n // The context document dies with its attach: resend on every connect.\n const connected = connection.status === \"connected\";\n useEffect(() => {\n if (contextSync === undefined) return;\n if (!connected) {\n syncState.lastSent = undefined;\n return;\n }\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n const forget = () => {\n if (syncState.lastSent === key) syncState.lastSent = undefined;\n };\n try {\n invokeRef.current(contextProtocol, \"set\", [value]).catch(forget);\n } catch {\n forget();\n }\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, connected, contextProtocol, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n // The stop verdict carries the run's retracted items; the stopping client\n // dequeues them into an empty composer. Other clients see them queued.\n const popRetracted = async (\n retracted: unknown,\n runId: string | null,\n ): Promise<void> => {\n if (!Array.isArray(retracted) || retracted.length === 0 || runId === null)\n return;\n const composerApi = threadRef.current!.composer();\n if (composerApi.getState().text !== \"\") return;\n const texts: string[] = [];\n for (const item of retracted as StatewireThread.RunsQueueEntry[]) {\n try {\n await dispatch({ type: \"run/dequeue\", runId, messageId: item.id });\n } catch {\n continue; // rejected dequeue: the item stays queued\n }\n texts.push(\n item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n );\n }\n if (texts.length === 0) return;\n const setText = composerApi.setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => [prev, ...texts].filter(Boolean).join(\"\\n\\n\"));\n };\n\n const { status, runs } = useMemo((): {\n status: StatewireThread.ThreadStatus;\n runs: StatewireThread.Runs;\n } => {\n const entries = (\n state as { runs?: readonly StatewireThread.RunState[] } | undefined\n )?.runs;\n const entry = entries?.[0];\n const failedEntries = failed.flatMap(\n (failure): StatewireThread.RunsFailedEntry[] => {\n const command = failedRunCommand(failure);\n return command === undefined\n ? []\n : [{ ...command.message, sendFailure: failure.failure }];\n },\n );\n return {\n status: presentStatus(\n entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n connection,\n ),\n runs:\n entry === undefined && failedEntries.length === 0\n ? RESTING_RUNS\n : {\n ...(entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n ...(entry.epoch !== undefined && { epoch: entry.epoch }),\n ...(entry.stopReason !== undefined && {\n stopReason: entry.stopReason,\n }),\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && {\n stopping: entry.stopping,\n }),\n ...(entry.nextDispatch !== undefined && {\n nextDispatch: entry.nextDispatch,\n }),\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n ...(entry.error !== undefined && { error: entry.error }),\n }),\n failed: failedEntries,\n },\n };\n }, [state, connection, failed]);\n\n const { converter } = options;\n const mounted = useSyncExternalStore(\n documents?.subscribe ?? noopSubscribe,\n () => documents?.list() ?? NO_DOCUMENTS,\n () => documents?.list() ?? NO_DOCUMENTS,\n );\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n runs,\n documents,\n mounted,\n invoke,\n }),\n [pending, connection, runs, documents, mounted, invoke],\n );\n const converted = useMemo(\n (): StatewireThread.State => converter(state, metadata),\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const liveRunId = runs.runId;\n\n const queue = useMemo(\n () =>\n createRunQueueAdapter(\n messages,\n liveRunId,\n runs.queue,\n runs.steerQueue,\n dispatch,\n dispatchSend,\n ),\n [messages, liveRunId, runs, dispatch, dispatchSend],\n );\n\n const branches = useMemo(\n () => createBranchCommandAdapter(messages, dispatch),\n [messages, dispatch],\n );\n\n const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo((): StatewireThread.Extras => {\n const takeFailed = (messageId: string): StatewireClient.FailedCommand => {\n const entry = failed.find(\n (f) => failedRunCommand(f)?.message.id === messageId,\n );\n if (entry === undefined)\n throw new Error(`statewire: unknown failed entry \"${messageId}\"`);\n return entry;\n };\n return {\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n connection,\n documents,\n invoke,\n state: converted.state === undefined ? state : converted.state,\n status,\n isBusy,\n inputRequests,\n runs,\n retryFailed: (messageId) => {\n if (retrying.current.has(messageId)) return;\n const entry = takeFailed(messageId);\n const command = retryCommand(\n messages,\n liveRunId,\n failedRunCommand(entry)!,\n );\n retrying.current.add(messageId);\n const release = () => {\n retrying.current.delete(messageId);\n };\n try {\n discardFailed(entry);\n void dispatch(command).then(release, release);\n } catch (error) {\n release();\n throw error;\n }\n },\n discardFailed: (messageId) => discardFailed(takeFailed(messageId)),\n popFailed: (messageId) => {\n const entry = takeFailed(messageId);\n discardFailed(entry);\n return failedRunCommand(entry)!\n .message.parts.flatMap((p) => (p.type === \"text\" ? [p.text] : []))\n .join(\"\\n\\n\");\n },\n };\n }, [\n dispatch,\n connection,\n documents,\n invoke,\n state,\n converted.state,\n status,\n isBusy,\n inputRequests,\n runs,\n failed,\n discardFailed,\n messages,\n liveRunId,\n ]);\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message, liveRunId)\n : {\n type: \"run/steer\",\n ...sendFields(\n messages,\n liveRunId,\n toWireMessage(message, crypto.randomUUID()),\n ),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId, liveRunId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message, liveRunId));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning: status === \"running\",\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\n onNew: handleAppend,\n queue,\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () =>\n dispatch({\n type: \"run/continue\",\n ...(liveRunId !== null && { runId: liveRunId }),\n }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(options.capabilities?.unstable_switchBranch && { branches }),\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n const runId = runs.runId;\n void commands[\"run/stop\"]!({\n ...payload,\n runId,\n ...(runs.epoch !== undefined && { epoch: runs.epoch }),\n })\n .then((retracted) => popRetracted(retracted, runId))\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n\n const composerStorage = useResources(\n options.storage?.composer !== undefined\n ? [withKey(\"composer\", options.storage.composer)]\n : [],\n )[0];\n\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n const composer = threadRef.current!.composer();\n const draft = storage.read();\n if (draft === undefined || !composer.getState().isEmpty) return;\n composer.setText(draft.text);\n for (const attachment of draft.attachments) {\n composer\n .addAttachment({\n id: attachment.id,\n type: attachment.type,\n name: attachment.name,\n ...(attachment.contentType !== undefined && {\n contentType: attachment.contentType,\n }),\n content: attachment.content,\n })\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n }\n }, [composerStorage]);\n\n const { text: draftText, attachments: composerAttachments } =\n thread.getState().composer;\n const draftAttachments = useMemo(\n () =>\n composerAttachments\n .filter(\n (attachment): attachment is CompleteAttachment =>\n attachment.status.type === \"complete\",\n )\n .map(({ file: _file, ...record }) => record),\n [composerAttachments],\n );\n const [draftSync] = useState(() => ({ writingFor: undefined as unknown }));\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n // First run per storage is the baseline, not a change: never clear the\n // stored draft the restore effect is about to load.\n const isBaseline = draftSync.writingFor !== storage;\n draftSync.writingFor = storage;\n if (draftText === \"\" && draftAttachments.length === 0) {\n if (!isBaseline) storage.clear();\n return;\n }\n storage.write({ text: draftText, attachments: draftAttachments });\n }, [draftSync, composerStorage, draftText, draftAttachments]);\n\n return thread;\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\n\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n /** A composer draft as persisted: the text plus the completed attachments. */\n export type ComposerDraft = {\n readonly text: string;\n readonly attachments: readonly CompleteAttachment[];\n };\n\n /** Composer draft storage seam; `write` must persist synchronously in the caller's flow. */\n export type ComposerStorage = {\n read(): ComposerDraft | undefined;\n write(draft: ComposerDraft): void;\n clear(): void;\n };\n\n export type Extras = {\n [symbolStatewireExtras]: true;\n /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */\n sendCommand: (command: Command) => Promise<unknown>;\n reconnect: () => void;\n connection: StatewireClient.ConnectionState;\n /** The mounted documents, or `undefined` on a transport without documents. */\n documents: StatewireDocuments.Source | undefined;\n /** Sends a statement on a negotiated protocol lane. */\n invoke: (\n protocol: string,\n method: string,\n params: readonly unknown[],\n ) => Promise<unknown>;\n /** The converter's `state` when it returns one, else the replicated state. */\n state: unknown;\n status: ThreadStatus;\n /** Negation of the server's broadcast idle level (a transport without idle is always busy). */\n isBusy: boolean;\n inputRequests: readonly InputRequestState[];\n runs: Runs;\n /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */\n retryFailed: (messageId: string) => void;\n /** Removes the failed entry; keyed by the entry's message id. */\n discardFailed: (messageId: string) => void;\n /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */\n popFailed: (messageId: string) => string;\n };\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n type RunSendCommand<TType extends \"run/enqueue\" | \"run/steer\"> = {\n readonly type: TType;\n /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: UserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunEnqueueCommand = RunSendCommand<\"run/enqueue\">;\n\n export type RunSteerCommand = RunSendCommand<\"run/steer\">;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly runId: string;\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n readonly runId?: string;\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly runId?: string;\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state; a present `response` key marks the entry answered. */\n export type InputRequestState = InputRequest & {\n readonly response?: InputResponse;\n /** The answer's `run/input` meta; absent when the answer carried none. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** Per-message branch metadata read from `metadata.custom.branch`: the message's own branch id and the fan-out's branch ids in creation order (own id included). */\n export type BranchMetadata = {\n readonly id: number;\n readonly siblings: readonly number[];\n };\n\n export type SwitchBranchCommand = {\n readonly type: \"message/switch-branch\";\n readonly branchId: number;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus = \"running\" | \"stopped\" | \"error\" | \"input-required\";\n\n /** The thread's status: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status; `\"evicted\"` and `\"disconnected\"` are client-derived from the connection, never replicated. */\n export type ThreadStatus =\n | \"loading\"\n | \"ready\"\n | \"evicted\"\n | \"disconnected\"\n | RunStatus;\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */\n export type RunsFailedEntry = RunsQueueEntry & {\n readonly sendFailure: StatewireClient.SendFailure;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** The run-starting op's meta; present only when carried. */\n readonly rootMeta?: ReadonlyJSONValue;\n /** Present when input outcomes ride the dispatch; visible until applied. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The stopping window: present while a stop of the live run is underway; `\"message-edit\"` / `\"message-reload\"` pair with `nextDispatch`. */\n export type RunsStopping = {\n readonly reason: \"stop\" | \"message-edit\" | \"message-reload\";\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */\n readonly epoch?: number;\n /** The reason carried by `run/stop`; persists through error/stop, cleared at the next dispatch. */\n readonly stopReason?: string | null;\n readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: \"ready\" | RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the state with unsettled commands folded in, resting defaults while no entry is live. */\n export type Runs = {\n /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */\n readonly epoch?: number;\n /** The reason carried by `run/stop`; persists through error/stop, cleared at the next dispatch. */\n readonly stopReason?: string | null;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */\n readonly failed: readonly RunsFailedEntry[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `connected`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\n runs: Runs;\n documents: StatewireDocuments.Source | undefined;\n /** The mounted documents as of this pass; a new map whenever one changes. */\n mounted: ReadonlyMap<number, StatewireDocuments.Document>;\n invoke: (\n protocol: string,\n method: string,\n params: readonly unknown[],\n ) => Promise<unknown>;\n };\n\n /** Converter output: app-owned keys only — the lib projects the run mounts itself; `state` replaces the replicated state on the extras and thread. */\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n /** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */\n initialState: T;\n /** Application protocol for optimistic commands; must match the transport's protocol. */\n protocol?: string | undefined;\n converter: StateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, applied, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n /** The host supports `message/switch-branch` (thread-global branch switching driven by `metadata.custom.branch`). */\n unstable_switchBranch?: boolean | undefined;\n }\n | undefined;\n /**\n * Durable drafts: the mounted composer storage restores on mount, mirrors\n * every change, and clears when the draft is consumed. The session storage\n * holds this thread's lane identity and its un-durable commands, which\n * resend under their original seqs on the next mount.\n */\n storage?:\n | {\n composer?: ResourceElement<ComposerStorage> | undefined;\n session?: ResourceElement<StatewireClient.SessionStorage> | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/core\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n messageSwitchBranch: StatewireThread.SwitchBranchCommand;\n }\n }\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;AAuDA,MAAM8C,+BACJ,IAAIG,IAAI;AACV,MAAMC,4BAA4B,CAAC;AAEnC,MAAaC,wBAAwBC,OAAO,kBAAkB;AAE9D,MAAaC,qBAAqBC,WAA4C;CAC5E,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEH,yBAAyBG,SAE3B,MAAM,IAAIG,MACR,mEACF;CAEF,OAAOH;AACT;AAEA,MAAMI,oBAAkE,CAAA;AAExE,MAAME,eAAqC;CACzCE,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,QAAQ,CAAA;AACV;;AAGA,MAAMC,oBACJC,UAOe;CACf,IACEA,MAAMO,YAAY,iBAClBP,MAAMO,YAAY,eAClBP,MAAMO,YAAY,YAElB,OAAOC,KAAAA;CACT,MAAMD,UAAUP,MAAMS,OAAO;CAG7B,IAAIF,SAASF,YAAYG,KAAAA,GAAW,OAAOA,KAAAA;CAC3C,OAAOD;AACT;AAIA,MAAMI,iBACJC,QACAE,eAEAF,WAAW,aACXE,WAAWF,WAAW,eACrBE,WAAWF,WAAW,aAAaE,WA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eAAegE,KAAAA,CAAkB,CAAC,CAAC4Q,IACrC"}
@@ -1 +1 @@
1
- {"version":3,"file":"runCommands.d.ts","names":[],"sources":["../src/runCommands.ts"],"mappings":";;;cAQa,gBACX,SAAS,eACT,eACC,gBAAgB;cAyEN,qBACX;EAAqB;KACrB,SAAS,eACT,yBACC,gBAAgB;;cAkBN,aACX;EAAqB;EAAY;IAAW;;KAC5C,sBACA,SAAS,gBAAgB;EAEzB;EACA,SAAS,gBAAgB;EACzB;;;cAWW,eACX;EAAqB;EAAY;IAAW;;KAC5C,sBACA,UACK,gBAAgB;EACf,SAAS,gBAAgB;MAE1B,gBAAgB;EACf,SAAS,gBAAgB;KAE3B,gBAAgB,mBACnB,gBAAgB;cAoBN,wBACX;EAAqB;KACrB,sBACA,qBAAqB,gBAAgB,gBACrC,0BAA0B,gBAAgB,gBAC1C,WAAW,SAAS,gBAAgB,qBACpC,eACE,SAAS,gBAAgB,YACzB,SAAS,2BAEV;;cA8EU,6BACX;EACE;EACA;IAAY,QAAQ;;KAEtB,WAAW,SAAS,gBAAgB,iCACnC;cAiBU,uBACX;EAAqB;EAAY;KACjC,yBACA,yBACC,gBAAgB"}
1
+ {"version":3,"file":"runCommands.d.ts","names":[],"sources":["../src/runCommands.ts"],"mappings":";;;cAQa,gBACX,SAAS,eACT,eACC,gBAAgB;cAgFN,qBACX;EAAqB;KACrB,SAAS,eACT,yBACC,gBAAgB;;cAkBN,aACX;EAAqB;EAAY;IAAW;;KAC5C,sBACA,SAAS,gBAAgB;EAEzB;EACA,SAAS,gBAAgB;EACzB;;;cAWW,eACX;EAAqB;EAAY;IAAW;;KAC5C,sBACA,UACK,gBAAgB;EACf,SAAS,gBAAgB;MAE1B,gBAAgB;EACf,SAAS,gBAAgB;KAE3B,gBAAgB,mBACnB,gBAAgB;cAoBN,wBACX;EAAqB;KACrB,sBACA,qBAAqB,gBAAgB,gBACrC,0BAA0B,gBAAgB,gBAC1C,WAAW,SAAS,gBAAgB,qBACpC,eACE,SAAS,gBAAgB,YACzB,SAAS,2BAEV;;cA8EU,6BACX;EACE;EACA;IAAY,QAAQ;;KAEtB,WAAW,SAAS,gBAAgB,iCACnC;cAiBU,uBACX;EAAqB;EAAY;KACjC,yBACA,yBACC,gBAAgB"}
@@ -25,7 +25,8 @@ const toWireMessage = (message, id) => {
25
25
  return {
26
26
  id,
27
27
  role: "user",
28
- parts
28
+ parts,
29
+ ...message.metadata?.custom !== void 0 && { metadata: JSON.parse(JSON.stringify(message.metadata.custom)) }
29
30
  };
30
31
  };
31
32
  const toQueueItemState = (item) => ({
@@ -1 +1 @@
1
- {"version":3,"file":"runCommands.js","names":["AppendMessage","ExternalThreadBranchAdapter","ExternalThreadQueueAdapter","QueuePlacement","StatewireThread","toWireMessage","message","id","UserMessage","role","Error","files","FilePart","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","undefined","parts","TextPart","length","const","join","toQueueItemState","item","RunQueueItem","prompt","map","placementFields","placement","insertAfter","insertBefore","viewedLeafId","messages","status","i","resolveEditCommand","runId","RunEditCommand","sourceId","index","findIndex","m","crypto","randomUUID","runAnchorMessageId","sendFields","retryCommand","command","RunEnqueueCommand","RunSteerCommand","RunCommand","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","dispatchSend","liveRunId","laneOf","queueItemId","some","sendCommand","lane","fields","items","steerItems","enqueue","steer","move","messageId","edit","wireMessage","remove","branchOf","metadata","custom","Record","BranchMetadata","branch","siblings","Number","isInteger","Array","isArray","every","includes","createBranchCommandAdapter","SwitchBranchCommand","getBranches","find","sibling","String","switchToBranch","branchId","target","resolveReloadCommand","parentId","RunReloadCommand"],"sources":["../src/runCommands.ts"],"sourcesContent":["import type {\n AppendMessage,\n ExternalThreadBranchAdapter,\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"@assistant-ui/core\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nexport const toWireMessage = (\n message: AppendMessage,\n id: string,\n): StatewireThread.UserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: StatewireThread.FilePart[] = [];\n const texts: string[] = [];\n const source = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const part of source) {\n if (part.type === \"text\") {\n texts.push(part.text);\n } else if (part.type === \"image\") {\n files.push({ type: \"file\", mediaType: \"image/*\", url: part.image });\n } else if (part.type === \"file\") {\n files.push({\n type: \"file\",\n mediaType: part.mimeType,\n url: part.data,\n ...(part.filename !== undefined && { filename: part.filename }),\n });\n } else {\n throw new Error(`statewire: unsupported message part \"${part.type}\"`);\n }\n }\n // default-safe against host capabilities: files first, one merged text part\n const parts: (StatewireThread.TextPart | StatewireThread.FilePart)[] = [\n ...files,\n ...(texts.length > 0\n ? [{ type: \"text\" as const, text: texts.join(\"\\n\\n\") }]\n : []),\n ];\n if (parts.length === 0)\n throw new Error(\"statewire: cannot send an empty message\");\n return { id, role: \"user\", parts };\n};\n\nconst toQueueItemState = (item: StatewireThread.RunQueueItem) => ({\n id: item.id,\n prompt: item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n parts: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n});\n\nconst placementFields = (placement: QueuePlacement) => ({\n ...(placement.insertAfter !== undefined && {\n insertAfter: placement.insertAfter,\n }),\n ...(placement.insertBefore !== undefined && {\n insertBefore: placement.insertBefore,\n }),\n});\n\nconst viewedLeafId = (\n messages: readonly { id: string; status?: { type: string } }[],\n): string | null => {\n // An in-flight assistant message is not host-committed history: anchor below it.\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]!.status?.type !== \"running\") return messages[i]!.id;\n }\n return null;\n};\n\nexport const resolveEditCommand = (\n messages: readonly { id: string }[],\n message: AppendMessage,\n runId: string | null,\n): StatewireThread.RunEditCommand => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n const index = messages.findIndex((m) => m.id === message.sourceId);\n if (index === -1)\n throw new Error(\n `statewire: run/edit source \"${message.sourceId}\" is unknown`,\n );\n return {\n type: \"run/edit\",\n runId: runId ?? crypto.randomUUID(),\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n runAnchorMessageId: messages[index - 1]?.id ?? null,\n };\n};\n\n/** The send fields for a run-creating or run-targeting enqueue/steer: target the live run, or mint a fresh one anchored at the viewed leaf. */\nexport const sendFields = (\n messages: readonly { id: string; status?: { type: string } }[],\n runId: string | null,\n message: StatewireThread.UserMessage,\n): {\n runId: string;\n message: StatewireThread.UserMessage;\n runAnchorMessageId?: string | null;\n} =>\n runId !== null\n ? { runId, message }\n : {\n runId: crypto.randomUUID(),\n message,\n runAnchorMessageId: viewedLeafId(messages),\n };\n\n/** Rebuilds a failed send against the current thread: edits re-anchor at the source's current parent, sends whose target run is gone fall back to a fresh enqueue. */\nexport const retryCommand = (\n messages: readonly { id: string; status?: { type: string } }[],\n runId: string | null,\n command:\n | (StatewireThread.RunEnqueueCommand & {\n message: StatewireThread.UserMessage;\n })\n | (StatewireThread.RunSteerCommand & {\n message: StatewireThread.UserMessage;\n })\n | StatewireThread.RunEditCommand,\n): StatewireThread.RunCommand => {\n if (command.type === \"run/edit\") {\n const index = messages.findIndex((m) => m.id === command.sourceId);\n if (index === -1)\n throw new Error(\n `statewire: run/edit source \"${command.sourceId}\" is unknown`,\n );\n return {\n ...command,\n runId: runId ?? crypto.randomUUID(),\n runAnchorMessageId: messages[index - 1]?.id ?? null,\n };\n }\n if (runId !== null && command.runId === runId) return command;\n return {\n type: \"run/enqueue\",\n ...sendFields(messages, runId, command.message),\n };\n};\n\nexport const createRunQueueAdapter = (\n messages: readonly { id: string }[],\n runId: string | null,\n queueItems: readonly StatewireThread.RunQueueItem[],\n steerQueueItems: readonly StatewireThread.RunQueueItem[],\n dispatch: (command: StatewireThread.RunCommand) => void,\n dispatchSend: (\n command: StatewireThread.RunCommand,\n message: AppendMessage,\n ) => void,\n): ExternalThreadQueueAdapter => {\n const liveRunId = (): string => {\n if (runId === null) throw new Error(\"statewire: no live run to target\");\n return runId;\n };\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems.some((item) => item.id === queueItemId)) return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n // edit-composer sends carry a sourceId; they bypass the lanes into run/edit\n const sendCommand = (\n lane: \"queue\" | \"steer\",\n message: AppendMessage,\n ): StatewireThread.RunCommand => {\n if (message.sourceId != null)\n return resolveEditCommand(messages, message, runId);\n const fields = sendFields(\n messages,\n runId,\n toWireMessage(message, crypto.randomUUID()),\n );\n return lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields };\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: steerQueueItems.map(toQueueItemState),\n enqueue: (message) => dispatchSend(sendCommand(\"queue\", message), message),\n steer: (message) => dispatchSend(sendCommand(\"steer\", message), message),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\n runId: liveRunId(),\n messageId: queueItemId,\n ...placementFields(placement),\n };\n dispatch(\n lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields },\n );\n },\n edit: (queueItemId, message) => {\n const wireMessage = toWireMessage(message, queueItemId);\n dispatch(\n laneOf(queueItemId) === \"steer\"\n ? { type: \"run/steer\", runId: liveRunId(), message: wireMessage }\n : { type: \"run/enqueue\", runId: liveRunId(), message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({\n type: \"run/dequeue\",\n runId: liveRunId(),\n messageId: queueItemId,\n }),\n };\n};\n\nconst branchOf = (\n message: { metadata: { custom: Record<string, unknown> } } | undefined,\n): StatewireThread.BranchMetadata | undefined => {\n const branch = message?.metadata.custom[\"branch\"];\n if (branch === undefined) return undefined;\n const { id, siblings } = branch as StatewireThread.BranchMetadata;\n if (\n !Number.isInteger(id) ||\n !Array.isArray(siblings) ||\n !siblings.every(Number.isInteger) ||\n !siblings.includes(id)\n )\n throw new Error(\"statewire: malformed branch metadata\");\n return { id, siblings };\n};\n\n/** Branch surface over the host's thread-global branch: siblings come from `metadata.custom.branch`, switching sends `message/switch-branch`. */\nexport const createBranchCommandAdapter = (\n messages: readonly {\n id: string;\n metadata: { custom: Record<string, unknown> };\n }[],\n dispatch: (command: StatewireThread.SwitchBranchCommand) => void,\n): ExternalThreadBranchAdapter => ({\n getBranches: (messageId) => {\n const branch = branchOf(messages.find((m) => m.id === messageId));\n if (branch === undefined) return [];\n // the own slot carries the message id so the picker can locate its position\n return branch.siblings.map((sibling) =>\n sibling === branch.id ? messageId : String(sibling),\n );\n },\n switchToBranch: (branchId) => {\n const target = Number(branchId);\n if (!Number.isInteger(target))\n throw new Error(`statewire: unknown branch \"${branchId}\"`);\n dispatch({ type: \"message/switch-branch\", branchId: target });\n },\n});\n\nexport const resolveReloadCommand = (\n messages: readonly { id: string; role: string }[],\n parentId: string | null,\n runId: string | null,\n): StatewireThread.RunReloadCommand => {\n const index =\n parentId === null\n ? 0\n : messages.findIndex((message) => message.id === parentId) + 1;\n if (parentId !== null && index === 0)\n throw new Error(`statewire: run/reload parent \"${parentId}\" is unknown`);\n const target = messages[index];\n if (target === undefined || target.role !== \"assistant\")\n throw new Error(\n \"statewire: run/reload requires an assistant message to regenerate\",\n );\n return {\n type: \"run/reload\",\n runId: runId ?? crypto.randomUUID(),\n sourceId: target.id,\n runAnchorMessageId: parentId,\n };\n};\n"],"mappings":";AAQA,MAAaK,iBACXC,SACAC,OACgC;CAChC,IAAID,QAAQG,SAAS,QACnB,MAAM,IAAIC,MAAM,6CAA6C;CAC/D,MAAMC,QAAoC,CAAA;CAC1C,MAAME,QAAkB,CAAA;CACxB,MAAMC,SAAS,CACb,G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AM,GAC1B,MAAM,IAAIhG,MAAM,8BAA8B+F,SAAQ,EAAG;EAC3DtC,SAAS;GAAE/C,MAAM;GAAyBqF,UAAUC;EAAO,CAAC;CAC9D;AACF;AAEA,MAAaC,wBACX9D,UACA+D,UACA3D,UACqC;CACrC,MAAMG,QACJwD,aAAa,OACT,IACA/D,SAASQ,WAAW/C,YAAYA,QAAQC,OAAOqG,QAAQ,IAAI;CACjE,IAAIA,aAAa,QAAQxD,UAAU,GACjC,MAAM,IAAI1C,MAAM,iCAAiCkG,SAAQ,aAAc;CACzE,MAAMF,SAAS7D,SAASO;CACxB,IAAIsD,WAAW7E,KAAAA,KAAa6E,OAAOjG,SAAS,aAC1C,MAAM,IAAIC,MACR,mEACF;CACF,OAAO;EACLU,MAAM;EACN6B,OAAOA,SAASM,OAAOC,WAAW;EAClCL,UAAUuD,OAAOnG;EACjBkD,oBAAoBmD;CACtB;AACF"}
1
+ {"version":3,"file":"runCommands.js","names":["AppendMessage","ExternalThreadBranchAdapter","ExternalThreadQueueAdapter","QueuePlacement","StatewireThread","toWireMessage","message","id","UserMessage","role","Error","files","FilePart","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","undefined","parts","TextPart","length","const","join","metadata","custom","JSON","parse","stringify","toQueueItemState","item","RunQueueItem","prompt","map","placementFields","placement","insertAfter","insertBefore","viewedLeafId","messages","status","i","resolveEditCommand","runId","RunEditCommand","sourceId","index","findIndex","m","crypto","randomUUID","runAnchorMessageId","sendFields","retryCommand","command","RunEnqueueCommand","RunSteerCommand","RunCommand","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","dispatchSend","liveRunId","laneOf","queueItemId","some","sendCommand","lane","fields","items","steerItems","enqueue","steer","move","messageId","edit","wireMessage","remove","branchOf","Record","BranchMetadata","branch","siblings","Number","isInteger","Array","isArray","every","includes","createBranchCommandAdapter","SwitchBranchCommand","getBranches","find","sibling","String","switchToBranch","branchId","target","resolveReloadCommand","parentId","RunReloadCommand"],"sources":["../src/runCommands.ts"],"sourcesContent":["import type {\n AppendMessage,\n ExternalThreadBranchAdapter,\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"@assistant-ui/core\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nexport const toWireMessage = (\n message: AppendMessage,\n id: string,\n): StatewireThread.UserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: StatewireThread.FilePart[] = [];\n const texts: string[] = [];\n const source = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const part of source) {\n if (part.type === \"text\") {\n texts.push(part.text);\n } else if (part.type === \"image\") {\n files.push({ type: \"file\", mediaType: \"image/*\", url: part.image });\n } else if (part.type === \"file\") {\n files.push({\n type: \"file\",\n mediaType: part.mimeType,\n url: part.data,\n ...(part.filename !== undefined && { filename: part.filename }),\n });\n } else {\n throw new Error(`statewire: unsupported message part \"${part.type}\"`);\n }\n }\n // default-safe against host capabilities: files first, one merged text part\n const parts: (StatewireThread.TextPart | StatewireThread.FilePart)[] = [\n ...files,\n ...(texts.length > 0\n ? [{ type: \"text\" as const, text: texts.join(\"\\n\\n\") }]\n : []),\n ];\n if (parts.length === 0)\n throw new Error(\"statewire: cannot send an empty message\");\n return {\n id,\n role: \"user\",\n parts,\n ...(message.metadata?.custom !== undefined && {\n metadata: JSON.parse(JSON.stringify(message.metadata.custom)),\n }),\n };\n};\n\nconst toQueueItemState = (item: StatewireThread.RunQueueItem) => ({\n id: item.id,\n prompt: item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n parts: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n});\n\nconst placementFields = (placement: QueuePlacement) => ({\n ...(placement.insertAfter !== undefined && {\n insertAfter: placement.insertAfter,\n }),\n ...(placement.insertBefore !== undefined && {\n insertBefore: placement.insertBefore,\n }),\n});\n\nconst viewedLeafId = (\n messages: readonly { id: string; status?: { type: string } }[],\n): string | null => {\n // An in-flight assistant message is not host-committed history: anchor below it.\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]!.status?.type !== \"running\") return messages[i]!.id;\n }\n return null;\n};\n\nexport const resolveEditCommand = (\n messages: readonly { id: string }[],\n message: AppendMessage,\n runId: string | null,\n): StatewireThread.RunEditCommand => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n const index = messages.findIndex((m) => m.id === message.sourceId);\n if (index === -1)\n throw new Error(\n `statewire: run/edit source \"${message.sourceId}\" is unknown`,\n );\n return {\n type: \"run/edit\",\n runId: runId ?? crypto.randomUUID(),\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n runAnchorMessageId: messages[index - 1]?.id ?? null,\n };\n};\n\n/** The send fields for a run-creating or run-targeting enqueue/steer: target the live run, or mint a fresh one anchored at the viewed leaf. */\nexport const sendFields = (\n messages: readonly { id: string; status?: { type: string } }[],\n runId: string | null,\n message: StatewireThread.UserMessage,\n): {\n runId: string;\n message: StatewireThread.UserMessage;\n runAnchorMessageId?: string | null;\n} =>\n runId !== null\n ? { runId, message }\n : {\n runId: crypto.randomUUID(),\n message,\n runAnchorMessageId: viewedLeafId(messages),\n };\n\n/** Rebuilds a failed send against the current thread: edits re-anchor at the source's current parent, sends whose target run is gone fall back to a fresh enqueue. */\nexport const retryCommand = (\n messages: readonly { id: string; status?: { type: string } }[],\n runId: string | null,\n command:\n | (StatewireThread.RunEnqueueCommand & {\n message: StatewireThread.UserMessage;\n })\n | (StatewireThread.RunSteerCommand & {\n message: StatewireThread.UserMessage;\n })\n | StatewireThread.RunEditCommand,\n): StatewireThread.RunCommand => {\n if (command.type === \"run/edit\") {\n const index = messages.findIndex((m) => m.id === command.sourceId);\n if (index === -1)\n throw new Error(\n `statewire: run/edit source \"${command.sourceId}\" is unknown`,\n );\n return {\n ...command,\n runId: runId ?? crypto.randomUUID(),\n runAnchorMessageId: messages[index - 1]?.id ?? null,\n };\n }\n if (runId !== null && command.runId === runId) return command;\n return {\n type: \"run/enqueue\",\n ...sendFields(messages, runId, command.message),\n };\n};\n\nexport const createRunQueueAdapter = (\n messages: readonly { id: string }[],\n runId: string | null,\n queueItems: readonly StatewireThread.RunQueueItem[],\n steerQueueItems: readonly StatewireThread.RunQueueItem[],\n dispatch: (command: StatewireThread.RunCommand) => void,\n dispatchSend: (\n command: StatewireThread.RunCommand,\n message: AppendMessage,\n ) => void,\n): ExternalThreadQueueAdapter => {\n const liveRunId = (): string => {\n if (runId === null) throw new Error(\"statewire: no live run to target\");\n return runId;\n };\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems.some((item) => item.id === queueItemId)) return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n // edit-composer sends carry a sourceId; they bypass the lanes into run/edit\n const sendCommand = (\n lane: \"queue\" | \"steer\",\n message: AppendMessage,\n ): StatewireThread.RunCommand => {\n if (message.sourceId != null)\n return resolveEditCommand(messages, message, runId);\n const fields = sendFields(\n messages,\n runId,\n toWireMessage(message, crypto.randomUUID()),\n );\n return lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields };\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: steerQueueItems.map(toQueueItemState),\n enqueue: (message) => dispatchSend(sendCommand(\"queue\", message), message),\n steer: (message) => dispatchSend(sendCommand(\"steer\", message), message),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\n runId: liveRunId(),\n messageId: queueItemId,\n ...placementFields(placement),\n };\n dispatch(\n lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields },\n );\n },\n edit: (queueItemId, message) => {\n const wireMessage = toWireMessage(message, queueItemId);\n dispatch(\n laneOf(queueItemId) === \"steer\"\n ? { type: \"run/steer\", runId: liveRunId(), message: wireMessage }\n : { type: \"run/enqueue\", runId: liveRunId(), message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({\n type: \"run/dequeue\",\n runId: liveRunId(),\n messageId: queueItemId,\n }),\n };\n};\n\nconst branchOf = (\n message: { metadata: { custom: Record<string, unknown> } } | undefined,\n): StatewireThread.BranchMetadata | undefined => {\n const branch = message?.metadata.custom[\"branch\"];\n if (branch === undefined) return undefined;\n const { id, siblings } = branch as StatewireThread.BranchMetadata;\n if (\n !Number.isInteger(id) ||\n !Array.isArray(siblings) ||\n !siblings.every(Number.isInteger) ||\n !siblings.includes(id)\n )\n throw new Error(\"statewire: malformed branch metadata\");\n return { id, siblings };\n};\n\n/** Branch surface over the host's thread-global branch: siblings come from `metadata.custom.branch`, switching sends `message/switch-branch`. */\nexport const createBranchCommandAdapter = (\n messages: readonly {\n id: string;\n metadata: { custom: Record<string, unknown> };\n }[],\n dispatch: (command: StatewireThread.SwitchBranchCommand) => void,\n): ExternalThreadBranchAdapter => ({\n getBranches: (messageId) => {\n const branch = branchOf(messages.find((m) => m.id === messageId));\n if (branch === undefined) return [];\n // the own slot carries the message id so the picker can locate its position\n return branch.siblings.map((sibling) =>\n sibling === branch.id ? messageId : String(sibling),\n );\n },\n switchToBranch: (branchId) => {\n const target = Number(branchId);\n if (!Number.isInteger(target))\n throw new Error(`statewire: unknown branch \"${branchId}\"`);\n dispatch({ type: \"message/switch-branch\", branchId: target });\n },\n});\n\nexport const resolveReloadCommand = (\n messages: readonly { id: string; role: string }[],\n parentId: string | null,\n runId: string | null,\n): StatewireThread.RunReloadCommand => {\n const index =\n parentId === null\n ? 0\n : messages.findIndex((message) => message.id === parentId) + 1;\n if (parentId !== null && index === 0)\n throw new Error(`statewire: run/reload parent \"${parentId}\" is unknown`);\n const target = messages[index];\n if (target === undefined || target.role !== \"assistant\")\n throw new Error(\n \"statewire: run/reload requires an assistant message to regenerate\",\n );\n return {\n type: \"run/reload\",\n runId: runId ?? crypto.randomUUID(),\n sourceId: target.id,\n runAnchorMessageId: parentId,\n };\n};\n"],"mappings":";AAQA,MAAaK,iBACXC,SACAC,OACgC;CAChC,IAAID,QAAQG,SAAS,QACnB,MAAM,IAAIC,MAAM,6CAA6C;CAC/D,MAAMC,QAAoC,CAAA;CAC1C,MAAME,QAAkB,CAAA;CACxB,MAAMC,SAAS,CACb,GAAGR,QAAQS,SACX,GAAIT,QAAQU,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAAG;CAE3D,KAAK,MAAMI,QAAQL,QACjB,IAAIK,KAAKC,SAAS,QAChBP,MAAMQ,KAAKF,KAAKG,IAAI;MACf,IAAIH,KAAKC,SAAS,SACvBT,MAAMU,KAAK;EAAED,MAAM;EAAQG,WAAW;EAAWC,KAAKL,KAAKM;CAAM,CAAC;MAC7D,IAAIN,KAAKC,SAAS,QACvBT,MAAMU,KAAK;EACTD,MAAM;EACNG,WAAWJ,KAAKO;EAChBF,KAAKL,KAAKQ;EACV,GAAIR,KAAKS,aAAaC,KAAAA,KAAa,EAAED,UAAUT,KAAKS,SAAS;CAC/D,CAAC;MAED,MAAM,IAAIlB,MAAM,wCAAwCS,KAAKC,KAAI,EAAG;CAIxE,MAAMU,QAAiE,CACrE,GAAGnB,OACH,GAAIE,MAAMmB,SAAS,IACf,CAAC;EAAEZ,MAAM;EAAiBE,MAAMT,MAAMqB,KAAK,MAAM;CAAE,CAAC,IACpD,CAAA,CAAG;CAET,IAAIJ,MAAME,WAAW,GACnB,MAAM,IAAItB,MAAM,yCAAyC;CAC3D,OAAO;EACLH;EACAE,MAAM;EACNqB;EACA,GAAIxB,QAAQ6B,UAAUC,WAAWP,KAAAA,KAAa,EAC5CM,UAAUE,KAAKC,MAAMD,KAAKE,UAAUjC,QAAQ6B,SAASC,MAAM,CAAC,EAC9D;CACF;AACF;AAEA,MAAMI,oBAAoBC,UAAwC;CACh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O;EAAEH;EAAIuF;CAAS;AACxB;;AAGA,MAAaO,8BACXnD,UAIAsB,cACiC;CACjC+B,cAAcjB,cAAc;EAC1B,MAAMO,SAASH,SAASxC,SAASsD,MAAM7C,MAAMA,EAAEpD,OAAO+E,SAAS,CAAC;EAChE,IAAIO,WAAWhE,KAAAA,GAAW,OAAO,CAAA;EAEjC,OAAOgE,OAAOC,SAASlD,KAAK6D,YAC1BA,YAAYZ,OAAOtF,KAAK+E,YAAYoB,OAAOD,OAAO,CACpD;CACF;CACAE,iBAAiBC,aAAa;EAC5B,MAAMC,SAASd,OAAOa,QAAQ;EAC9B,IAAI,CAACb,OAAOC,UAAUa,MAAM,GAC1B,MAAM,IAAInG,MAAM,8BAA8BkG,SAAQ,EAAG;EAC3DpC,SAAS;GAAEpD,MAAM;GAAyBwF,UAAUC;EAAO,CAAC;CAC9D;AACF;AAEA,MAAaC,wBACX5D,UACA6D,UACAzD,UACqC;CACrC,MAAMG,QACJsD,aAAa,OACT,IACA7D,SAASQ,WAAWpD,YAAYA,QAAQC,OAAOwG,QAAQ,IAAI;CACjE,IAAIA,aAAa,QAAQtD,UAAU,GACjC,MAAM,IAAI/C,MAAM,iCAAiCqG,SAAQ,aAAc;CACzE,MAAMF,SAAS3D,SAASO;CACxB,IAAIoD,WAAWhF,KAAAA,KAAagF,OAAOpG,SAAS,aAC1C,MAAM,IAAIC,MACR,mEACF;CACF,OAAO;EACLU,MAAM;EACNkC,OAAOA,SAASM,OAAOC,WAAW;EAClCL,UAAUqD,OAAOtG;EACjBuD,oBAAoBiD;CACtB;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/react-statewire",
3
- "version": "0.29.0",
3
+ "version": "0.29.1",
4
4
  "description": "assistant-ui thread binding for statewire backends",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -38,7 +38,7 @@
38
38
  "@assistant-ui/store": "^0.3.0",
39
39
  "@assistant-ui/tap": "^0.9.7",
40
40
  "assistant-stream": "^0.3.37",
41
- "statewire": "^0.19.0"
41
+ "statewire": "^0.19.1"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "@assistant-ui/core": ">=0.3.12",
@@ -1,13 +1,13 @@
1
1
  // @vitest-environment jsdom
2
2
 
3
3
  // Contract tests for the composer draft storage seam: restore on mount,
4
- // synchronous write-through on change, clear when the draft is consumed.
4
+ // write-through in the commit that applies a change, clear when consumed.
5
5
 
6
6
  import { act, render, waitFor } from "@testing-library/react";
7
7
  import type { FC } from "react";
8
8
  import { useState } from "react";
9
9
  import { describe, expect, it } from "vitest";
10
- import { AuiProvider, useAui } from "@assistant-ui/store";
10
+ import { AuiConfig, AuiProvider, useAui } from "@assistant-ui/store";
11
11
  import { flushTapSync, resource } from "@assistant-ui/tap";
12
12
  import {
13
13
  StatewireReject,
@@ -84,7 +84,7 @@ const mountThread = (
84
84
  const [storage, setStorage] =
85
85
  useState<StatewireThread.Options<ServerState>["storage"]>();
86
86
  knobs.setStorage = (element) => setStorage({ composer: element });
87
- const aui = useAui({
87
+ const config = AuiConfig({
88
88
  thread: StatewireThread({
89
89
  initialState: { messages: [], status: "ready", runs: [] },
90
90
  converter,
@@ -93,7 +93,7 @@ const mountThread = (
93
93
  }),
94
94
  });
95
95
  return (
96
- <AuiProvider value={aui}>
96
+ <AuiProvider config={config}>
97
97
  <Capture />
98
98
  </AuiProvider>
99
99
  );
@@ -136,13 +136,11 @@ describe("StatewireThread composer draft storage", () => {
136
136
  });
137
137
  await waitFor(() => expect(composerOf(aui).getState().type).toBe("thread"));
138
138
 
139
- act(() => {
140
- flushTapSync(() => composerOf(aui).setText("hel"));
141
- // the write landed inside the flush — no await, no timers
142
- expect(store.cell.draft).toEqual({ text: "hel", attachments: [] });
143
- flushTapSync(() => composerOf(aui).setText("hello"));
144
- expect(store.cell.draft).toEqual({ text: "hello", attachments: [] });
145
- });
139
+ act(() => flushTapSync(() => composerOf(aui).setText("hel")));
140
+ // the write landed in the commit that applied the text — no await, no timers
141
+ expect(store.cell.draft).toEqual({ text: "hel", attachments: [] });
142
+ act(() => flushTapSync(() => composerOf(aui).setText("hello")));
143
+ expect(store.cell.draft).toEqual({ text: "hello", attachments: [] });
146
144
  expect(store.cell.log).toEqual(["write:hel", "write:hello"]);
147
145
  });
148
146
 
@@ -155,11 +153,9 @@ describe("StatewireThread composer draft storage", () => {
155
153
  });
156
154
  await waitFor(() => expect(composerOf(aui).getState().type).toBe("thread"));
157
155
 
158
- act(() => {
159
- flushTapSync(() => composerOf(aui).setText("hello"));
160
- flushTapSync(() => composerOf(aui).send());
161
- expect(store.cell.draft).toBeUndefined();
162
- });
156
+ act(() => flushTapSync(() => composerOf(aui).setText("hello")));
157
+ act(() => flushTapSync(() => composerOf(aui).send()));
158
+ expect(store.cell.draft).toBeUndefined();
163
159
  expect(store.cell.log).toEqual(["write:hello", "clear"]);
164
160
  await waitFor(() => expect(server.received).toHaveLength(1));
165
161
  });
@@ -7,7 +7,7 @@
7
7
  import { act, render, waitFor } from "@testing-library/react";
8
8
  import type { FC } from "react";
9
9
  import { describe, expect, it } from "vitest";
10
- import { AuiProvider, useAui } from "@assistant-ui/store";
10
+ import { AuiConfig, AuiProvider, useAui } from "@assistant-ui/store";
11
11
  import { StatewireHttp } from "statewire";
12
12
  import { asStatewireExtras, StatewireThread } from "./StatewireThread";
13
13
  import { useStatewireRuns } from "./hooks";
@@ -145,7 +145,7 @@ const mountThread = (
145
145
  return null;
146
146
  };
147
147
  const App: FC = () => {
148
- const aui = useAui({
148
+ const config = AuiConfig({
149
149
  thread: StatewireThread<ServerState>({
150
150
  initialState: INITIAL_STATE,
151
151
  converter,
@@ -153,7 +153,7 @@ const mountThread = (
153
153
  }),
154
154
  });
155
155
  return (
156
- <AuiProvider value={aui}>
156
+ <AuiProvider config={config}>
157
157
  <Capture />
158
158
  </AuiProvider>
159
159
  );
@@ -8,7 +8,7 @@
8
8
  import { act, render, waitFor } from "@testing-library/react";
9
9
  import type { FC } from "react";
10
10
  import { describe, expect, it } from "vitest";
11
- import { AuiProvider, useAui } from "@assistant-ui/store";
11
+ import { AuiConfig, AuiProvider, useAui } from "@assistant-ui/store";
12
12
  import { resource } from "@assistant-ui/tap";
13
13
  import {
14
14
  StatewireReject,
@@ -96,7 +96,7 @@ const mountThread = (
96
96
  return null;
97
97
  };
98
98
  const App: FC = () => {
99
- const aui = useAui({
99
+ const config = AuiConfig({
100
100
  thread: StatewireThread<ServerState>({
101
101
  initialState: { messages: [], status: "ready", runs: [] },
102
102
  converter,
@@ -104,7 +104,7 @@ const mountThread = (
104
104
  }),
105
105
  });
106
106
  return (
107
- <AuiProvider value={aui}>
107
+ <AuiProvider config={config}>
108
108
  <Capture />
109
109
  </AuiProvider>
110
110
  );
@@ -9,7 +9,7 @@ import { useState } from "react";
9
9
  import type { FC } from "react";
10
10
  import type { ExternalThreadMessage } from "@assistant-ui/core/store";
11
11
  import { describe, expect, it } from "vitest";
12
- import { AuiProvider, useAui } from "@assistant-ui/store";
12
+ import { AuiConfig, AuiProvider, useAui } from "@assistant-ui/store";
13
13
  import { resource, withKey } from "@assistant-ui/tap";
14
14
  import { StatewireHttp } from "statewire";
15
15
  import { useStatewireCommands, useStatewireState } from "statewire/host";
@@ -246,7 +246,7 @@ const mountThread = (
246
246
  return null;
247
247
  };
248
248
  const App: FC = () => {
249
- const aui = useAui({
249
+ const config = AuiConfig({
250
250
  thread: StatewireThread<RunsServerState>({
251
251
  initialState: INITIAL_STATE,
252
252
  converter,
@@ -254,7 +254,7 @@ const mountThread = (
254
254
  }),
255
255
  });
256
256
  return (
257
- <AuiProvider value={aui}>
257
+ <AuiProvider config={config}>
258
258
  <Capture />
259
259
  </AuiProvider>
260
260
  );
@@ -774,7 +774,7 @@ describe("StatewireThread runs mode", () => {
774
774
  withKey("a", serverA.transport),
775
775
  );
776
776
  cell.swap = () => setTransport(() => withKey("b", serverB.transport));
777
- const aui = useAui({
777
+ const config = AuiConfig({
778
778
  thread: StatewireThread<RunsServerState>({
779
779
  initialState: preload,
780
780
  converter,
@@ -782,7 +782,7 @@ describe("StatewireThread runs mode", () => {
782
782
  }),
783
783
  });
784
784
  return (
785
- <AuiProvider value={aui}>
785
+ <AuiProvider config={config}>
786
786
  <Capture />
787
787
  </AuiProvider>
788
788
  );
@@ -7,7 +7,7 @@ import { act, render, waitFor } from "@testing-library/react";
7
7
  import type { FC, ReactNode } from "react";
8
8
  import { useState } from "react";
9
9
  import { describe, expect, it } from "vitest";
10
- import { AuiProvider, useAui } from "@assistant-ui/store";
10
+ import { AuiConfig, AuiProvider, useAui } from "@assistant-ui/store";
11
11
  import { resource } from "@assistant-ui/tap";
12
12
  import {
13
13
  StatewireReject,
@@ -225,11 +225,11 @@ const mountThread = (
225
225
  return null;
226
226
  };
227
227
  const App: FC = () => {
228
- const aui = useAui({
228
+ const config = AuiConfig({
229
229
  thread: StatewireThread({ initialState: INITIAL_STATE, ...options }),
230
230
  });
231
231
  return (
232
- <AuiProvider value={aui}>
232
+ <AuiProvider config={config}>
233
233
  <Capture />
234
234
  {children}
235
235
  </AuiProvider>
@@ -586,7 +586,7 @@ describe("StatewireThread", () => {
586
586
  expect(seen).toHaveLength(2);
587
587
  });
588
588
 
589
- it("fires onConnectionChange with the status at first flush, then once per transition", async () => {
589
+ it("fires onConnectionChange with the initial status, then once per transition", async () => {
590
590
  const statuses: string[] = [];
591
591
  const mock = createMockTransport<ServerState>(INITIAL_STATE);
592
592
  mountThread({
@@ -595,11 +595,15 @@ describe("StatewireThread", () => {
595
595
  onConnectionChange: (connection) => statuses.push(connection.status),
596
596
  });
597
597
 
598
- await waitFor(() => expect(statuses).toEqual(["connected"]));
598
+ await waitFor(() =>
599
+ expect(statuses).toEqual(["connecting", "connected"]),
600
+ );
599
601
  await mock.finish("gone");
600
- await waitFor(() => expect(statuses).toEqual(["connected", "stopped"]));
602
+ await waitFor(() =>
603
+ expect(statuses).toEqual(["connecting", "connected", "stopped"]),
604
+ );
601
605
  await new Promise((r) => setTimeout(r, 20));
602
- expect(statuses).toEqual(["connected", "stopped"]);
606
+ expect(statuses).toEqual(["connecting", "connected", "stopped"]);
603
607
  });
604
608
 
605
609
  it("stays quiet on unrelated re-renders and callback identity changes", async () => {
@@ -610,7 +614,7 @@ describe("StatewireThread", () => {
610
614
  const App: FC = () => {
611
615
  const [, setTick] = useState(0);
612
616
  knobs.rerender = () => setTick((t) => t + 1);
613
- const aui = useAui({
617
+ const config = AuiConfig({
614
618
  thread: StatewireThread({
615
619
  initialState: INITIAL_STATE,
616
620
  transport: server.transport,
@@ -620,7 +624,7 @@ describe("StatewireThread", () => {
620
624
  statuses.push(connection.status),
621
625
  }),
622
626
  });
623
- return <AuiProvider value={aui}>{null}</AuiProvider>;
627
+ return <AuiProvider config={config}>{null}</AuiProvider>;
624
628
  };
625
629
  render(<App />);
626
630
 
@@ -694,6 +698,35 @@ describe("StatewireThread", () => {
694
698
  expect(contextValueOf(mock.commands[1]!)["system"]).toBe("be nice");
695
699
  });
696
700
 
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
+ });
706
+ const { aui } = mountThread({
707
+ transport: mock.transport,
708
+ converter,
709
+ contextSync: "command-send",
710
+ });
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");
716
+ act(() =>
717
+ asStatewireExtras(aui().thread().getState().extras).reconnect(),
718
+ );
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()
723
+ .modelContext()
724
+ .register({ getModelContext: () => ({}) });
725
+
726
+ await waitFor(() => expect(mock.commands).toHaveLength(1));
727
+ expect(contextValueOf(mock.commands[0]!)).toEqual({});
728
+ });
729
+
697
730
  it("stays off the wire without the option", async () => {
698
731
  const mock = createMockTransport<ServerState>(INITIAL_STATE);
699
732
  const { aui } = mountThread({ transport: mock.transport, converter });
@@ -898,6 +931,7 @@ describe("StatewireThread", () => {
898
931
  id: expect.any(String),
899
932
  role: "user",
900
933
  parts: [{ type: "text", text: "better question" }],
934
+ metadata: {},
901
935
  },
902
936
  }),
903
937
  );
@@ -937,6 +971,7 @@ describe("StatewireThread", () => {
937
971
  id: expect.any(String),
938
972
  role: "user",
939
973
  parts: [{ type: "text", text: "better question" }],
974
+ metadata: {},
940
975
  },
941
976
  },
942
977
  ]),
@@ -1328,6 +1363,45 @@ describe("StatewireThread", () => {
1328
1363
  return trackingConverter;
1329
1364
  };
1330
1365
 
1366
+ it("hands the converter and extras the documents, mounted map, invoke and connection", async () => {
1367
+ const passes: StatewireThread.ConnectionMetadata[] = [];
1368
+ const mock = createMockTransport<ServerState>(INITIAL_STATE);
1369
+ const { aui } = mountThread({
1370
+ transport: mock.transport,
1371
+ converter: (state, meta) => {
1372
+ passes.push(meta);
1373
+ return { ...converter(state, meta), state: { pass: passes.length } };
1374
+ },
1375
+ });
1376
+ await waitFor(() => expect(threadStatus(aui())).toBe("ready"));
1377
+ await mock.setState({
1378
+ ...INITIAL_STATE,
1379
+ messages: [{ id: "m1", role: "user", text: "hi" }],
1380
+ });
1381
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["hi"]));
1382
+
1383
+ const first = passes[0]!;
1384
+ const last = passes.at(-1)!;
1385
+ expect(passes.length).toBeGreaterThan(1);
1386
+ expect(last.documents).toBe(first.documents);
1387
+ expect(last.invoke).toBe(first.invoke);
1388
+ expect(last.mounted.get(0)?.value).toMatchObject({
1389
+ messages: [{ id: "m1" }],
1390
+ });
1391
+
1392
+ const extras = asStatewireExtras(aui().thread().getState().extras);
1393
+ expect(extras.connection.status).toBe("connected");
1394
+ expect(extras.documents).toBe(first.documents);
1395
+ expect(extras.invoke).toBe(first.invoke);
1396
+ expect(extras.state).toEqual({ pass: passes.length });
1397
+ void extras.invoke("default", "ping", [1]);
1398
+ await waitFor(() =>
1399
+ expect(mock.commands).toEqual([
1400
+ { protocol: "default", method: "ping", params: [1] },
1401
+ ]),
1402
+ );
1403
+ });
1404
+
1331
1405
  it("projects connection transitions into the converter", async () => {
1332
1406
  const seen: string[] = [];
1333
1407
  const mock = createMockTransport<ServerState>(INITIAL_STATE);
@@ -1366,9 +1440,13 @@ describe("StatewireThread", () => {
1366
1440
  await mock.finish("gone");
1367
1441
  await waitFor(() => expect(seen.at(-1)).toBe("stopped"));
1368
1442
 
1369
- asStatewireExtras(aui().thread().getState().extras).reconnect();
1443
+ act(() =>
1444
+ asStatewireExtras(aui().thread().getState().extras).reconnect(),
1445
+ );
1370
1446
 
1371
- await waitFor(() => expect(seen.at(-1)).toBe("connecting"));
1447
+ // A fresh episode: first dial at attempt 0, then the dead server fails it.
1448
+ expect(seen.at(-1)).toBe("connecting");
1449
+ await waitFor(() => expect(seen.at(-1)).toBe("retrying"));
1372
1450
  });
1373
1451
  });
1374
1452
  });
@@ -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,42 @@ 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
+ isBusy,
160
+ failed,
161
+ discardFailed,
162
+ } = useStatewire<unknown, AnyCommands>({
163
+ transport: options.transport,
164
+ onError: (error) => latest.current.onError?.(error),
165
+ storage: options.storage,
166
+ initialState: options.initialState,
167
+ ...(options.protocol !== undefined && { protocol: options.protocol }),
168
+ optimistic: (draft, command, ctx) => {
169
+ runsOptimistic(draft, command, ctx);
170
+ latest.current.optimistic?.(draft, command, ctx);
171
+ },
172
+ materialize: (draft: {}) => latest.current.materialize?.(draft),
173
+ onCommandChange: (update, ctx) => {
174
+ if (update.status === "applied" || update.status === "settled")
175
+ retire(update.params[0]);
176
+ latest.current.onCommandChange?.(update, ctx);
177
+ },
178
+ onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),
179
+ onConnectionChange: (connection) =>
180
+ latest.current.onConnectionChange?.(connection),
181
+ failureCovered: (state, entry) => {
182
+ const command = failedRunCommand(entry);
183
+ if (command === undefined) return false;
184
+ const messages = (state as { messages?: readonly { id: string }[] })
185
+ .messages;
186
+ return messages?.some((m) => m.id === command.message.id) ?? false;
187
+ },
188
+ });
170
189
 
171
190
  const discarded = useRef(new WeakSet<StatewireClient.FailedCommand>());
172
191
  // Effects can replay before the updated failed lane reaches the binding.
@@ -202,7 +221,14 @@ const useStatewireThread = (
202
221
  const key = JSON.stringify(value);
203
222
  if (key === syncState.lastSent) return;
204
223
  syncState.lastSent = key;
205
- void invokeRef.current(contextProtocol, "set", [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) {
@@ -330,14 +356,22 @@ const useStatewireThread = (
330
356
  }, [state, connection, failed]);
331
357
 
332
358
  const { converter } = options;
359
+ const mounted = useSyncExternalStore(
360
+ documents?.subscribe ?? noopSubscribe,
361
+ () => documents?.list() ?? NO_DOCUMENTS,
362
+ () => documents?.list() ?? NO_DOCUMENTS,
363
+ );
333
364
  const metadata = useMemo(
334
365
  (): StatewireThread.ConnectionMetadata => ({
335
366
  pendingCommands: [...pending],
336
367
  isSending: pending.length > 0,
337
368
  connection,
338
369
  runs,
370
+ documents,
371
+ mounted,
372
+ invoke,
339
373
  }),
340
- [pending, connection, runs],
374
+ [pending, connection, runs, documents, mounted, invoke],
341
375
  );
342
376
  const converted = useMemo(
343
377
  (): StatewireThread.State => converter(state, metadata),
@@ -381,7 +415,10 @@ const useStatewireThread = (
381
415
  [symbolStatewireExtras]: true,
382
416
  sendCommand: dispatch,
383
417
  reconnect: connection.reconnect,
384
- state,
418
+ connection,
419
+ documents,
420
+ invoke,
421
+ state: converted.state === undefined ? state : converted.state,
385
422
  status,
386
423
  isBusy,
387
424
  inputRequests,
@@ -417,8 +454,11 @@ const useStatewireThread = (
417
454
  };
418
455
  }, [
419
456
  dispatch,
420
- connection.reconnect,
457
+ connection,
458
+ documents,
459
+ invoke,
421
460
  state,
461
+ converted.state,
422
462
  status,
423
463
  isBusy,
424
464
  inputRequests,
@@ -590,6 +630,16 @@ export namespace StatewireThread {
590
630
  /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */
591
631
  sendCommand: (command: Command) => Promise<unknown>;
592
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. */
593
643
  state: unknown;
594
644
  status: ThreadStatus;
595
645
  /** Negation of the server's broadcast idle level (a transport without idle is always busy). */
@@ -743,6 +793,7 @@ export namespace StatewireThread {
743
793
  export type RunQueueItem = {
744
794
  readonly id: string;
745
795
  readonly parts: readonly (TextPart | FilePart)[];
796
+ readonly metadata?: Record<string, unknown>;
746
797
  };
747
798
 
748
799
  /** Run subsystem status replicated by the host. */
@@ -872,9 +923,17 @@ export namespace StatewireThread {
872
923
  connection: StatewireClient.ConnectionState;
873
924
  /** The typed runs read. */
874
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>;
875
934
  };
876
935
 
877
- /** 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. */
878
937
  export type State = {
879
938
  readonly messages: readonly ThreadMessage[];
880
939
  readonly state?: ReadonlyJSONValue;
@@ -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) => ({