@assistant-ui/react-statewire 0.15.2 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,6 +16,8 @@ declare namespace StatewireThread {
16
16
  reconnect: () => void;
17
17
  state: unknown;
18
18
  status: ThreadStatus;
19
+ /** Negation of the server's broadcast idle level (a transport without idle is always busy). */
20
+ isBusy: boolean;
19
21
  inputRequests: readonly InputRequestState[];
20
22
  runs: Runs;
21
23
  };
@@ -140,7 +142,7 @@ declare namespace StatewireThread {
140
142
  readonly response: InputResponse | null;
141
143
  readonly meta: ReadonlyJSONValue | null;
142
144
  };
143
- /** The dispatch record — the unacked batch handed to the run; absent between the ack and the next dispatch or take. */
145
+ /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */
144
146
  export type RunsDispatch = {
145
147
  readonly trigger: "message-send" | "message-edit" | "message-reload" | "input-resume" | "error-continue" | "stop-continue" | "steer";
146
148
  readonly messages: readonly RunsQueueEntry[];
@@ -148,7 +150,7 @@ declare namespace StatewireThread {
148
150
  readonly rollbackTo?: string | null;
149
151
  /** The run-starting op's meta; present only when carried. */
150
152
  readonly rootMeta?: ReadonlyJSONValue;
151
- /** Present when input outcomes ride the dispatch; visible until the ack. */
153
+ /** Present when input outcomes ride the dispatch; visible until applied. */
152
154
  readonly inputOutcomes?: readonly RunsInputOutcome[];
153
155
  };
154
156
  /** The stopping window: present while a stop of the live run is underway; `"message-edit"` / `"message-reload"` pair with `nextDispatch`. */
@@ -167,7 +169,7 @@ declare namespace StatewireThread {
167
169
  readonly status: RunStatus;
168
170
  readonly queue: readonly RunsQueueEntry[];
169
171
  readonly steerQueue: readonly RunsQueueEntry[];
170
- /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
172
+ /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */
171
173
  readonly dispatching?: RunsDispatch;
172
174
  readonly stopping?: RunsStopping;
173
175
  /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */
@@ -197,7 +199,7 @@ declare namespace StatewireThread {
197
199
  readonly runId: string | null;
198
200
  readonly queue: readonly RunsQueueEntry[];
199
201
  readonly steerQueue: readonly RunsQueueEntry[];
200
- /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
202
+ /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */
201
203
  readonly dispatching?: RunsDispatch;
202
204
  readonly stopping?: RunsStopping;
203
205
  /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */
@@ -246,7 +248,7 @@ declare namespace StatewireThread {
246
248
  contextSync?: "command-send" | undefined;
247
249
  /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */
248
250
  stopPayload?: (() => StopPayload) | undefined;
249
- /** Observes each command's lifecycle (queued, posted, acked, settled); runs after the built-in pending-command retirement. */
251
+ /** Observes each command's lifecycle (queued, posted, applied, settled); runs after the built-in pending-command retirement. */
250
252
  onCommandChange?: ((update: Statewire.CommandUpdate<Record<string, (...args: any[]) => unknown>>, ctx: {
251
253
  state: NonNullable<T>;
252
254
  }) => void) | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cAwCa;cAEA,oBAAqB,oBAAkB,gBAAgB;cAqRvD,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C,UAAU,KAAK,gBAAgB,UAAU;cAEzC;KACT;IACD,cAAc,SAAS;IACvB;IACA;IACA,QAAQ;IACR,wBAAwB;IACxB,MAAM;;cAGI;aACD;aACA;;cAGC;aACD;aACA;aACA;aACA;;cAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;cAIV;aACD;aACA;;cAGC;aACD;;aAEA;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;;aAEA;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAE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,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;;IAGN;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"}
1
+ {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cAwCa;cAEA,oBAAqB,oBAAkB,gBAAgB;cA4RvD,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C,UAAU,KAAK,gBAAgB,UAAU;cAEzC;KACT;IACD,cAAc,SAAS;IACvB;IACA;IACA,QAAQ;;IAER;IACA,wBAAwB;IACxB,MAAM;;cAGI;aACD;aACA;;cAGC;aACD;aACA;aACA;aACA;;cAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;cAIV;aACD;aACA;;cAGC;aACD;;aAEA;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;;aAEA;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;aACA;aACA;;cAGC;aACD;;aAEA;aACA,SAAS;aACT;;aAEA;;cAGC;aACD;aACA;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;cACC,cAAc;;;cAId,eACR,uBACA,2BACA;cAEQ,gBAAgB;cAEhB;aACD;aACA;aACA;aACA,UAAU;;;cAIT,oBAAoB;aACrB,WAAW;;aAEX,OAAO;;cAGN;aACD;;aAEA;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MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB"}
@@ -30,7 +30,7 @@ const useStatewireThread = (options) => {
30
30
  latest.current = options;
31
31
  const [pending, setPending] = useState([]);
32
32
  const [retire] = useState(() => (command) => setPending((prev) => prev.includes(command) ? prev.filter((c) => c !== command) : prev));
33
- const { state: state_0, commands, connection: connection_0, setContext } = useStatewire({
33
+ const { state: state_0, commands, connection: connection_0, setContext, isBusy } = useStatewire({
34
34
  transport: options.transport,
35
35
  initialState: options.initialState,
36
36
  optimistic: (draft, command_0, ctx) => {
@@ -39,7 +39,7 @@ const useStatewireThread = (options) => {
39
39
  },
40
40
  materialize: (draft_0) => latest.current.materialize?.(draft_0),
41
41
  onCommandChange: (update, ctx_0) => {
42
- if (update.status === "acked" || update.status === "settled") retire(update.params[0]);
42
+ if (update.status === "applied" || update.status === "settled") retire(update.params[0]);
43
43
  latest.current.onCommandChange?.(update, ctx_0);
44
44
  },
45
45
  onStateChange: (state, ctx_1) => latest.current.onStateChange?.(state, ctx_1),
@@ -58,9 +58,7 @@ const useStatewireThread = (options) => {
58
58
  const key = JSON.stringify(value);
59
59
  if (key === syncState.lastSent) return;
60
60
  syncState.lastSent = key;
61
- setContextRef.current(value).catch((error) => {
62
- latest.current.onError?.(error);
63
- });
61
+ setContextRef.current(value);
64
62
  };
65
63
  send();
66
64
  if (!modelContext.subscribe) throw new Error("statewire: contextSync requires a subscribable model context");
@@ -73,9 +71,9 @@ const useStatewireThread = (options) => {
73
71
  const dispatch = useCallback((command_1) => {
74
72
  setPending((prev_0) => [...prev_0, command_1]);
75
73
  const settled = commands[command_1.type](command_1);
76
- settled.catch((error_0) => {
74
+ settled.catch((error) => {
77
75
  retire(command_1);
78
- latest.current.onError?.(error_0);
76
+ latest.current.onError?.(error);
79
77
  });
80
78
  return settled;
81
79
  }, [commands, retire]);
@@ -137,6 +135,7 @@ const useStatewireThread = (options) => {
137
135
  reconnect: connection_0.reconnect,
138
136
  state: state_0,
139
137
  status,
138
+ isBusy,
140
139
  inputRequests,
141
140
  runs
142
141
  }), [
@@ -144,6 +143,7 @@ const useStatewireThread = (options) => {
144
143
  connection_0.reconnect,
145
144
  state_0,
146
145
  status,
146
+ isBusy,
147
147
  inputRequests,
148
148
  runs
149
149
  ]);
@@ -183,8 +183,8 @@ const useStatewireThread = (options) => {
183
183
  commands["run/stop"]({
184
184
  ...payload,
185
185
  runId: runs.runId
186
- }).catch((error_1) => {
187
- latest.current.onError?.(error_1);
186
+ }).catch((error_0) => {
187
+ latest.current.onError?.(error_0);
188
188
  });
189
189
  }
190
190
  }));
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","createRunQueueAdapter","resolveEditCommand","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","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","Options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","state","commands","connection","setContext","transport","initialState","optimistic","draft","ctx","materialize","onCommandChange","update","status","params","onStateChange","onConnectionChange","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","error","onError","subscribe","dispatch","settled","type","threadRef","dispatchSend","message","sourceId","text","content","flatMap","part","join","setText","composer","next","runs","ThreadStatus","entries","RunState","entry","dispatching","stopping","nextDispatch","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","State","messages","liveRunId","sendCommand","reconnect","handleAppend","crypto","randomUUID","handleReload","parentId","handleEdit","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","UserCommands","Commands","Transport","TextPart","FilePart","mediaType","url","filename","UserMessage","id","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","runAnchorMessageId","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","RunsQueueEntry","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","reason","RunsError","MaterializeEffects","append","rollback","to","RunsState","Exclude","ConnectionState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } 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 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 { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\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};\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\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, setContext } = useStatewire<\n unknown,\n AnyCommands\n >({\n transport: options.transport,\n initialState: options.initialState,\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 === \"acked\" || 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 });\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\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 setContextRef.current(value).catch((error: Error) => {\n latest.current.onError?.(error);\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, 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 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 return {\n status: entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n runs:\n entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && { stopping: entry.stopping }),\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 };\n }, [state]);\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 inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo(\n (): StatewireThread.Extras => ({\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n status,\n inputRequests,\n runs,\n }),\n [dispatch, connection.reconnect, state, status, inputRequests, runs],\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 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 void commands[\"run/stop\"]!({ ...payload, runId: runs.runId }).catch(\n (error: Error) => {\n latest.current.onError?.(error);\n },\n );\n },\n }),\n );\n threadRef.current = thread;\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 export type Extras = {\n [symbolStatewireExtras]: true;\n sendCommand: (command: Command) => void;\n reconnect: () => void;\n state: unknown;\n status: ThreadStatus;\n inputRequests: readonly InputRequestState[];\n runs: Runs;\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 export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\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 RunSteerCommand = {\n readonly type: \"run/steer\";\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 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 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, derived from the state: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status. */\n export type ThreadStatus = \"loading\" | \"ready\" | 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 /** 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 unacked batch handed to the run; absent between the ack 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 the ack. */\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 readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */\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: Exclude<ThreadStatus, \"loading\">;\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 readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */\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 export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\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 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, acked, 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 }\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 }\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":";;;;;;;;;;AAwCA,MAAasC,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;AACd;AAEA,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOlC,kBAAkB+B,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,sBACJC,YAC2B;CAC3B,MAAME,SAAS3D,OAAOyD,OAAO;CAC7BE,OAAOC,UAAUH;CAEjB,MAAM,CAACI,SAASC,cAAc7D,SAC5B,CAAA,CACF;CACA,MAAM,CAAC+D,UAAU/D,gBACRgE,YACLH,YAAYI,SACVA,KAAKC,SAASF,OAAkC,IAC5CC,KAAKE,QAAQC,MAAMA,MAAMJ,OAAO,IAChCC,IACN,CACJ;CAEA,MAAM,EAAEI,OAAAA,SAAOC,UAAUC,YAAAA,cAAYC,eAAepD,aAGlD;EACAqD,WAAWjB,QAAQiB;EACnBC,cAAclB,QAAQkB;EACtBC,aAAaC,OAAOZ,WAASa,QAAQ;GACnC/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CAAC+L,IACrC"}
1
+ {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","createRunQueueAdapter","resolveEditCommand","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","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","Options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","state","commands","connection","setContext","isBusy","transport","initialState","optimistic","draft","ctx","materialize","onCommandChange","update","status","params","onStateChange","onConnectionChange","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","subscribe","dispatch","settled","type","catch","error","onError","threadRef","dispatchSend","message","sourceId","text","content","flatMap","part","join","setText","composer","next","runs","ThreadStatus","entries","RunState","entry","dispatching","stopping","nextDispatch","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","State","messages","liveRunId","sendCommand","reconnect","handleAppend","crypto","randomUUID","handleReload","parentId","handleEdit","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","UserCommands","Commands","Transport","TextPart","FilePart","mediaType","url","filename","UserMessage","id","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","runAnchorMessageId","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","RunsQueueEntry","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","reason","RunsError","MaterializeEffects","append","rollback","to","RunsState","Exclude","ConnectionState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } 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 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 { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\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};\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\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, setContext, isBusy } = useStatewire<\n unknown,\n AnyCommands\n >({\n transport: options.transport,\n initialState: options.initialState,\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 });\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\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 setContextRef.current(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, 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 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 return {\n status: entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n runs:\n entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && { stopping: entry.stopping }),\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 };\n }, [state]);\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 inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo(\n (): StatewireThread.Extras => ({\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n }),\n [\n dispatch,\n connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n ],\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 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 void commands[\"run/stop\"]!({ ...payload, runId: runs.runId }).catch(\n (error: Error) => {\n latest.current.onError?.(error);\n },\n );\n },\n }),\n );\n threadRef.current = thread;\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 export type Extras = {\n [symbolStatewireExtras]: true;\n sendCommand: (command: Command) => void;\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 };\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 export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\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 RunSteerCommand = {\n readonly type: \"run/steer\";\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 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 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, derived from the state: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status. */\n export type ThreadStatus = \"loading\" | \"ready\" | 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 /** 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 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: Exclude<ThreadStatus, \"loading\">;\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 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 export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\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 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 }\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 }\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":";;;;;;;;;;AAwCA,MAAasC,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,oBAA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ACN,GAAIkC,cAAc,QAAQ,EAAE3F,OAAO2F,UAAU;EAC/C,CAAC,EACL;EACA,GAAIhF,QAAQmG,cAAcK,UAAU,EAAEC,UAAUnB,aAAa;EAC7DoB,kBAAkBC,gBAChB/D,SAASvE,uBAAuBiG,eAAeqC,aAAa3B,SAAS,CAAC;EACxE4B,0BAA0BC,aACxBjE,SAASxE,yBAAyBkG,eAAeuC,UAAU7B,SAAS,CAAC;EACvE8B,gBAAgB;GACd,MAAMC,UAAU7G,OAAOC,QAAQ6G,cAAc;GAC7C,IACED,YAAYpH,KAAAA,MACX,OAAOoH,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAI/H,MAAM,mDAAmD;GACrE,SAAc,WAAW,CAAE;IAAE,GAAG+H;IAAS1H,OAAOyE,KAAKzE;GAAM,CAAC,CAAC,CAAC0D,OAC3DC,YAAiB;IAChB9C,OAAOC,QAAQ8C,UAAUD,OAAK;GAChC,CACF;EACF;CACF,CAAC,CACH;CACAE,UAAU/C,UAAUsF;CACpB,OAAOA;AACT;AAEA,MAAa3G,mBACXkB,YAEAvD,SAASsD,kBAAkB,CAAC,CAACC,OAAuC;AA0WtEjD,uBACEgD,oBACAnD,eAAe+C,KAAAA,CAAkB,CAAC,CAACgM,IACrC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/react-statewire",
3
- "version": "0.15.2",
3
+ "version": "0.16.0",
4
4
  "description": "assistant-ui thread binding for statewire backends",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -33,7 +33,7 @@
33
33
  "@assistant-ui/store": "^0.3.0",
34
34
  "@assistant-ui/tap": "^0.9.7",
35
35
  "assistant-stream": "^0.3.37",
36
- "statewire": "^0.8.1"
36
+ "statewire": "^0.9.0"
37
37
  },
38
38
  "peerDependencies": {
39
39
  "@assistant-ui/core": ">=0.3.12",
@@ -128,7 +128,7 @@ const createRemoteServer = (
128
128
  opts?: { hold?: boolean },
129
129
  ) => {
130
130
  const received: { method: string; params: unknown[] }[] = [];
131
- const clients = new Map<string, number>();
131
+ const clients = new Map<string, { seq: number; ctxSeq: number }>();
132
132
  const encoder = new TextEncoder();
133
133
  const frame = (chunk: unknown) => `data: ${JSON.stringify(chunk)}\n\n`;
134
134
  let released = !(opts?.hold ?? false);
@@ -138,16 +138,32 @@ const createRemoteServer = (
138
138
  parkedSnapshot?.();
139
139
  parkedSnapshot = undefined;
140
140
  };
141
+ type Frame = {
142
+ ctx?: { seq: number }[];
143
+ cmd?: { method: string; params: unknown[]; seq: number }[];
144
+ };
145
+ const admit = (clientId: string, body: Frame) => {
146
+ const rec = clients.get(clientId)!;
147
+ for (const statement of body.ctx ?? []) {
148
+ rec.ctxSeq = Math.max(rec.ctxSeq, statement.seq);
149
+ }
150
+ for (const statement of body.cmd ?? []) {
151
+ rec.seq = Math.max(rec.seq, statement.seq);
152
+ received.push({ method: statement.method, params: statement.params });
153
+ }
154
+ };
141
155
  const fetchImpl = (async (input: RequestInfo | URL, init2?: RequestInit) => {
142
156
  const url = String(input);
143
157
  const headers = new Headers(init2?.headers);
144
158
  const clientId = headers.get("Statewire-Client-Id")!;
145
159
  if (url.endsWith("/stream")) {
146
- const known = clients.get(clientId);
147
- if (known === undefined) clients.set(clientId, 0);
160
+ const known = clients.has(clientId);
161
+ if (!known) clients.set(clientId, { seq: 0, ctxSeq: 0 });
162
+ const rec = clients.get(clientId)!;
163
+ const attachFrame = JSON.parse(String(init2?.body)) as Frame;
148
164
  const body = new ReadableStream<Uint8Array>({
149
165
  start: (c) => {
150
- const sendSnapshot = () =>
166
+ const sendSnapshot = () => {
151
167
  c.enqueue(
152
168
  encoder.encode(
153
169
  frame({
@@ -158,21 +174,29 @@ const createRemoteServer = (
158
174
  value: { ...INITIAL_STATE, ...init },
159
175
  },
160
176
  ],
161
- syn: { lastSeq: known ?? -1, lease: "lease-1" },
177
+ syn: {
178
+ seq: rec.seq,
179
+ ctxSeq: rec.ctxSeq,
180
+ record: known ? "resumed" : "fresh",
181
+ },
162
182
  }),
163
183
  ),
164
184
  );
185
+ admit(clientId, attachFrame);
186
+ };
165
187
  if (released) sendSnapshot();
166
188
  else parkedSnapshot = sendSnapshot;
167
189
  },
168
190
  });
169
191
  return new Response(body, {
170
192
  status: 200,
171
- headers: { "content-type": "text/event-stream" },
193
+ headers: {
194
+ "content-type": "text/event-stream",
195
+ "Statewire-Lease": "lease-1",
196
+ },
172
197
  });
173
198
  }
174
- clients.set(clientId, Number(headers.get("Statewire-Command-Seq")));
175
- received.push(JSON.parse(String(init2?.body)));
199
+ admit(clientId, JSON.parse(String(init2?.body)) as Frame);
176
200
  return Response.json({});
177
201
  }) as typeof fetch;
178
202
  return {
@@ -697,7 +721,7 @@ describe("StatewireThread runs mode", () => {
697
721
 
698
722
  server.release();
699
723
 
700
- // Attach posts the queued command; the still-unacked overlay survives the snapshot.
724
+ // Attach posts the queued command; the still-unapplied overlay survives the snapshot.
701
725
  await waitFor(() =>
702
726
  expect(server.received.map((c) => c.method)).toEqual(["run/enqueue"]),
703
727
  );
@@ -440,7 +440,7 @@ describe("StatewireThread", () => {
440
440
  expect(updates.map((u) => u.status)).toEqual([
441
441
  "queued",
442
442
  "posted",
443
- "acked",
443
+ "applied",
444
444
  "settled",
445
445
  ]),
446
446
  );
@@ -604,14 +604,8 @@ describe("StatewireThread", () => {
604
604
  });
605
605
 
606
606
  describe("contextSync: command-send", () => {
607
- const contextValueOf = (command: { context?: unknown }) => {
608
- const ops = command.context as [
609
- { op: string; path: unknown[]; value: unknown },
610
- ];
611
- expect(ops).toHaveLength(1);
612
- expect(ops[0]).toMatchObject({ op: "replace", path: [] });
613
- return ops[0].value as Record<string, unknown>;
614
- };
607
+ const contextValueOf = (command: { context?: unknown }) =>
608
+ command.context as Record<string, unknown>;
615
609
 
616
610
  it("sends the ambient model context on connect and on every change", async () => {
617
611
  const mock = createMockTransport<ServerState>(INITIAL_STATE);
@@ -90,7 +90,7 @@ const useStatewireThread = (
90
90
  ),
91
91
  );
92
92
 
93
- const { state, commands, connection, setContext } = useStatewire<
93
+ const { state, commands, connection, setContext, isBusy } = useStatewire<
94
94
  unknown,
95
95
  AnyCommands
96
96
  >({
@@ -102,7 +102,7 @@ const useStatewireThread = (
102
102
  },
103
103
  materialize: (draft: {}) => latest.current.materialize?.(draft),
104
104
  onCommandChange: (update, ctx) => {
105
- if (update.status === "acked" || update.status === "settled")
105
+ if (update.status === "applied" || update.status === "settled")
106
106
  retire(update.params[0]);
107
107
  latest.current.onCommandChange?.(update, ctx);
108
108
  },
@@ -124,9 +124,7 @@ const useStatewireThread = (
124
124
  const key = JSON.stringify(value);
125
125
  if (key === syncState.lastSent) return;
126
126
  syncState.lastSent = key;
127
- void setContextRef.current(value).catch((error: Error) => {
128
- latest.current.onError?.(error);
129
- });
127
+ setContextRef.current(value);
130
128
  };
131
129
  send();
132
130
  if (!modelContext.subscribe) {
@@ -242,10 +240,19 @@ const useStatewireThread = (
242
240
  reconnect: connection.reconnect,
243
241
  state,
244
242
  status,
243
+ isBusy,
245
244
  inputRequests,
246
245
  runs,
247
246
  }),
248
- [dispatch, connection.reconnect, state, status, inputRequests, runs],
247
+ [
248
+ dispatch,
249
+ connection.reconnect,
250
+ state,
251
+ status,
252
+ isBusy,
253
+ inputRequests,
254
+ runs,
255
+ ],
249
256
  );
250
257
 
251
258
  const handleAppend = (message: AppendMessage) => {
@@ -333,6 +340,8 @@ export namespace StatewireThread {
333
340
  reconnect: () => void;
334
341
  state: unknown;
335
342
  status: ThreadStatus;
343
+ /** Negation of the server's broadcast idle level (a transport without idle is always busy). */
344
+ isBusy: boolean;
336
345
  inputRequests: readonly InputRequestState[];
337
346
  runs: Runs;
338
347
  };
@@ -496,7 +505,7 @@ export namespace StatewireThread {
496
505
  readonly meta: ReadonlyJSONValue | null;
497
506
  };
498
507
 
499
- /** The dispatch record — the unacked batch handed to the run; absent between the ack and the next dispatch or take. */
508
+ /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */
500
509
  export type RunsDispatch = {
501
510
  readonly trigger:
502
511
  | "message-send"
@@ -511,7 +520,7 @@ export namespace StatewireThread {
511
520
  readonly rollbackTo?: string | null;
512
521
  /** The run-starting op's meta; present only when carried. */
513
522
  readonly rootMeta?: ReadonlyJSONValue;
514
- /** Present when input outcomes ride the dispatch; visible until the ack. */
523
+ /** Present when input outcomes ride the dispatch; visible until applied. */
515
524
  readonly inputOutcomes?: readonly RunsInputOutcome[];
516
525
  };
517
526
 
@@ -533,7 +542,7 @@ export namespace StatewireThread {
533
542
  readonly status: RunStatus;
534
543
  readonly queue: readonly RunsQueueEntry[];
535
544
  readonly steerQueue: readonly RunsQueueEntry[];
536
- /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
545
+ /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */
537
546
  readonly dispatching?: RunsDispatch;
538
547
  readonly stopping?: RunsStopping;
539
548
  /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */
@@ -566,7 +575,7 @@ export namespace StatewireThread {
566
575
  readonly runId: string | null;
567
576
  readonly queue: readonly RunsQueueEntry[];
568
577
  readonly steerQueue: readonly RunsQueueEntry[];
569
- /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
578
+ /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */
570
579
  readonly dispatching?: RunsDispatch;
571
580
  readonly stopping?: RunsStopping;
572
581
  /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */
@@ -628,7 +637,7 @@ export namespace StatewireThread {
628
637
  contextSync?: "command-send" | undefined;
629
638
  /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */
630
639
  stopPayload?: (() => StopPayload) | undefined;
631
- /** Observes each command's lifecycle (queued, posted, acked, settled); runs after the built-in pending-command retirement. */
640
+ /** Observes each command's lifecycle (queued, posted, applied, settled); runs after the built-in pending-command retirement. */
632
641
  onCommandChange?:
633
642
  | ((
634
643
  update: Statewire.CommandUpdate<
@@ -0,0 +1,33 @@
1
+ // @vitest-environment jsdom
2
+
3
+ // Contract: the broadcast idle flag's edges reach React through the normal
4
+ // subscription channel — a component reading isBusy re-renders on each edge.
5
+
6
+ import { render, waitFor } from "@testing-library/react";
7
+ import { describe, expect, it } from "vitest";
8
+ import { useStatewire } from "statewire";
9
+ import { createMockTransport } from "statewire/testing";
10
+
11
+ describe("useStatewire isBusy", () => {
12
+ it("re-renders on each idle edge", async () => {
13
+ const mock = createMockTransport({ count: 0 });
14
+ const busyLog: boolean[] = [];
15
+ const View = () => {
16
+ const { isBusy } = useStatewire({ transport: mock.transport });
17
+ busyLog.push(isBusy);
18
+ return null;
19
+ };
20
+ render(<View />);
21
+ await waitFor(() => expect(mock.attached).toBe(true));
22
+ expect(busyLog.at(-1)).toBe(true);
23
+
24
+ await mock.sendEnvelope({ idle: true });
25
+ await waitFor(() => expect(busyLog.at(-1)).toBe(false));
26
+
27
+ await mock.sendEnvelope({
28
+ ops: [{ op: "replace", path: ["count"], value: 1 }],
29
+ idle: false,
30
+ });
31
+ await waitFor(() => expect(busyLog.at(-1)).toBe(true));
32
+ });
33
+ });