@assistant-ui/react-statewire 0.5.0 → 0.6.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.
@@ -2,7 +2,8 @@ import { StatewireThread } from "./StatewireThread.js";
2
2
  import { ResourceElement } from "@assistant-ui/tap";
3
3
  import { Assistant } from "@assistant-ui/react";
4
4
  import { ClientOutput } from "@assistant-ui/store";
5
- import { AttachmentAdapter, LanguageModelConfig, LanguageModelV1CallSettings, ThreadMessage, ToolExecutionStatus } from "@assistant-ui/core";
5
+ import { AttachmentAdapter, LanguageModelConfig, LanguageModelV1CallSettings, ThreadMessage } from "@assistant-ui/core";
6
+ import { StatewireClient } from "statewire";
6
7
  import { ReadonlyJSONValue } from "assistant-stream/utils";
7
8
  //#region src/AssistantTransportThread.d.ts
8
9
  declare const symbolAssistantTransportExtras: unique symbol;
@@ -141,12 +142,9 @@ declare namespace AssistantTransportThread {
141
142
  */
142
143
  readonly inputRequests?: readonly AssistantTransportThread.InputRequestState[];
143
144
  };
144
- export type ConnectionMetadata = {
145
- pendingCommands: Command[];
146
- isSending: boolean;
147
- toolStatuses: Record<string, ToolExecutionStatus>;
148
- };
149
- export type StateConverter<T> = (state: T, connectionMetadata: ConnectionMetadata) => State;
145
+ export type StateConverter<T> = (state: T) => State;
146
+ /** Folds an unsettled command into a draft of the client state; called once per pending command, in send order, re-run on every state change. A throwing fold logs and drops that command's update. */
147
+ export type Optimistic<T> = (draft: T, command: Command, ctx: StatewireClient.OptimisticContext) => void;
150
148
  export type HeadersValue = Record<string, string> | Headers;
151
149
  export type Protocol = "data-stream" | "assistant-transport";
152
150
  export type SendCommandsRequestBody = {
@@ -163,6 +161,7 @@ declare namespace AssistantTransportThread {
163
161
  export type Options<T> = {
164
162
  initialState: T;
165
163
  converter: StateConverter<T>;
164
+ optimistic?: Optimistic<T> | undefined;
166
165
  api: string;
167
166
  resumeApi?: string | undefined;
168
167
  protocol?: Protocol | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantTransportThread.d.ts","names":[],"sources":["../src/AssistantTransportThread.ts"],"mappings":";;;;;;;cA2Da;KAID;GACT;EACD,cAAc,SAAS,yBAAyB;EAChD;EACA;;EAEA,yBAAyB,yBAAyB;;EAElD,OAAO,gBAAgB;;cAGZ,6BACX,oBACC;cA+UU,2BAA4B,GACvC,SAAS,yBAAyB,QAAQ,OACzC,gBAAgB;kBAKF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C;aACD;aACA;;cAGC;aACD;aACA;aACA;aACA;;cAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;cAIV;aACD;aACA;;cAGC;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;aACA;;cAGC;aACD;aACA,SAAS;aACT;;cAGC;aACD;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;cACC,cAAc;;;cAId,eACR,uBACA,2BACA;cAEQ;aACD,QAAQ;;aAER;aACA,WAAW;;cAGV;aACD;aACA,aAAa;aACb;;cAGC,gBAAgB;cAEhB;aACD;aACA;aACA,UAAU;;;cAIT,oBAAoB;aACrB,UAAU;;cAGT;aACD;aACA;;cAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;cAEQ,UAAU,aAAa;;cAGvB;aACD;aACA,iBAAiB,WAAW;;cAG3B;aACD,mBAAmB;aACnB,QAAQ;aACR;;;;;;;;aAQA,iBAAiB;;aAEjB,sBAAsB;;;;;;aAMtB,yBAAyB,yBAAyB;;cAGjD;IACV,iBAAiB;IACjB;IACA,cAAc,eAAe;;cAGnB,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;cAEO,eAAe,yBAAyB;cAExC;cAEA;IACV,UAAU;IACV;IACA;IACA,OAAO;IACP,cAAc;IACd,QAAQ;IACR;IACA;KACC;;cAGS,QAAQ;IAClB,cAAc;IACd,WAAW,eAAe;IAC1B;IACA;IACA,WAAW;IACX,SAAS,sBAAsB,QAAQ;IACvC,uBAAuB;;IAEvB,+BAEM,MAAM,4BACH,0BAA0B,QAAQ;IAE3C,eAAe,UAAU;IACzB;IACA,YAEM,OAAO,OACP;MACE,UAAU;MACV,cAAc,UAAU,OAAO,MAAM;iBAE7B;;;;;IAMhB,aACM;MACA,UAAU;MACV,cAAc,UAAU,OAAO,MAAM;MACrC,QAAQ;;IAGd;MAEM;;;;;;MAMA;;MAEA;;IAGN;MAEM,cAAc"}
1
+ {"version":3,"file":"AssistantTransportThread.d.ts","names":[],"sources":["../src/AssistantTransportThread.ts"],"mappings":";;;;;;;;cA4Da;KAID;GACT;EACD,cAAc,SAAS,yBAAyB;EAChD;EACA;;EAEA,yBAAyB,yBAAyB;;EAElD,OAAO,gBAAgB;;cAGZ,6BACX,oBACC;cA4XU,2BAA4B,GACvC,SAAS,yBAAyB,QAAQ,OACzC,gBAAgB;kBAKF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C;aACD;aACA;;cAGC;aACD;aACA;aACA;aACA;;cAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;cAIV;aACD;aACA;;cAGC;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;aACA;;cAGC;aACD;aACA,SAAS;aACT;;cAGC;aACD;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;cACC,cAAc;;;cAId,eACR,uBACA,2BACA;cAEQ;aACD,QAAQ;;aAER;aACA,WAAW;;cAGV;aACD;aACA,aAAa;aACb;;cAGC,gBAAgB;cAEhB;aACD;aACA;aACA,UAAU;;;cAIT,oBAAoB;aACrB,UAAU;;cAGT;aACD;aACA;;cAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;cAEQ,UAAU,aAAa;;cAGvB;aACD;aACA,iBAAiB,WAAW;;cAG3B;aACD,mBAAmB;aACnB,QAAQ;aACR;;;;;;;;aAQA,iBAAiB;;aAEjB,sBAAsB;;;;;;aAMtB,yBAAyB,yBAAyB;;cAGjD,eAAe,MAAM,OAAO,MAAM;;cAGlC,WAAW,MACrB,OAAO,GACP,SAAS,SACT,KAAK,gBAAgB;cAGX,eAAe,yBAAyB;cAExC;cAEA;IACV,UAAU;IACV;IACA;IACA,OAAO;IACP,cAAc;IACd,QAAQ;IACR;IACA;KACC;;cAGS,QAAQ;IAClB,cAAc;IACd,WAAW,eAAe;IAC1B,aAAa,WAAW;IACxB;IACA;IACA,WAAW;IACX,SAAS,sBAAsB,QAAQ;IACvC,uBAAuB;;IAEvB,+BAEM,MAAM,4BACH,0BAA0B,QAAQ;IAE3C,eAAe,UAAU;IACzB;IACA,YAEM,OAAO,OACP;MACE,UAAU;MACV,cAAc,UAAU,OAAO,MAAM;iBAE7B;;;;;IAMhB,aACM;MACA,UAAU;MACV,cAAc,UAAU,OAAO,MAAM;MACrC,QAAQ;;IAGd;MAEM;;;;;;MAMA;;MAEA;;IAGN;MAEM,cAAc"}
@@ -7,7 +7,7 @@ import { ExternalThread } from "@assistant-ui/react";
7
7
  import { forwardTransformScopes, useAssistantClientRef } from "@assistant-ui/store";
8
8
  import { createMessageQueue } from "@assistant-ui/core";
9
9
  import { ToolInvocationTracker } from "@assistant-ui/core/internal";
10
- import { useStatewire } from "statewire";
10
+ import { applyOptimistic, useStatewire } from "statewire";
11
11
  //#region src/AssistantTransportThread.ts
12
12
  const EMPTY_TOOL_STATUSES = {};
13
13
  const EMPTY_QUEUE_ITEMS = [];
@@ -17,6 +17,15 @@ const asAssistantTransportExtras = (extras) => {
17
17
  if (typeof extras !== "object" || extras == null || !(symbolAssistantTransportExtras in extras)) throw new Error("This method can only be called when you are using AssistantTransportThread or StatewireThread");
18
18
  return extras;
19
19
  };
20
+ const foldOptimistic = (state, commands, optimistic, ctxOf) => {
21
+ let next = state;
22
+ for (const command of commands) try {
23
+ next = applyOptimistic(next, (draft) => optimistic(draft, command, ctxOf(command)));
24
+ } catch (error) {
25
+ console.error(`statewire: optimistic reducer threw for "${command.type}"; dropping its optimistic update`, error);
26
+ }
27
+ return next;
28
+ };
20
29
  const messagesContainToolCall = (messages, toolCallId) => messages.some((message) => message.content.some((part) => part.type === "tool-call" && (part.toolCallId === toolCallId || part.messages !== void 0 && messagesContainToolCall(part.messages, toolCallId))));
21
30
  const useAssistantTransportThread = (options) => {
22
31
  const clientRef = useAssistantClientRef();
@@ -46,27 +55,38 @@ const useAssistantTransportThread = (options) => {
46
55
  commands.send(command, opts).catch(() => {});
47
56
  }, [commands]);
48
57
  const [toolStatuses, setToolStatuses] = useState(EMPTY_TOOL_STATUSES);
49
- const { converter } = options;
50
- const converted = useMemo(() => converter(agentState, {
51
- pendingCommands: [...queue.inTransit, ...queue.queued],
52
- isSending,
53
- toolStatuses
54
- }), [
58
+ const [ctxOf] = useState(() => {
59
+ const ctxs = /* @__PURE__ */ new WeakMap();
60
+ let seq = 0;
61
+ return (command_0) => {
62
+ let ctx = ctxs.get(command_0);
63
+ if (ctx === void 0) {
64
+ ctx = {
65
+ ts: Date.now(),
66
+ seq: ++seq
67
+ };
68
+ ctxs.set(command_0, ctx);
69
+ }
70
+ return ctx;
71
+ };
72
+ });
73
+ const { converter, optimistic } = options;
74
+ const converted = useMemo(() => converter(optimistic ? foldOptimistic(agentState, [...queue.inTransit, ...queue.queued], optimistic, ctxOf) : agentState), [
55
75
  converter,
76
+ optimistic,
56
77
  agentState,
57
78
  queue,
58
- isSending,
59
- toolStatuses
79
+ ctxOf
60
80
  ]);
61
81
  const convertedRef = useRef(converted);
62
82
  convertedRef.current = converted;
63
83
  const [toolInvocations] = useState(() => new ToolInvocationTracker(() => {
64
84
  return (clientRef.current ?? clientRef.parent).modelContext().getModelContext().tools;
65
85
  }, {
66
- onResult: (command_0) => {
86
+ onResult: (command_1) => {
67
87
  const messages = convertedRef.current.messages;
68
- if (!messagesContainToolCall(messages, command_0.toolCallId)) return;
69
- dispatch(resolveToolResultInput(convertedRef.current.inputRequests ?? [], command_0));
88
+ if (!messagesContainToolCall(messages, command_1.toolCallId)) return;
89
+ dispatch(resolveToolResultInput(convertedRef.current.inputRequests ?? [], command_1));
70
90
  },
71
91
  onStatusesChange: (statuses) => {
72
92
  setToolStatuses(statuses.size === 0 ? EMPTY_TOOL_STATUSES : Object.fromEntries(statuses));
@@ -98,19 +118,19 @@ const useAssistantTransportThread = (options) => {
98
118
  inputRequests
99
119
  ]);
100
120
  const handleEdit = (message) => {
101
- const command_1 = resolveEditCommand(message);
102
- toolInvocations.abort().then(() => dispatch(command_1));
121
+ const command_2 = resolveEditCommand(message);
122
+ toolInvocations.abort().then(() => dispatch(command_2));
103
123
  };
104
124
  const handleAppend = (message_0) => {
105
125
  if (message_0.sourceId != null) return handleEdit(message_0);
106
126
  const startRun = message_0.startRun ?? message_0.role === "user";
107
- const command_2 = {
127
+ const command_3 = {
108
128
  type: "run/steer",
109
129
  message: toWireMessage(message_0, crypto.randomUUID()),
110
130
  anchorMessageId: viewedLeafId(convertedRef.current.messages)
111
131
  };
112
132
  commands.setParentId(message_0.parentId).catch(() => {});
113
- const send = () => dispatch(command_2, { schedule: startRun });
133
+ const send = () => dispatch(command_3, { schedule: startRun });
114
134
  if (startRun) toolInvocations.abort().then(send);
115
135
  else send();
116
136
  };
@@ -174,8 +194,8 @@ const useAssistantTransportThread = (options) => {
174
194
  } },
175
195
  ...options.capabilities?.edit && { onEdit: handleEdit },
176
196
  onReload: (parentId) => {
177
- const command_3 = resolveReloadCommand(convertedRef.current.messages, parentId);
178
- toolInvocations.abort().then(() => dispatch(command_3));
197
+ const command_4 = resolveReloadCommand(convertedRef.current.messages, parentId);
198
+ toolInvocations.abort().then(() => dispatch(command_4));
179
199
  },
180
200
  onCancel: () => {
181
201
  messageQueue?.clear();
@@ -198,11 +218,7 @@ const useAssistantTransportThread = (options) => {
198
218
  },
199
219
  onLoadExternalState: (imported) => {
200
220
  commands.importState(imported).catch(() => {});
201
- convertedRef.current = options.converter(imported, {
202
- pendingCommands: [...queue.inTransit, ...queue.queued],
203
- isSending,
204
- toolStatuses: EMPTY_TOOL_STATUSES
205
- });
221
+ convertedRef.current = converter(optimistic ? foldOptimistic(imported, [...queue.inTransit, ...queue.queued], optimistic, ctxOf) : imported);
206
222
  toolInvocations.reset();
207
223
  setToolStatuses(EMPTY_TOOL_STATUSES);
208
224
  }
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantTransportThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","resource","useResource","ResourceElement","ExternalThread","Assistant","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","createMessageQueue","AddToolResultOptions","AppendMessage","AttachmentAdapter","LanguageModelConfig","LanguageModelV1CallSettings","MessageQueueController","MessageQueueDriver","RespondToToolApprovalOptions","ResumeToolCallOptions","ThreadMessage","ToolExecutionStatus","ReadonlyJSONValue","ToolInvocationTracker","useStatewire","StatewireThread","AssistantTransportHost","AssistantTransportHostCommands","AssistantTransportHostState","HostQueueCell","HostRunContext","SendOptions","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","EMPTY_TOOL_STATUSES","Record","EMPTY_QUEUE_ITEMS","subscribeNoop","symbolAssistantTransportExtras","Symbol","AssistantTransportExtras","sendCommand","command","AssistantTransportThread","Command","reconnect","state","inputRequests","InputRequestState","runs","Runs","asAssistantTransportExtras","extras","Error","messagesContainToolCall","messages","toolCallId","some","message","content","part","type","undefined","useAssistantTransportThread","options","Options","clientRef","getRunContext","aui","current","parent","threadId","threadListItem","getState","remoteId","modelContext","getModelContext","queueCell","queued","inTransit","commands","connection","transport","agent","agentState","isSending","isReplaying","queue","dispatch","opts","send","catch","toolStatuses","setToolStatuses","converter","converted","pendingCommands","convertedRef","toolInvocations","tools","onResult","onStatusesChange","statuses","size","Object","fromEntries","setState","isRunning","isLoading","reset","inputSeam","present","handleEdit","abort","then","handleAppend","sourceId","startRun","role","crypto","randomUUID","anchorMessageId","setParentId","parentId","schedule","handleCancel","cancel","driverRef","run","at","id","queueProjection","steerProjection","steerQueue","capabilities","queueSeam","serverQueue","enableQueue","queueRef","clear","messageQueue","queueItems","subscribe","adapter","items","steerQueueItems","steerItems","busy","keys","length","wasBusyRef","notifyBusy","notifyIdle","attachmentAdapter","adapters","attachments","onNew","edit","onEdit","onReload","onCancel","onResume","continue","resumeApi","resume","onAddToolResult","toolOptions","onRespondToToolApproval","onResumeToolCall","payload","onLoadExternalState","imported","importState","T","UserCommands","Commands","TextPart","text","FilePart","mediaType","url","filename","RunUserMessage","parts","metadata","RunPlacement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","ToolApprovalInputRequest","CustomInputRequest","key","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","RunReloadCommand","RunCommand","RunQueueItem","State","ConnectionMetadata","StateConverter","connectionMetadata","HeadersValue","Headers","Protocol","SendCommandsRequestBody","system","callSettings","config","initialState","api","protocol","headers","Promise","body","prepareSendCommandsRequest","onResponse","Response","onFinish","onError","error","params","updateState","updater","hook"],"sources":["../src/AssistantTransportThread.ts"],"sourcesContent":["import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { Assistant, ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport { createMessageQueue } from \"@assistant-ui/core\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n LanguageModelConfig,\n LanguageModelV1CallSettings,\n MessageQueueController,\n MessageQueueDriver,\n RespondToToolApprovalOptions,\n ResumeToolCallOptions,\n ThreadMessage,\n ToolExecutionStatus,\n} from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { ToolInvocationTracker } from \"@assistant-ui/core/internal\";\nimport { useStatewire } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\nimport { AssistantTransportHost } from \"./host\";\nimport type {\n AssistantTransportHostCommands,\n AssistantTransportHostState,\n HostQueueCell,\n HostRunContext,\n SendOptions,\n} from \"./host\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\n\nconst EMPTY_TOOL_STATUSES: Record<string, ToolExecutionStatus> = {};\nconst EMPTY_QUEUE_ITEMS: MessageQueueController[\"adapter\"][\"items\"] = [];\nconst subscribeNoop = () => () => {};\n\nexport const symbolAssistantTransportExtras = Symbol(\n \"assistant-transport-extras\",\n);\n\nexport type AssistantTransportExtras = {\n [symbolAssistantTransportExtras]: true;\n sendCommand: (command: AssistantTransportThread.Command) => void;\n reconnect: () => void;\n state: unknown;\n /** The host's parked input requests; absent when the converter does not project them. */\n inputRequests?: readonly AssistantTransportThread.InputRequestState[];\n /** The typed runs read; present iff StatewireThread runs with the `runs` option. */\n runs?: StatewireThread.Runs;\n};\n\nexport const asAssistantTransportExtras = (\n extras: unknown,\n): AssistantTransportExtras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolAssistantTransportExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using AssistantTransportThread or StatewireThread\",\n );\n\n return extras as AssistantTransportExtras;\n};\n\nconst messagesContainToolCall = (\n messages: readonly ThreadMessage[],\n toolCallId: string,\n): boolean =>\n messages.some((message) =>\n message.content.some(\n (part) =>\n part.type === \"tool-call\" &&\n (part.toolCallId === toolCallId ||\n (part.messages !== undefined &&\n messagesContainToolCall(part.messages, toolCallId))),\n ),\n );\n\nconst useAssistantTransportThread = (\n options: AssistantTransportThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const clientRef = useAssistantClientRef();\n const [getRunContext] = useState(() => (): HostRunContext => {\n const aui = clientRef.current ?? clientRef.parent;\n // legacy parity: a threadListItem throw must not kill the run\n let threadId: string | null = null;\n try {\n threadId = aui.threadListItem().getState().remoteId ?? null;\n } catch {}\n return {\n modelContext: aui.modelContext().getModelContext(),\n threadId,\n };\n });\n\n const [queueCell] = useState(\n (): HostQueueCell => ({ current: { queued: [], inTransit: [] } }),\n );\n const { state, commands, connection } = useStatewire<\n AssistantTransportHostState,\n AssistantTransportHostCommands\n >({\n transport: AssistantTransportHost({ ...options, getRunContext, queueCell }),\n });\n const { agent: agentState, isSending, isReplaying } = state;\n const queue = queueCell.current;\n\n const dispatch = useCallback(\n (command: AssistantTransportThread.Command, opts?: SendOptions) => {\n void commands.send(command, opts).catch(() => {});\n },\n [commands],\n );\n\n const [toolStatuses, setToolStatuses] =\n useState<Record<string, ToolExecutionStatus>>(EMPTY_TOOL_STATUSES);\n\n const { converter } = options;\n const converted = useMemo(\n () =>\n converter(agentState, {\n pendingCommands: [...queue.inTransit, ...queue.queued],\n isSending,\n toolStatuses,\n }),\n [converter, agentState, queue, isSending, toolStatuses],\n );\n const convertedRef = useRef(converted);\n convertedRef.current = converted;\n\n const [toolInvocations] = useState(\n () =>\n new ToolInvocationTracker(\n () => {\n const aui = clientRef.current ?? clientRef.parent;\n return aui.modelContext().getModelContext().tools;\n },\n {\n onResult: (command) => {\n const messages = convertedRef.current\n .messages as readonly ThreadMessage[];\n if (!messagesContainToolCall(messages, command.toolCallId)) return;\n dispatch(\n resolveToolResultInput(\n convertedRef.current.inputRequests ?? [],\n command,\n ),\n );\n },\n onStatusesChange: (statuses) => {\n setToolStatuses(\n statuses.size === 0\n ? EMPTY_TOOL_STATUSES\n : Object.fromEntries(statuses),\n );\n },\n },\n ),\n );\n // dep-less by design: setState dedups identical snapshots internally\n useEffect(() => {\n toolInvocations.setState({\n messages: converted.messages as readonly ThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n });\n });\n useEffect(\n () => () => {\n toolInvocations.reset();\n },\n [toolInvocations],\n );\n\n const inputRequests = converted.inputRequests;\n const [inputSeam] = useState(() => ({\n present: inputRequests !== undefined,\n }));\n if (inputSeam.present !== (inputRequests !== undefined))\n throw new Error(\n \"statewire: the converter's inputRequests projection must be stable — it was \" +\n (inputSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state: agentState,\n ...(inputRequests !== undefined && { inputRequests }),\n }),\n [dispatch, connection.reconnect, agentState, inputRequests],\n );\n\n const handleEdit = (message: AppendMessage) => {\n const command = resolveEditCommand(message);\n void toolInvocations.abort().then(() => dispatch(command));\n };\n\n const handleAppend = (message: AppendMessage) => {\n if (message.sourceId != null) return handleEdit(message);\n const startRun = message.startRun ?? message.role === \"user\";\n const command: AssistantTransportThread.Command = {\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(convertedRef.current.messages),\n };\n void commands.setParentId(message.parentId).catch(() => {});\n\n const send = () => dispatch(command, { schedule: startRun });\n if (startRun) {\n // abort in-flight tool executions so their late results cannot race the new turn\n void toolInvocations.abort().then(send);\n } else {\n send();\n }\n };\n\n const handleCancel = () => {\n void toolInvocations.abort();\n void commands.cancel().catch(() => {});\n };\n\n const driverRef = useRef<{\n run: MessageQueueDriver[\"run\"];\n cancel: () => void;\n }>(undefined as never);\n driverRef.current = {\n // the queued message was stamped with the head at enqueue time; restamp so\n // it appends to the thread the finished run left behind\n run: (message) =>\n handleAppend({\n ...message,\n parentId: convertedRef.current.messages.at(-1)?.id ?? null,\n }),\n cancel: handleCancel,\n };\n\n const queueProjection = converted.queue;\n const steerProjection = converted.steerQueue;\n if (steerProjection !== undefined && queueProjection === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n if (queueProjection !== undefined && options.capabilities?.queue)\n throw new Error(\n \"statewire: the converter's queue projection excludes capabilities.queue\",\n );\n const [queueSeam] = useState(() => ({\n present: queueProjection !== undefined,\n }));\n if (queueSeam.present !== (queueProjection !== undefined))\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n const serverQueue = useMemo(\n () =>\n queueProjection\n ? createRunQueueAdapter(\n converted.messages,\n queueProjection,\n steerProjection,\n dispatch,\n )\n : undefined,\n [converted.messages, queueProjection, steerProjection, dispatch],\n );\n\n const enableQueue = options.capabilities?.queue === true;\n const queueRef = useRef<MessageQueueController | null>(null);\n if (enableQueue && !queueRef.current) {\n queueRef.current = createMessageQueue({\n run: (message, opts) => driverRef.current.run(message, opts),\n cancel: () => driverRef.current.cancel(),\n });\n } else if (!enableQueue && queueRef.current) {\n queueRef.current.clear();\n queueRef.current = null;\n }\n const messageQueue = queueRef.current;\n\n // fresh view per snapshot: the controller mutates adapter.items in place,\n // which a stable prop identity would hide from the thread resource\n const queueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.items ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n const steerQueueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n\n // settled edge: the queue only advances once the host run loop has fully\n // released (isSending), the converted state agrees, and no client tool from\n // the finished run is still executing\n const busy =\n isSending || converted.isRunning || Object.keys(toolStatuses).length > 0;\n const wasBusyRef = useRef(false);\n useEffect(() => {\n if (wasBusyRef.current === busy) return;\n wasBusyRef.current = busy;\n if (busy) messageQueue?.notifyBusy();\n else messageQueue?.notifyIdle();\n });\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(serverQueue\n ? { queue: serverQueue }\n : messageQueue && {\n queue: {\n ...messageQueue.adapter,\n items: queueItems,\n steerItems: steerQueueItems,\n },\n }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n onReload: (parentId: string | null) => {\n const command = resolveReloadCommand(\n convertedRef.current.messages,\n parentId,\n );\n void toolInvocations.abort().then(() => dispatch(command));\n },\n onCancel: () => {\n // user cancel drops pending lanes; a steer interrupt (driver.cancel) keeps them\n messageQueue?.clear();\n handleCancel();\n },\n onResume: () => {\n if (options.capabilities?.continue) {\n dispatch({ type: \"run/continue\" });\n return;\n }\n if (!options.resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n void commands.resume().catch(() => {});\n },\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(\n resolveToolResultInput(\n convertedRef.current.inputRequests!,\n toolOptions,\n ),\n ),\n onRespondToToolApproval: (options: RespondToToolApprovalOptions) =>\n dispatch(\n resolveToolApprovalInput(\n convertedRef.current.inputRequests!,\n options,\n ),\n ),\n }),\n onResumeToolCall: ({ toolCallId, payload }: ResumeToolCallOptions) => {\n if (!toolInvocations.resume(toolCallId, payload))\n throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);\n },\n onLoadExternalState: (imported: unknown) => {\n void commands.importState(imported).catch(() => {});\n // reset() aborts tools before React re-renders — gate their late results against the imported state\n convertedRef.current = options.converter(imported, {\n pendingCommands: [...queue.inTransit, ...queue.queued],\n isSending,\n toolStatuses: EMPTY_TOOL_STATUSES,\n });\n toolInvocations.reset();\n setToolStatuses(EMPTY_TOOL_STATUSES);\n },\n }),\n );\n};\n\nexport const AssistantTransportThread = <T>(\n options: AssistantTransportThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useAssistantTransportThread)(\n options as AssistantTransportThread.Options<any>,\n );\n\nexport namespace AssistantTransportThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\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 RunUserMessage = {\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 RunPlacement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\n } & (\n | {\n readonly message: RunUserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n RunPlacement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: RunUserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n RunPlacement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n readonly message: RunUserMessage;\n readonly sourceId: string;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\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 ToolCallInputResponse = {\n readonly output: ReadonlyJSONValue;\n /** Default false; when true, `output` carries the error payload. */\n readonly isError?: boolean;\n readonly artifact?: ReadonlyJSONValue;\n };\n\n export type ToolApprovalInputResponse = {\n readonly decision: \"approve\" | \"reject\" | \"edit\" | \"respond\";\n readonly editedArgs?: ReadonlyJSONValue;\n readonly message?: string;\n };\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state with its response echo. */\n export type InputRequestState = InputRequest & {\n readonly response: InputResponse | null;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n readonly sourceId: string;\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 export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the server-side queue: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions and excludes the\n * client-local `capabilities.queue` buffer.\n */\n readonly queue?: readonly RunQueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly RunQueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning it\n * (even empty) routes tool results and approvals with a matching pending\n * request through `run/input`. Presence must be stable across conversions.\n */\n readonly inputRequests?: readonly AssistantTransportThread.InputRequestState[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n toolStatuses: Record<string, ToolExecutionStatus>;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n export type HeadersValue = Record<string, string> | Headers;\n\n export type Protocol = \"data-stream\" | \"assistant-transport\";\n\n export type SendCommandsRequestBody = {\n commands: Command[];\n state: unknown;\n system: string | undefined;\n tools: Record<string, unknown> | undefined;\n callSettings: LanguageModelV1CallSettings | undefined;\n config: LanguageModelConfig | undefined;\n threadId: string | null;\n parentId?: string | null;\n [key: string]: unknown;\n };\n\n export type Options<T> = {\n initialState: T;\n converter: StateConverter<T>;\n api: string;\n resumeApi?: string | undefined;\n protocol?: Protocol | undefined;\n headers: HeadersValue | (() => Promise<HeadersValue>);\n body?: object | (() => Promise<object | undefined>) | undefined;\n /** Transform the fully assembled request body before it is sent. */\n prepareSendCommandsRequest?:\n | ((\n body: SendCommandsRequestBody,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>)\n | undefined;\n onResponse?: ((response: Response) => void) | undefined;\n onFinish?: (() => void) | undefined;\n onError?:\n | ((\n error: Error,\n params: {\n commands: Command[];\n updateState: (updater: (state: T) => T) => void;\n },\n ) => void | Promise<void>)\n | undefined;\n /**\n * Called when commands are cancelled. After an error, queued commands are\n * cancelled once `onError` settles; `error` then carries the cause.\n */\n onCancel?:\n | ((params: {\n commands: Command[];\n updateState: (updater: (state: T) => T) => void;\n error?: Error;\n }) => void)\n | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /**\n * Buffer messages sent during a run in an in-memory queue and dispatch\n * them once the run settles. Steering interrupts the active run.\n * Mutually exclusive with the converter's `queue` projection.\n */\n queue?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\n };\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useAssistantTransportThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;;AAuDA,MAAM4C,sBAA2D,CAAC;AAClE,MAAME,oBAAgE,CAAA;AACtE,MAAMC,4BAA4B,CAAC;AAEnC,MAAaC,iCAAiCC,OAC5C,4BACF;AAaA,MAAaY,8BACXC,WAC6B;CAC7B,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEd,kCAAkCc,SAEpC,MAAM,IAAIC,MACR,+FACF;CAEF,OAAOD;AACT;AAEA,MAAME,2BACJC,UACAC,eAEAD,SAASE,MAAMC,YACbA,QAAQC,QAAQF,MACbG,SACCA,KAAKC,SAAS,gBACbD,KAAKJ,eAAeA,cAClBI,KAAKL,aAAaO,KAAAA,KACjBR,wBAAwBM,KAAKL,UAAUC,UAAU,EACzD,CACF;AAEF,MAAMO,+BACJC,YAC2B;CAC3B,MAAME,YAAY/D,sBAAsB;CACxC,MAAM,CAACgE,iBAAiBzE,qBAAqC;EAC3D,MAAM0E,MAAMF,UAAUG,WAAWH,UAAUI;EAE3C,IAAIC,WAA0B;EAC9B,IAAI;GACFA,WAAWH,IAAII,eAAe,CAAC,CAACC,SAAS,CAAC,CAACC,YAAY;EACzD,QAAQ,CAAC;EACT,OAAO;GACLC,cAAcP,IAAIO,aAAa,CAAC,CAACC,gBAAgB;GACjDL;EACF;CACF,CAAC;CAED,MAAM,CAACM,aAAanF,gBACI,EAAE2E,SAAS;EAAES,QAAQ,CAAA;EAAIC,WAAW,CAAA;CAAG,EAAE,EACjE;CACA,MAAM,EAAEjC,OAAOkC,UAAUC,eAAe9D,aAGtC,EACA+D,WAAW7D,uBAAuB;EAAE,GAAG2C;EAASG;EAAeU;CAAU,CAAC,EAC5E,CAAC;CACD,MAAM,EAAEM,OAAOC,YAAYC,WAAWC,gBAAgBxC;CACtD,MAAM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EiE,aAAa5B,QAAQtB,eACrBiB,SACF,CACF;EACJ;EACAwG,mBAAmB,EAAEhH,YAAYiH,cAAqC;GACpE,IAAI,CAACvE,gBAAgBkE,OAAO5G,YAAYiH,OAAO,GAC7C,MAAM,IAAIpH,MAAM,aAAaG,WAAU,4BAA6B;EACxE;EACAkH,sBAAsBC,aAAsB;GAC1C,SAAcC,YAAYD,QAAQ,CAAC,CAAChF,YAAY,CAAC,CAAC;GAElDM,aAAa5B,UAAUL,QAAQ8B,UAAU6E,UAAU;IACjD3E,iBAAiB,CAAC,GAAGT,MAAMR,WAAW,GAAGQ,MAAMT,MAAM;IACrDO;IACAO,cAAc1D;GAChB,CAAC;GACDgE,gBAAgBW,MAAM;GACtBhB,gBAAgB3D,mBAAmB;EACrC;CACF,CAAC,CACH;AACF;AAEA,MAAaS,4BACXqB,YAEApE,SAASmE,2BAA2B,CAAC,CACnCC,OACF;AAwPF9D,uBACE6D,6BACAhE,eAAe+D,KAAAA,CAAkB,CAAC,CAACiL,IACrC"}
1
+ {"version":3,"file":"AssistantTransportThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","resource","useResource","ResourceElement","ExternalThread","Assistant","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","createMessageQueue","AddToolResultOptions","AppendMessage","AttachmentAdapter","LanguageModelConfig","LanguageModelV1CallSettings","MessageQueueController","MessageQueueDriver","RespondToToolApprovalOptions","ResumeToolCallOptions","ThreadMessage","ToolExecutionStatus","ReadonlyJSONValue","ToolInvocationTracker","applyOptimistic","useStatewire","StatewireClient","StatewireThread","AssistantTransportHost","AssistantTransportHostCommands","AssistantTransportHostState","HostQueueCell","HostRunContext","SendOptions","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","EMPTY_TOOL_STATUSES","Record","EMPTY_QUEUE_ITEMS","subscribeNoop","symbolAssistantTransportExtras","Symbol","AssistantTransportExtras","sendCommand","command","AssistantTransportThread","Command","reconnect","state","inputRequests","InputRequestState","runs","Runs","asAssistantTransportExtras","extras","Error","foldOptimistic","commands","optimistic","Optimistic","ctxOf","OptimisticContext","next","draft","error","console","type","messagesContainToolCall","messages","toolCallId","some","message","content","part","undefined","useAssistantTransportThread","options","Options","clientRef","getRunContext","aui","current","parent","threadId","threadListItem","getState","remoteId","modelContext","getModelContext","queueCell","queued","inTransit","connection","transport","agent","agentState","isSending","isReplaying","queue","dispatch","opts","send","catch","toolStatuses","setToolStatuses","ctxs","WeakMap","seq","ctx","get","ts","Date","now","set","converter","converted","convertedRef","toolInvocations","tools","onResult","onStatusesChange","statuses","size","Object","fromEntries","setState","isRunning","isLoading","reset","inputSeam","present","handleEdit","abort","then","handleAppend","sourceId","startRun","role","crypto","randomUUID","anchorMessageId","setParentId","parentId","schedule","handleCancel","cancel","driverRef","run","at","id","queueProjection","steerProjection","steerQueue","capabilities","queueSeam","serverQueue","enableQueue","queueRef","clear","messageQueue","queueItems","subscribe","adapter","items","steerQueueItems","steerItems","busy","keys","length","wasBusyRef","notifyBusy","notifyIdle","attachmentAdapter","adapters","attachments","onNew","edit","onEdit","onReload","onCancel","onResume","continue","resumeApi","resume","onAddToolResult","toolOptions","onRespondToToolApproval","onResumeToolCall","payload","onLoadExternalState","imported","importState","T","UserCommands","Commands","TextPart","text","FilePart","mediaType","url","filename","RunUserMessage","parts","metadata","RunPlacement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","ToolApprovalInputRequest","CustomInputRequest","key","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","RunReloadCommand","RunCommand","RunQueueItem","State","StateConverter","HeadersValue","Headers","Protocol","SendCommandsRequestBody","system","callSettings","config","initialState","api","protocol","headers","Promise","body","prepareSendCommandsRequest","onResponse","Response","onFinish","onError","params","updateState","updater","hook"],"sources":["../src/AssistantTransportThread.ts"],"sourcesContent":["import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { Assistant, ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport { createMessageQueue } from \"@assistant-ui/core\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n LanguageModelConfig,\n LanguageModelV1CallSettings,\n MessageQueueController,\n MessageQueueDriver,\n RespondToToolApprovalOptions,\n ResumeToolCallOptions,\n ThreadMessage,\n ToolExecutionStatus,\n} from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { ToolInvocationTracker } from \"@assistant-ui/core/internal\";\nimport { applyOptimistic, useStatewire } from \"statewire\";\nimport type { StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\nimport { AssistantTransportHost } from \"./host\";\nimport type {\n AssistantTransportHostCommands,\n AssistantTransportHostState,\n HostQueueCell,\n HostRunContext,\n SendOptions,\n} from \"./host\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\n\nconst EMPTY_TOOL_STATUSES: Record<string, ToolExecutionStatus> = {};\nconst EMPTY_QUEUE_ITEMS: MessageQueueController[\"adapter\"][\"items\"] = [];\nconst subscribeNoop = () => () => {};\n\nexport const symbolAssistantTransportExtras = Symbol(\n \"assistant-transport-extras\",\n);\n\nexport type AssistantTransportExtras = {\n [symbolAssistantTransportExtras]: true;\n sendCommand: (command: AssistantTransportThread.Command) => void;\n reconnect: () => void;\n state: unknown;\n /** The host's parked input requests; absent when the converter does not project them. */\n inputRequests?: readonly AssistantTransportThread.InputRequestState[];\n /** The typed runs read; present iff StatewireThread runs with the `runs` option. */\n runs?: StatewireThread.Runs;\n};\n\nexport const asAssistantTransportExtras = (\n extras: unknown,\n): AssistantTransportExtras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolAssistantTransportExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using AssistantTransportThread or StatewireThread\",\n );\n\n return extras as AssistantTransportExtras;\n};\n\nconst foldOptimistic = (\n state: unknown,\n commands: readonly AssistantTransportThread.Command[],\n optimistic: AssistantTransportThread.Optimistic<unknown>,\n ctxOf: (command: object) => StatewireClient.OptimisticContext,\n): unknown => {\n let next = state;\n for (const command of commands) {\n try {\n next = applyOptimistic(next, (draft) =>\n optimistic(draft, command, ctxOf(command)),\n );\n } catch (error) {\n console.error(\n `statewire: optimistic reducer threw for \"${command.type}\"; dropping its optimistic update`,\n error,\n );\n }\n }\n return next;\n};\n\nconst messagesContainToolCall = (\n messages: readonly ThreadMessage[],\n toolCallId: string,\n): boolean =>\n messages.some((message) =>\n message.content.some(\n (part) =>\n part.type === \"tool-call\" &&\n (part.toolCallId === toolCallId ||\n (part.messages !== undefined &&\n messagesContainToolCall(part.messages, toolCallId))),\n ),\n );\n\nconst useAssistantTransportThread = (\n options: AssistantTransportThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const clientRef = useAssistantClientRef();\n const [getRunContext] = useState(() => (): HostRunContext => {\n const aui = clientRef.current ?? clientRef.parent;\n // legacy parity: a threadListItem throw must not kill the run\n let threadId: string | null = null;\n try {\n threadId = aui.threadListItem().getState().remoteId ?? null;\n } catch {}\n return {\n modelContext: aui.modelContext().getModelContext(),\n threadId,\n };\n });\n\n const [queueCell] = useState(\n (): HostQueueCell => ({ current: { queued: [], inTransit: [] } }),\n );\n const { state, commands, connection } = useStatewire<\n AssistantTransportHostState,\n AssistantTransportHostCommands\n >({\n transport: AssistantTransportHost({ ...options, getRunContext, queueCell }),\n });\n const { agent: agentState, isSending, isReplaying } = state;\n const queue = queueCell.current;\n\n const dispatch = useCallback(\n (command: AssistantTransportThread.Command, opts?: SendOptions) => {\n void commands.send(command, opts).catch(() => {});\n },\n [commands],\n );\n\n const [toolStatuses, setToolStatuses] =\n useState<Record<string, ToolExecutionStatus>>(EMPTY_TOOL_STATUSES);\n\n const [ctxOf] = useState(() => {\n const ctxs = new WeakMap<object, StatewireClient.OptimisticContext>();\n let seq = 0;\n return (command: object): StatewireClient.OptimisticContext => {\n let ctx = ctxs.get(command);\n if (ctx === undefined) {\n ctx = { ts: Date.now(), seq: ++seq };\n ctxs.set(command, ctx);\n }\n return ctx;\n };\n });\n\n const { converter, optimistic } = options;\n const converted = useMemo(\n () =>\n converter(\n optimistic\n ? foldOptimistic(\n agentState,\n [...queue.inTransit, ...queue.queued],\n optimistic,\n ctxOf,\n )\n : agentState,\n ),\n [converter, optimistic, agentState, queue, ctxOf],\n );\n const convertedRef = useRef(converted);\n convertedRef.current = converted;\n\n const [toolInvocations] = useState(\n () =>\n new ToolInvocationTracker(\n () => {\n const aui = clientRef.current ?? clientRef.parent;\n return aui.modelContext().getModelContext().tools;\n },\n {\n onResult: (command) => {\n const messages = convertedRef.current\n .messages as readonly ThreadMessage[];\n if (!messagesContainToolCall(messages, command.toolCallId)) return;\n dispatch(\n resolveToolResultInput(\n convertedRef.current.inputRequests ?? [],\n command,\n ),\n );\n },\n onStatusesChange: (statuses) => {\n setToolStatuses(\n statuses.size === 0\n ? EMPTY_TOOL_STATUSES\n : Object.fromEntries(statuses),\n );\n },\n },\n ),\n );\n // dep-less by design: setState dedups identical snapshots internally\n useEffect(() => {\n toolInvocations.setState({\n messages: converted.messages as readonly ThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n });\n });\n useEffect(\n () => () => {\n toolInvocations.reset();\n },\n [toolInvocations],\n );\n\n const inputRequests = converted.inputRequests;\n const [inputSeam] = useState(() => ({\n present: inputRequests !== undefined,\n }));\n if (inputSeam.present !== (inputRequests !== undefined))\n throw new Error(\n \"statewire: the converter's inputRequests projection must be stable — it was \" +\n (inputSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state: agentState,\n ...(inputRequests !== undefined && { inputRequests }),\n }),\n [dispatch, connection.reconnect, agentState, inputRequests],\n );\n\n const handleEdit = (message: AppendMessage) => {\n const command = resolveEditCommand(message);\n void toolInvocations.abort().then(() => dispatch(command));\n };\n\n const handleAppend = (message: AppendMessage) => {\n if (message.sourceId != null) return handleEdit(message);\n const startRun = message.startRun ?? message.role === \"user\";\n const command: AssistantTransportThread.Command = {\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(convertedRef.current.messages),\n };\n void commands.setParentId(message.parentId).catch(() => {});\n\n const send = () => dispatch(command, { schedule: startRun });\n if (startRun) {\n // abort in-flight tool executions so their late results cannot race the new turn\n void toolInvocations.abort().then(send);\n } else {\n send();\n }\n };\n\n const handleCancel = () => {\n void toolInvocations.abort();\n void commands.cancel().catch(() => {});\n };\n\n const driverRef = useRef<{\n run: MessageQueueDriver[\"run\"];\n cancel: () => void;\n }>(undefined as never);\n driverRef.current = {\n // the queued message was stamped with the head at enqueue time; restamp so\n // it appends to the thread the finished run left behind\n run: (message) =>\n handleAppend({\n ...message,\n parentId: convertedRef.current.messages.at(-1)?.id ?? null,\n }),\n cancel: handleCancel,\n };\n\n const queueProjection = converted.queue;\n const steerProjection = converted.steerQueue;\n if (steerProjection !== undefined && queueProjection === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n if (queueProjection !== undefined && options.capabilities?.queue)\n throw new Error(\n \"statewire: the converter's queue projection excludes capabilities.queue\",\n );\n const [queueSeam] = useState(() => ({\n present: queueProjection !== undefined,\n }));\n if (queueSeam.present !== (queueProjection !== undefined))\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n const serverQueue = useMemo(\n () =>\n queueProjection\n ? createRunQueueAdapter(\n converted.messages,\n queueProjection,\n steerProjection,\n dispatch,\n )\n : undefined,\n [converted.messages, queueProjection, steerProjection, dispatch],\n );\n\n const enableQueue = options.capabilities?.queue === true;\n const queueRef = useRef<MessageQueueController | null>(null);\n if (enableQueue && !queueRef.current) {\n queueRef.current = createMessageQueue({\n run: (message, opts) => driverRef.current.run(message, opts),\n cancel: () => driverRef.current.cancel(),\n });\n } else if (!enableQueue && queueRef.current) {\n queueRef.current.clear();\n queueRef.current = null;\n }\n const messageQueue = queueRef.current;\n\n // fresh view per snapshot: the controller mutates adapter.items in place,\n // which a stable prop identity would hide from the thread resource\n const queueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.items ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n const steerQueueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n\n // settled edge: the queue only advances once the host run loop has fully\n // released (isSending), the converted state agrees, and no client tool from\n // the finished run is still executing\n const busy =\n isSending || converted.isRunning || Object.keys(toolStatuses).length > 0;\n const wasBusyRef = useRef(false);\n useEffect(() => {\n if (wasBusyRef.current === busy) return;\n wasBusyRef.current = busy;\n if (busy) messageQueue?.notifyBusy();\n else messageQueue?.notifyIdle();\n });\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(serverQueue\n ? { queue: serverQueue }\n : messageQueue && {\n queue: {\n ...messageQueue.adapter,\n items: queueItems,\n steerItems: steerQueueItems,\n },\n }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n onReload: (parentId: string | null) => {\n const command = resolveReloadCommand(\n convertedRef.current.messages,\n parentId,\n );\n void toolInvocations.abort().then(() => dispatch(command));\n },\n onCancel: () => {\n // user cancel drops pending lanes; a steer interrupt (driver.cancel) keeps them\n messageQueue?.clear();\n handleCancel();\n },\n onResume: () => {\n if (options.capabilities?.continue) {\n dispatch({ type: \"run/continue\" });\n return;\n }\n if (!options.resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n void commands.resume().catch(() => {});\n },\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(\n resolveToolResultInput(\n convertedRef.current.inputRequests!,\n toolOptions,\n ),\n ),\n onRespondToToolApproval: (options: RespondToToolApprovalOptions) =>\n dispatch(\n resolveToolApprovalInput(\n convertedRef.current.inputRequests!,\n options,\n ),\n ),\n }),\n onResumeToolCall: ({ toolCallId, payload }: ResumeToolCallOptions) => {\n if (!toolInvocations.resume(toolCallId, payload))\n throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);\n },\n onLoadExternalState: (imported: unknown) => {\n void commands.importState(imported).catch(() => {});\n // reset() aborts tools before React re-renders — gate their late results against the imported state\n convertedRef.current = converter(\n optimistic\n ? foldOptimistic(\n imported,\n [...queue.inTransit, ...queue.queued],\n optimistic,\n ctxOf,\n )\n : imported,\n );\n toolInvocations.reset();\n setToolStatuses(EMPTY_TOOL_STATUSES);\n },\n }),\n );\n};\n\nexport const AssistantTransportThread = <T>(\n options: AssistantTransportThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useAssistantTransportThread)(\n options as AssistantTransportThread.Options<any>,\n );\n\nexport namespace AssistantTransportThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\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 RunUserMessage = {\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 RunPlacement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\n } & (\n | {\n readonly message: RunUserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n RunPlacement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: RunUserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n RunPlacement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n readonly message: RunUserMessage;\n readonly sourceId: string;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\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 ToolCallInputResponse = {\n readonly output: ReadonlyJSONValue;\n /** Default false; when true, `output` carries the error payload. */\n readonly isError?: boolean;\n readonly artifact?: ReadonlyJSONValue;\n };\n\n export type ToolApprovalInputResponse = {\n readonly decision: \"approve\" | \"reject\" | \"edit\" | \"respond\";\n readonly editedArgs?: ReadonlyJSONValue;\n readonly message?: string;\n };\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state with its response echo. */\n export type InputRequestState = InputRequest & {\n readonly response: InputResponse | null;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n readonly sourceId: string;\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 export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the server-side queue: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions and excludes the\n * client-local `capabilities.queue` buffer.\n */\n readonly queue?: readonly RunQueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly RunQueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning it\n * (even empty) routes tool results and approvals with a matching pending\n * request through `run/input`. Presence must be stable across conversions.\n */\n readonly inputRequests?: readonly AssistantTransportThread.InputRequestState[];\n };\n\n export type StateConverter<T> = (state: T) => State;\n\n /** Folds an unsettled command into a draft of the client state; called once per pending command, in send order, re-run on every state change. A throwing fold logs and drops that command's update. */\n export type Optimistic<T> = (\n draft: T,\n command: Command,\n ctx: StatewireClient.OptimisticContext,\n ) => void;\n\n export type HeadersValue = Record<string, string> | Headers;\n\n export type Protocol = \"data-stream\" | \"assistant-transport\";\n\n export type SendCommandsRequestBody = {\n commands: Command[];\n state: unknown;\n system: string | undefined;\n tools: Record<string, unknown> | undefined;\n callSettings: LanguageModelV1CallSettings | undefined;\n config: LanguageModelConfig | undefined;\n threadId: string | null;\n parentId?: string | null;\n [key: string]: unknown;\n };\n\n export type Options<T> = {\n initialState: T;\n converter: StateConverter<T>;\n optimistic?: Optimistic<T> | undefined;\n api: string;\n resumeApi?: string | undefined;\n protocol?: Protocol | undefined;\n headers: HeadersValue | (() => Promise<HeadersValue>);\n body?: object | (() => Promise<object | undefined>) | undefined;\n /** Transform the fully assembled request body before it is sent. */\n prepareSendCommandsRequest?:\n | ((\n body: SendCommandsRequestBody,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>)\n | undefined;\n onResponse?: ((response: Response) => void) | undefined;\n onFinish?: (() => void) | undefined;\n onError?:\n | ((\n error: Error,\n params: {\n commands: Command[];\n updateState: (updater: (state: T) => T) => void;\n },\n ) => void | Promise<void>)\n | undefined;\n /**\n * Called when commands are cancelled. After an error, queued commands are\n * cancelled once `onError` settles; `error` then carries the cause.\n */\n onCancel?:\n | ((params: {\n commands: Command[];\n updateState: (updater: (state: T) => T) => void;\n error?: Error;\n }) => void)\n | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /**\n * Buffer messages sent during a run in an in-memory queue and dispatch\n * them once the run settles. Steering interrupts the active run.\n * Mutually exclusive with the converter's `queue` projection.\n */\n queue?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\n };\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useAssistantTransportThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;;AAwDA,MAAM8C,sBAA2D,CAAC;AA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D,SAAO,CAAC;EAC3D;EACAuI,gBAAgB;GAEdpB,cAAcD,MAAM;GACpBd,aAAa;EACf;EACAoC,gBAAgB;GACd,IAAIxG,QAAQ6E,cAAc4B,UAAU;IAClClF,SAAS,EAAEjC,MAAM,eAAe,CAAC;IACjC;GACF;GACA,IAAI,CAACU,QAAQ0G,WACX,MAAM,IAAI/H,MAAM,+CAA+C;GACjE,SAAcgI,OAAO,CAAC,CAACjF,YAAY,CAAC,CAAC;EACvC;EACA,GAAIrD,kBAAkByB,KAAAA,KAAa;GACjC8G,kBAAkBC,gBAChBtF,SACEhE,uBACEiF,aAAanC,QAAQhC,eACrBwI,WACF,CACF;GACFC,0BAA0B9G,cACxBuB,SACEjE,yBACEkF,aAAanC,QAAQhC,eACrB2B,SACF,CACF;EACJ;EACA+G,mBAAmB,EAAEtH,YAAYuH,cAAqC;GACpE,IAAI,CAACvE,gBAAgBkE,OAAOlH,YAAYuH,OAAO,GAC7C,MAAM,IAAIrI,MAAM,aAAac,WAAU,4BAA6B;EACxE;EACAwH,sBAAsBC,aAAsB;GAC1C,SAAcC,YAAYD,QAAQ,CAAC,CAACxF,YAAY,CAAC,CAAC;GAElDc,aAAanC,UAAUiC,UACrBxD,aACIF,eACEsI,UACA,CAAC,GAAG5F,MAAMP,WAAW,GAAGO,MAAMR,MAAM,GACpChC,YACAE,KACF,IACAkI,QACN;GACAzE,gBAAgBW,MAAM;GACtBxB,gBAAgBpE,mBAAmB;EACrC;CACF,CAAC,CACH;AACF;AAEA,MAAaS,4BACX+B,YAEAhF,SAAS+E,2BAA2B,CAAC,CACnCC,OACF;AAuPF1E,uBACEyE,6BACA5E,eAAe2E,KAAAA,CAAkB,CAAC,CAACqL,IACrC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/react-statewire",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "assistant-ui thread binding for statewire backends",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -34,7 +34,7 @@
34
34
  "@assistant-ui/store": "^0.3.0",
35
35
  "@assistant-ui/tap": "^0.9.7",
36
36
  "assistant-stream": "^0.3.33",
37
- "statewire": "^0.5.0"
37
+ "statewire": "^0.6.0"
38
38
  },
39
39
  "peerDependencies": {
40
40
  "@assistant-ui/react": ">=0.15.6",
@@ -31,7 +31,8 @@ import type {
31
31
  } from "@assistant-ui/core";
32
32
  import type { ReadonlyJSONValue } from "assistant-stream/utils";
33
33
  import { ToolInvocationTracker } from "@assistant-ui/core/internal";
34
- import { useStatewire } from "statewire";
34
+ import { applyOptimistic, useStatewire } from "statewire";
35
+ import type { StatewireClient } from "statewire";
35
36
  import type { StatewireThread } from "./StatewireThread";
36
37
  import { AssistantTransportHost } from "./host";
37
38
  import type {
@@ -87,6 +88,28 @@ export const asAssistantTransportExtras = (
87
88
  return extras as AssistantTransportExtras;
88
89
  };
89
90
 
91
+ const foldOptimistic = (
92
+ state: unknown,
93
+ commands: readonly AssistantTransportThread.Command[],
94
+ optimistic: AssistantTransportThread.Optimistic<unknown>,
95
+ ctxOf: (command: object) => StatewireClient.OptimisticContext,
96
+ ): unknown => {
97
+ let next = state;
98
+ for (const command of commands) {
99
+ try {
100
+ next = applyOptimistic(next, (draft) =>
101
+ optimistic(draft, command, ctxOf(command)),
102
+ );
103
+ } catch (error) {
104
+ console.error(
105
+ `statewire: optimistic reducer threw for "${command.type}"; dropping its optimistic update`,
106
+ error,
107
+ );
108
+ }
109
+ }
110
+ return next;
111
+ };
112
+
90
113
  const messagesContainToolCall = (
91
114
  messages: readonly ThreadMessage[],
92
115
  toolCallId: string,
@@ -140,15 +163,33 @@ const useAssistantTransportThread = (
140
163
  const [toolStatuses, setToolStatuses] =
141
164
  useState<Record<string, ToolExecutionStatus>>(EMPTY_TOOL_STATUSES);
142
165
 
143
- const { converter } = options;
166
+ const [ctxOf] = useState(() => {
167
+ const ctxs = new WeakMap<object, StatewireClient.OptimisticContext>();
168
+ let seq = 0;
169
+ return (command: object): StatewireClient.OptimisticContext => {
170
+ let ctx = ctxs.get(command);
171
+ if (ctx === undefined) {
172
+ ctx = { ts: Date.now(), seq: ++seq };
173
+ ctxs.set(command, ctx);
174
+ }
175
+ return ctx;
176
+ };
177
+ });
178
+
179
+ const { converter, optimistic } = options;
144
180
  const converted = useMemo(
145
181
  () =>
146
- converter(agentState, {
147
- pendingCommands: [...queue.inTransit, ...queue.queued],
148
- isSending,
149
- toolStatuses,
150
- }),
151
- [converter, agentState, queue, isSending, toolStatuses],
182
+ converter(
183
+ optimistic
184
+ ? foldOptimistic(
185
+ agentState,
186
+ [...queue.inTransit, ...queue.queued],
187
+ optimistic,
188
+ ctxOf,
189
+ )
190
+ : agentState,
191
+ ),
192
+ [converter, optimistic, agentState, queue, ctxOf],
152
193
  );
153
194
  const convertedRef = useRef(converted);
154
195
  convertedRef.current = converted;
@@ -397,11 +438,16 @@ const useAssistantTransportThread = (
397
438
  onLoadExternalState: (imported: unknown) => {
398
439
  void commands.importState(imported).catch(() => {});
399
440
  // reset() aborts tools before React re-renders — gate their late results against the imported state
400
- convertedRef.current = options.converter(imported, {
401
- pendingCommands: [...queue.inTransit, ...queue.queued],
402
- isSending,
403
- toolStatuses: EMPTY_TOOL_STATUSES,
404
- });
441
+ convertedRef.current = converter(
442
+ optimistic
443
+ ? foldOptimistic(
444
+ imported,
445
+ [...queue.inTransit, ...queue.queued],
446
+ optimistic,
447
+ ctxOf,
448
+ )
449
+ : imported,
450
+ );
405
451
  toolInvocations.reset();
406
452
  setToolStatuses(EMPTY_TOOL_STATUSES);
407
453
  },
@@ -577,16 +623,14 @@ export namespace AssistantTransportThread {
577
623
  readonly inputRequests?: readonly AssistantTransportThread.InputRequestState[];
578
624
  };
579
625
 
580
- export type ConnectionMetadata = {
581
- pendingCommands: Command[];
582
- isSending: boolean;
583
- toolStatuses: Record<string, ToolExecutionStatus>;
584
- };
626
+ export type StateConverter<T> = (state: T) => State;
585
627
 
586
- export type StateConverter<T> = (
587
- state: T,
588
- connectionMetadata: ConnectionMetadata,
589
- ) => State;
628
+ /** Folds an unsettled command into a draft of the client state; called once per pending command, in send order, re-run on every state change. A throwing fold logs and drops that command's update. */
629
+ export type Optimistic<T> = (
630
+ draft: T,
631
+ command: Command,
632
+ ctx: StatewireClient.OptimisticContext,
633
+ ) => void;
590
634
 
591
635
  export type HeadersValue = Record<string, string> | Headers;
592
636
 
@@ -607,6 +651,7 @@ export namespace AssistantTransportThread {
607
651
  export type Options<T> = {
608
652
  initialState: T;
609
653
  converter: StateConverter<T>;
654
+ optimistic?: Optimistic<T> | undefined;
610
655
  api: string;
611
656
  resumeApi?: string | undefined;
612
657
  protocol?: Protocol | undefined;
@@ -11,6 +11,7 @@ import {
11
11
  export type TestState = {
12
12
  messages: { id: string; role: "user" | "assistant"; text: string }[];
13
13
  todos?: string[];
14
+ isRunning?: boolean;
14
15
  };
15
16
 
16
17
  export const INITIAL_STATE: TestState = { messages: [] };
@@ -34,24 +35,24 @@ export const toThreadMessage = (m: {
34
35
 
35
36
  export const defaultConverter: AssistantTransportThread.StateConverter<
36
37
  TestState
37
- > = (state, meta) => ({
38
- messages: [
39
- ...state.messages.map(toThreadMessage),
40
- ...meta.pendingCommands.flatMap((c, i) =>
41
- c.type === "run/steer" && "message" in c
42
- ? [
43
- toThreadMessage({
44
- id: `optimistic-${i}`,
45
- role: "user",
46
- text: c.message.parts.find((p) => p.type === "text")?.text ?? "",
47
- }),
48
- ]
49
- : [],
50
- ),
51
- ],
52
- isRunning: meta.isSending,
38
+ > = (state) => ({
39
+ messages: state.messages.map(toThreadMessage),
40
+ isRunning: state.isRunning ?? false,
53
41
  });
54
42
 
43
+ export const defaultOptimistic: AssistantTransportThread.Optimistic<
44
+ TestState
45
+ > = (draft, command, ctx) => {
46
+ draft.isRunning = true;
47
+ if (command.type === "run/steer" && "message" in command) {
48
+ draft.messages.push({
49
+ id: `optimistic-${ctx.seq}`,
50
+ role: "user",
51
+ text: command.message.parts.find((p) => p.type === "text")?.text ?? "",
52
+ });
53
+ }
54
+ };
55
+
55
56
  export const sseEvent = (chunk: unknown) =>
56
57
  `data: ${JSON.stringify(chunk)}\n\n`;
57
58
  export const DONE = "data: [DONE]\n\n";
@@ -149,6 +150,7 @@ export const mountThread = (
149
150
  api: "https://example.com/api",
150
151
  headers: {},
151
152
  converter: defaultConverter,
153
+ optimistic: defaultOptimistic,
152
154
  protocol: "assistant-transport",
153
155
  ...options,
154
156
  }),
@@ -181,46 +183,44 @@ export const threadTexts = (aui: () => ReturnType<typeof useAui>) =>
181
183
  m.parts.flatMap((p) => (p.type === "text" ? [p.text] : [])).join(""),
182
184
  );
183
185
 
184
- export const toolCallConverter = (
185
- metas: AssistantTransportThread.ConnectionMetadata[],
186
- ): AssistantTransportThread.StateConverter<TestState> => {
187
- type ToolCallState = TestState & {
188
- toolCall?: { id: string; name: string; argsText: string };
189
- inputRequests?: AssistantTransportThread.InputRequestState[];
190
- };
191
- return (state, meta) => {
192
- metas.push(meta);
193
- const base = {
194
- ...defaultConverter(state, meta),
195
- inputRequests: (state as ToolCallState).inputRequests ?? [],
186
+ export const toolCallConverter =
187
+ (): AssistantTransportThread.StateConverter<TestState> => {
188
+ type ToolCallState = TestState & {
189
+ toolCall?: { id: string; name: string; argsText: string };
190
+ inputRequests?: AssistantTransportThread.InputRequestState[];
196
191
  };
197
- const toolCall = (state as ToolCallState).toolCall;
198
- if (!toolCall) return base;
199
- return {
200
- ...base,
201
- messages: [
202
- ...base.messages,
203
- {
204
- id: "a-tool",
205
- role: "assistant",
206
- createdAt: new Date(0),
207
- content: [
208
- {
209
- type: "tool-call",
210
- toolCallId: toolCall.id,
211
- toolName: toolCall.name,
212
- args: JSON.parse(toolCall.argsText),
213
- argsText: toolCall.argsText,
214
- },
215
- ],
216
- attachments: [],
217
- metadata: { custom: {} },
218
- status: { type: "requires-action", reason: "tool-call" },
219
- } as unknown as ExternalThreadMessage,
220
- ],
192
+ return (state) => {
193
+ const base = {
194
+ ...defaultConverter(state),
195
+ inputRequests: (state as ToolCallState).inputRequests ?? [],
196
+ };
197
+ const toolCall = (state as ToolCallState).toolCall;
198
+ if (!toolCall) return base;
199
+ return {
200
+ ...base,
201
+ messages: [
202
+ ...base.messages,
203
+ {
204
+ id: "a-tool",
205
+ role: "assistant",
206
+ createdAt: new Date(0),
207
+ content: [
208
+ {
209
+ type: "tool-call",
210
+ toolCallId: toolCall.id,
211
+ toolName: toolCall.name,
212
+ args: JSON.parse(toolCall.argsText),
213
+ argsText: toolCall.argsText,
214
+ },
215
+ ],
216
+ attachments: [],
217
+ metadata: { custom: {} },
218
+ status: { type: "requires-action", reason: "tool-call" },
219
+ } as unknown as ExternalThreadMessage,
220
+ ],
221
+ };
221
222
  };
222
223
  };
223
- };
224
224
 
225
225
  export const emitToolCall = (server: StreamResponse) => {
226
226
  server.emit({