@assistant-ui/react-statewire 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
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"}
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;cA6XU,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"}
@@ -152,7 +152,7 @@ const useAssistantTransportThread = (options) => {
152
152
  if (queueProjection !== void 0 && options.capabilities?.queue) throw new Error("statewire: the converter's queue projection excludes capabilities.queue");
153
153
  const [queueSeam] = useState(() => ({ present: queueProjection !== void 0 }));
154
154
  if (queueSeam.present !== (queueProjection !== void 0)) throw new Error("statewire: the converter's queue projection must be stable — it was " + (queueSeam.present ? "defined" : "undefined") + " on first convert and changed since");
155
- const serverQueue = useMemo(() => queueProjection ? createRunQueueAdapter(converted.messages, queueProjection, steerProjection, dispatch) : void 0, [
155
+ const serverQueue = useMemo(() => queueProjection ? createRunQueueAdapter(converted.messages, queueProjection, steerProjection, dispatch, (command_4) => dispatch(command_4)) : void 0, [
156
156
  converted.messages,
157
157
  queueProjection,
158
158
  steerProjection,
@@ -194,8 +194,8 @@ const useAssistantTransportThread = (options) => {
194
194
  } },
195
195
  ...options.capabilities?.edit && { onEdit: handleEdit },
196
196
  onReload: (parentId) => {
197
- const command_4 = resolveReloadCommand(convertedRef.current.messages, parentId);
198
- toolInvocations.abort().then(() => dispatch(command_4));
197
+ const command_5 = resolveReloadCommand(convertedRef.current.messages, parentId);
198
+ toolInvocations.abort().then(() => dispatch(command_5));
199
199
  },
200
200
  onCancel: () => {
201
201
  messageQueue?.clear();
@@ -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","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;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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,+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"}
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 (command) => dispatch(command),\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;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,kBACJR,OACAS,UACAC,YACAE,UACY;CACZ,IAAIE,OAAOd;CACX,KAAK,MAAMJ,WAAWa,UACpB,IAAI;EACFK,OAAO3C,gBAAgB2C,OAAOC,UAC5BL,WAAWK,OAAOnB,SAASgB,MAAMhB,OAAO,CAAC,CAC3C;CACF,SAASoB,OAAO;EACdC,QAAQD,MACN,4CAA4CpB,QAAQsB,KAAI,oCACxDF,KACF;CACF;CAEF,OAAOF;AACT;AAEA,MAAMK,2BACJC,UACAC,eAEAD,SAASE,MAAMC,YACbA,QAAQC,QAAQF,MACbG,SACCA,KAAKP,SAAS,gBACbO,KAAKJ,eAAeA,cAClBI,KAAKL,aAAaM,KAAAA,KACjBP,wBAAwBM,KAAKL,UAAUC,UAAU,EACzD,CACF;AAEF,MAAMM,+BACJC,YAC2B;CAC3B,MAAME,YAAY3E,sBAAsB;CACxC,MAAM,CAAC4E,iBAAiBrF,qBAAqC;EAC3D,MAAMsF,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,gB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,OACF;AAuPF1E,uBACEyE,6BACA5E,eAAe2E,KAAAA,CAAkB,CAAC,CAACqL,IACrC"}
@@ -153,6 +153,8 @@ declare namespace StatewireThread {
153
153
  readonly status: Exclude<RunStatus, "ready">;
154
154
  readonly queue: readonly RunsQueueEntry[];
155
155
  readonly steerQueue: readonly RunsQueueEntry[];
156
+ /** The current dispatch's unacked messages — handed to the run, cleared at the messages-ack. */
157
+ readonly dispatching: readonly RunsQueueEntry[];
156
158
  /** The parked pending set; present only in input-required. */
157
159
  readonly inputRequests?: readonly InputRequestState[];
158
160
  readonly error: RunsError | null;
@@ -172,6 +174,8 @@ declare namespace StatewireThread {
172
174
  readonly runId: string | null;
173
175
  readonly queue: readonly RunsQueueEntry[];
174
176
  readonly steerQueue: readonly RunsQueueEntry[];
177
+ /** The current dispatch's unacked messages — handed to the run, cleared at the messages-ack. */
178
+ readonly dispatching: readonly RunsQueueEntry[];
175
179
  /** The parked pending set; present only in input-required. */
176
180
  readonly inputRequests?: readonly InputRequestState[];
177
181
  readonly error: RunsError | null;
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;cAoUa;GACV,GACC,SAAS,gBAAgB,YAAY,KACpC,gBAAgB;GAClB,GACC,SAAS,gBAAgB,QAAQ,KAChC,gBAAgB;;kBAIJ;OACH,UAAU,KAAK,gBAAgB,UAAU;OAEzC;aACD;aACA;;OAGC;aACD;aACA;aACA;aACA;;OAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;OAIV;aACD;aACA;;OAGC;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;aACA;;OAGC;aACD;aACA,SAAS;aACT;;OAGC;aACD;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;cACC,cAAc;;;OAId,eACR,uBACA,2BACA;OAEQ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Q;;IAExC,eAAe,OAAO;IACtB,WAAW,mBAAmB;;IAE9B,aACI,gBAAgB,WACd,GACA,mBAAmB;;;;YAOjB;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":";;;;;;;cAuWa;GACV,GACC,SAAS,gBAAgB,YAAY,KACpC,gBAAgB;GAClB,GACC,SAAS,gBAAgB,QAAQ,KAChC,gBAAgB;;kBAIJ;OACH,UAAU,KAAK,gBAAgB,UAAU;OAEzC;aACD;aACA;;OAGC;aACD;aACA;aACA;aACA;;OAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;OAIV;aACD;aACA;;OAGC;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;aACA;;OAGC;aACD;aACA,SAAS;aACT;;OAGC;aACD;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;cACC,cAAc;;;OAId,eACR,uBACA,2BACA;OAEQ;aACD,QAAQ;;aAER;aACA,WAAW;;OAGV;aACD;aACA,aAAa;aACb;;OAGC,gBAAgB;OAEhB;aACD;aACA;aACA,UAAU;;;OAIT,oBAAoB;aACrB,UAAU;;OAGT;aACD;aACA;;OAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;OAEQ,UAAU,yBAAyB,UAAU;;OAG7C;aACD;aACA,iBAAiB,WAAW;;OAG3B;aACD,mBAAmB;aACnB,QAAQ;aACR;;aAEA;;;;;;;aAOA,iBAAiB;;aAEjB,sBAAsB;;;;;;;aAOtB,yBAAyB;;;OAIxB;;OAQA,iBAAiB;;aAElB,OAAO;;;OAIN;aACD;cACC,cAAc;;;OAId;;aAED;aACA,QAAQ,QAAQ;aAChB,gBAAgB;aAChB,qBAAqB;;aAErB,sBAAsB;;aAEtB,yBAAyB;aACzB,OAAO;aACP;;;OAIC;;aAED,QAAQ;;aAER,eAAe;;;OAId;aACD,QAAQ;;aAER;aACA,gBAAgB;aAChB,qBAAqB;;aAErB,sBAAsB;;aAEtB,yBAAyB;aACzB,OAAO;aACP;;OAGC;IACV,iBAAiB;IACjB;;IAEA,YAAY,gBAAgB;;IAE5B,OAAO;;OAGG,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;;OAGO;aACD,mBAAmB;aACnB,QAAQ;;OAGP,mBAAmB,MAC7B,OAAO,GACP,oBAAoB;IAAuB,MAAM;QAC9C;;;;;OAMO;aACD;cACC,cAAc;;OAGd,QAAQ;IAClB,WAAW,UAAU;IACrB,cAAc;IACd,WAAW,eAAe;IAC1B;;;;;;IAMA;;IAEA,qBAAqB;;IAErB,oBAEM,QAAQ,UAAU,cAChB,mBAAmB,2BAErB;MAAO,OAAO,YAAY;;;IAIhC,kBACM,OAAO,YAAY,IAAI;MAAO,SAAS,UAAU;;;IAGvD,uBACM,YAAY,gBAAgB;IAElC,YAAY,OAAO;IACnB;MAEM;;MAEA;;MAEA;;IAGN;MAEM,cAAc;MACd,SAAS;MACT,WAAW;;;;OAMP,YAAY,KAAK,KAAK,QAAQ;;IAExC,eAAe,OAAO;IACtB,WAAW,mBAAmB;;IAE9B,aACI,gBAAgB,WACd,GACA,mBAAmB;;;;YAOjB;cACE;MACR,YAAY,gBAAgB;MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB"}
@@ -1,4 +1,4 @@
1
- import { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, toWireMessage, viewedLeafId } from "./runCommands.js";
1
+ import { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, toDispatchingMessage, toWireMessage, viewedLeafId } from "./runCommands.js";
2
2
  import { resolveToolApprovalInput, resolveToolResultInput } from "./inputRequests.js";
3
3
  import { symbolAssistantTransportExtras } from "./AssistantTransportThread.js";
4
4
  import { runsOptimistic } from "./runsOptimistic.js";
@@ -14,6 +14,7 @@ const READY_RUNS = {
14
14
  runId: null,
15
15
  queue: [],
16
16
  steerQueue: [],
17
+ dispatching: [],
17
18
  error: null,
18
19
  runLeafMessageId: null
19
20
  };
@@ -74,11 +75,22 @@ const useStatewireThread = (options) => {
74
75
  ]);
75
76
  const dispatch = useCallback((command_1) => {
76
77
  setPending((prev_0) => [...prev_0, command_1]);
77
- commands[command_1.type](command_1).catch((error_0) => {
78
+ const settled = commands[command_1.type](command_1);
79
+ settled.catch((error_0) => {
78
80
  retire(command_1);
79
81
  latest.current.onError?.(error_0);
80
82
  });
83
+ return settled;
81
84
  }, [commands, retire]);
85
+ const threadRef = useRef(null);
86
+ const dispatchSend = useCallback((command_2, message) => {
87
+ if (message.sourceId != null) return void dispatch(command_2);
88
+ const text = message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n\n");
89
+ dispatch(command_2).catch(() => {
90
+ const setText = threadRef.current.composer().setText;
91
+ setText((prev_1) => prev_1 === "" ? text : prev_1);
92
+ });
93
+ }, [dispatch]);
82
94
  const runs = useMemo(() => {
83
95
  if (runsOption === void 0) return void 0;
84
96
  const entry = (runsOption === true ? state_0 : runsOption(state_0))?.runs?.[0];
@@ -87,6 +99,7 @@ const useStatewireThread = (options) => {
87
99
  runId: entry.runId,
88
100
  queue: entry.queue,
89
101
  steerQueue: entry.steerQueue,
102
+ dispatching: entry.dispatching,
90
103
  ...entry.inputRequests !== void 0 && { inputRequests: entry.inputRequests },
91
104
  error: entry.error,
92
105
  runLeafMessageId: entry.runLeafMessageId
@@ -108,16 +121,23 @@ const useStatewireThread = (options) => {
108
121
  state_0,
109
122
  metadata
110
123
  ]);
124
+ const messages = useMemo(() => {
125
+ const known = new Set(converted.messages.map((m) => m.id));
126
+ const pending_0 = (runs?.dispatching ?? []).filter((e) => !known.has(e.id));
127
+ if (pending_0.length === 0) return converted.messages;
128
+ return [...converted.messages, ...pending_0.map(toDispatchingMessage)];
129
+ }, [converted.messages, runs]);
111
130
  const queueItems = runs !== void 0 ? runs.queue : converted.queue;
112
131
  const steerQueueItems = runs !== void 0 ? runs.steerQueue : converted.steerQueue;
113
132
  if (steerQueueItems !== void 0 && queueItems === void 0) throw new Error("statewire: the converter's steerQueue projection requires the queue projection");
114
133
  const [queueSeam] = useState(() => ({ present: queueItems !== void 0 }));
115
134
  if (queueSeam.present !== (queueItems !== void 0)) throw new Error("statewire: the converter's queue projection must be stable — it was " + (queueSeam.present ? "defined" : "undefined") + " on first convert and changed since");
116
- const queue = useMemo(() => queueItems ? createRunQueueAdapter(converted.messages, queueItems, steerQueueItems, dispatch) : void 0, [
117
- converted.messages,
135
+ const queue = useMemo(() => queueItems ? createRunQueueAdapter(messages, queueItems, steerQueueItems, dispatch, dispatchSend) : void 0, [
136
+ messages,
118
137
  queueItems,
119
138
  steerQueueItems,
120
- dispatch
139
+ dispatch,
140
+ dispatchSend
121
141
  ]);
122
142
  const inputRequests = runs !== void 0 ? runs.inputRequests ?? [] : converted.inputRequests;
123
143
  const [inputSeam] = useState(() => ({ present: inputRequests !== void 0 }));
@@ -136,21 +156,21 @@ const useStatewireThread = (options) => {
136
156
  inputRequests,
137
157
  runs
138
158
  ]);
139
- const handleAppend = (message) => {
140
- dispatch(message.sourceId != null ? resolveEditCommand(message) : {
159
+ const handleAppend = (message_0) => {
160
+ dispatchSend(message_0.sourceId != null ? resolveEditCommand(message_0) : {
141
161
  type: "run/steer",
142
- message: toWireMessage(message, crypto.randomUUID()),
143
- anchorMessageId: viewedLeafId(converted.messages)
144
- });
162
+ message: toWireMessage(message_0, crypto.randomUUID()),
163
+ anchorMessageId: viewedLeafId(messages)
164
+ }, message_0);
145
165
  };
146
166
  const handleReload = (parentId) => {
147
- dispatch(resolveReloadCommand(converted.messages, parentId));
167
+ dispatch(resolveReloadCommand(messages, parentId));
148
168
  };
149
- const handleEdit = (message_0) => {
150
- dispatch(resolveEditCommand(message_0));
169
+ const handleEdit = (message_1) => {
170
+ dispatch(resolveEditCommand(message_1));
151
171
  };
152
- return useResource(ExternalThread({
153
- messages: converted.messages,
172
+ const thread = useResource(ExternalThread({
173
+ messages,
154
174
  isRunning: runs !== void 0 ? runs.status === "running" : converted.isRunning,
155
175
  isLoading: !attached,
156
176
  state: converted.state,
@@ -180,6 +200,8 @@ const useStatewireThread = (options) => {
180
200
  });
181
201
  }
182
202
  }));
203
+ threadRef.current = thread;
204
+ return thread;
183
205
  };
184
206
  const StatewireThread = (options) => resource(useStatewireThread)(options);
185
207
  forwardTransformScopes(useStatewireThread, ExternalThread(void 0).hook);
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportThread","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","AnyOptions","StatewireThread","Options","RunsOptions","READY_RUNS","Runs","status","runId","queue","steerQueue","error","runLeafMessageId","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","runsOption","runs","runsSeam","Error","state","transportState","commands","connection","setContext","transport","optimistic","draft","ctx","runsOpt","onCommandChange","update","params","onStateChange","onConnectionChange","attached","initialState","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","onError","subscribe","dispatch","type","mount","RunsState","entry","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","State","queueItems","steerQueueItems","queueSeam","present","messages","inputSeam","extras","sendCommand","reconnect","handleAppend","message","sourceId","crypto","randomUUID","anchorMessageId","handleReload","parentId","handleEdit","isRunning","isLoading","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","Transport","TextPart","text","FilePart","mediaType","url","filename","UserMessage","id","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","InputRequestState","RunReloadCommand","RunCommand","QueueItem","RunStatus","RunsQueueEntry","meta","RunsError","RunState","Exclude","ConnectionState","StateConverter","connectionMetadata","RunsConverterState","RunsStateConverter","StopPayload","reason","CommandUpdate","NonNullable","changes","Changes","Connection","Omit","Optimistic","Assistant","Commands","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/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\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 ExternalThreadQueueAdapter,\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 { symbolAssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type {\n AssistantTransportExtras,\n AssistantTransportThread,\n} from \"./AssistantTransportThread\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\ntype AnyOptions =\n | StatewireThread.Options<any>\n | StatewireThread.RunsOptions<any>;\n\nconst READY_RUNS: StatewireThread.Runs = {\n status: \"ready\",\n runId: null,\n queue: [],\n steerQueue: [],\n error: null,\n runLeafMessageId: null,\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 = (options: AnyOptions): 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 runsOption = options.runs;\n const [runsSeam] = useState(() => runsOption !== undefined);\n if (runsSeam !== (runsOption !== undefined))\n throw new Error(\n \"statewire: the runs option must be stable — it was \" +\n (runsSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const {\n state: transportState,\n commands,\n connection,\n setContext,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n ...(runsSeam && {\n optimistic: (draft, command, ctx) => {\n const runsOpt = latest.current.runs!;\n runsOptimistic(runsOpt === true ? draft : runsOpt(draft), command, ctx);\n (latest.current as StatewireThread.RunsOptions<unknown>).optimistic?.(\n draft,\n command,\n ctx,\n );\n },\n }),\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 const attached = transportState !== undefined;\n const state = attached ? transportState : options.initialState;\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 void commands[command.type]!(command).catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n },\n [commands, retire],\n );\n\n const runs = useMemo((): StatewireThread.Runs | undefined => {\n if (runsOption === undefined) return undefined;\n const mount = (runsOption === true ? state : runsOption(state)) as\n | StatewireThread.RunsState\n | undefined;\n const entry = mount?.runs?.[0];\n return entry === undefined\n ? READY_RUNS\n : {\n status: entry.status,\n runId: entry.runId,\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n error: entry.error,\n runLeafMessageId: entry.runLeafMessageId,\n };\n }, [runsOption, 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 !== undefined && { runs }),\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n () =>\n converter(\n state,\n metadata as StatewireThread.ConnectionMetadata & {\n runs: StatewireThread.Runs;\n },\n ) as StatewireThread.State,\n [converter, state, metadata],\n );\n const queueItems = runs !== undefined ? runs.queue : converted.queue;\n const steerQueueItems =\n runs !== undefined ? runs.steerQueue : converted.steerQueue;\n if (steerQueueItems !== undefined && queueItems === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n const [queueSeam] = useState(() => ({\n present: queueItems !== undefined,\n }));\n if (queueSeam.present !== (queueItems !== 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\n const queue = useMemo(\n (): ExternalThreadQueueAdapter | undefined =>\n queueItems\n ? createRunQueueAdapter(\n converted.messages,\n queueItems,\n steerQueueItems,\n dispatch,\n )\n : undefined,\n [converted.messages, queueItems, steerQueueItems, dispatch],\n );\n\n const inputRequests =\n runs !== undefined ? (runs.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,\n ...(inputRequests !== undefined && { inputRequests }),\n ...(runs !== undefined && { runs }),\n }),\n [dispatch, connection.reconnect, state, inputRequests, runs],\n );\n\n const handleAppend = (message: AppendMessage) => {\n dispatch(\n message.sourceId != null\n ? resolveEditCommand(message)\n : {\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(converted.messages),\n },\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(converted.messages, parentId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(message));\n };\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning:\n runs !== undefined ? runs.status === \"running\" : converted.isRunning,\n isLoading: !attached,\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 && { queue }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () => dispatch({ type: \"run/continue\" }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval)),\n }),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n const runId = runs !== undefined ? runs.runId : converted.runId;\n const args =\n runId === undefined\n ? payload === undefined\n ? []\n : [payload]\n : [{ ...payload, runId }];\n void commands[\"run/stop\"]!(...args).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n};\n\nexport const StatewireThread: {\n <T>(\n options: StatewireThread.RunsOptions<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n <T>(\n options: StatewireThread.Options<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n} = (options: AnyOptions): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options);\n\nexport namespace StatewireThread {\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\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 } & (\n | {\n readonly message: UserMessage;\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 Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: UserMessage;\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 Placement;\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: UserMessage;\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 = AssistantTransportThread.Command | RunCommand;\n\n /** A queued message projected out of the host state, wire shape. */\n export type QueueItem = {\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 /** The live run's id projected out of the host state; stamped onto `run/stop`. */\n readonly runId?: string | null;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the queue capability: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions.\n */\n readonly queue?: readonly QueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly QueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning\n * it (even empty) routes tool results and approvals with a matching\n * pending request through `run/input`. Presence must be stable across\n * conversions.\n */\n readonly inputRequests?: readonly InputRequestState[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus =\n | \"ready\"\n | \"running\"\n | \"stopped\"\n | \"error\"\n | \"input-required\";\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 /** 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 — minted at dispatch, persists through input-required, null in error/stop. */\n readonly runId: string | null;\n readonly status: Exclude<RunStatus, \"ready\">;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\n readonly runLeafMessageId: string | null;\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: RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the selected mount with unsettled commands folded in, ready defaults while resting. */\n export type Runs = {\n readonly status: RunStatus;\n /** The live run's id — non-null in running and input-required; stamped onto `run/stop`. */\n readonly runId: string | null;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\n readonly runLeafMessageId: string | null;\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; present iff the `runs` option is set. */\n runs?: Runs;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /** Converter output in runs mode: app-owned keys only — the lib projects the run mounts itself. */\n export type RunsConverterState = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type RunsStateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata & { runs: Runs },\n ) => RunsConverterState;\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 initialState: T;\n converter: StateConverter<T>;\n runs?: 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 /** Options with the runs read enabled: the lib types the run mounts and the converter returns app-owned keys only. */\n export type RunsOptions<T> = Omit<Options<T>, \"converter\" | \"runs\"> & {\n /** `true` reads the run mounts off the state root; a selector picks a nested mount. */\n runs: true | ((state: T) => unknown);\n converter: RunsStateConverter<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 };\n}\n\ndeclare module \"@assistant-ui/react\" {\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":";;;;;;;;;;;AAiDA,MAAM6C,aAAmC;CACvCE,QAAQ;CACRC,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,OAAO;CACPC,kBAAkB;AACpB;AAEA,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOnC,kBAAkBgC,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,sBAAsBC,YAAgD;CAC1E,MAAMC,SAAS3D,OAAO0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AU,EAAEC,UAAUnB,aAAa;EAC7D,GAAIxB,kBAAkB3D,KAAAA,KAAa;GACjCuG,kBAAkBC,gBAChBlD,SAAS1E,uBAAuB+E,eAAe6C,WAAW,CAAC;GAC7DC,0BAA0BC,aACxBpD,SAAS3E,yBAAyBgF,eAAe+C,QAAQ,CAAC;EAC9D;EACAC,gBAAgB;GACd,MAAMC,UAAUtG,OAAOC,QAAQsG,cAAc;GAC7C,IACED,YAAY5G,KAAAA,MACX,OAAO4G,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAIxF,MAAM,mDAAmD;GACrE,MAAM5B,QAAQ0B,SAASlB,KAAAA,IAAYkB,KAAK1B,QAAQ0E,UAAU1E;GAC1D,MAAMR,OACJQ,UAAUQ,KAAAA,IACN4G,YAAY5G,KAAAA,IACV,CAAA,IACA,CAAC4G,OAAO,IACV,CAAC;IAAE,GAAGA;IAASpH;GAAM,CAAC;GAC5B,SAAc,WAAW,CAAE,GAAGR,IAAI,CAAC,CAACmE,OAAOxD,YAAiB;IAC1DW,OAAOC,QAAQ6C,UAAUzD,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;AACF;AAEA,MAAaT,mBAORmB,YACHxD,SAASuD,kBAAkB,CAAC,CAACC,OAAO;AA4UtCnD,uBACEkD,oBACApD,eAAegD,KAAAA,CAAkB,CAAC,CAACsL,IACrC"}
1
+ {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportThread","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","toDispatchingMessage","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","AnyOptions","StatewireThread","Options","RunsOptions","READY_RUNS","Runs","status","runId","queue","steerQueue","dispatching","error","runLeafMessageId","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","runsOption","runs","runsSeam","Error","state","transportState","commands","connection","setContext","transport","optimistic","draft","ctx","runsOpt","onCommandChange","update","params","onStateChange","onConnectionChange","attached","initialState","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","onError","subscribe","dispatch","settled","type","threadRef","dispatchSend","message","sourceId","text","content","flatMap","part","join","setText","composer","next","mount","RunsState","entry","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","State","messages","known","Set","map","m","id","e","has","queueItems","steerQueueItems","queueSeam","present","inputSeam","extras","sendCommand","reconnect","handleAppend","crypto","randomUUID","anchorMessageId","handleReload","parentId","handleEdit","thread","isRunning","isLoading","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","Transport","TextPart","FilePart","mediaType","url","filename","UserMessage","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","InputRequestState","RunReloadCommand","RunCommand","QueueItem","RunStatus","RunsQueueEntry","meta","RunsError","RunState","Exclude","ConnectionState","StateConverter","connectionMetadata","RunsConverterState","RunsStateConverter","StopPayload","reason","CommandUpdate","NonNullable","changes","Changes","Connection","Omit","Optimistic","Assistant","Commands","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/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\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 ExternalThreadQueueAdapter,\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 { symbolAssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type {\n AssistantTransportExtras,\n AssistantTransportThread,\n} from \"./AssistantTransportThread\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n toDispatchingMessage,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\ntype AnyOptions =\n | StatewireThread.Options<any>\n | StatewireThread.RunsOptions<any>;\n\nconst READY_RUNS: StatewireThread.Runs = {\n status: \"ready\",\n runId: null,\n queue: [],\n steerQueue: [],\n dispatching: [],\n error: null,\n runLeafMessageId: null,\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 = (options: AnyOptions): 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 runsOption = options.runs;\n const [runsSeam] = useState(() => runsOption !== undefined);\n if (runsSeam !== (runsOption !== undefined))\n throw new Error(\n \"statewire: the runs option must be stable — it was \" +\n (runsSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const {\n state: transportState,\n commands,\n connection,\n setContext,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n ...(runsSeam && {\n optimistic: (draft, command, ctx) => {\n const runsOpt = latest.current.runs!;\n runsOptimistic(runsOpt === true ? draft : runsOpt(draft), command, ctx);\n (latest.current as StatewireThread.RunsOptions<unknown>).optimistic?.(\n draft,\n command,\n ctx,\n );\n },\n }),\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 const attached = transportState !== undefined;\n const state = attached ? transportState : options.initialState;\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 runs = useMemo((): StatewireThread.Runs | undefined => {\n if (runsOption === undefined) return undefined;\n const mount = (runsOption === true ? state : runsOption(state)) as\n | StatewireThread.RunsState\n | undefined;\n const entry = mount?.runs?.[0];\n return entry === undefined\n ? READY_RUNS\n : {\n status: entry.status,\n runId: entry.runId,\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n dispatching: entry.dispatching,\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n error: entry.error,\n runLeafMessageId: entry.runLeafMessageId,\n };\n }, [runsOption, 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 !== undefined && { runs }),\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n () =>\n converter(\n state,\n metadata as StatewireThread.ConnectionMetadata & {\n runs: StatewireThread.Runs;\n },\n ) as StatewireThread.State,\n [converter, state, metadata],\n );\n // Dispatch limbo renders as in-flight messages; ids already converted win.\n const messages = useMemo((): StatewireThread.State[\"messages\"] => {\n const known = new Set(converted.messages.map((m) => m.id));\n const pending = (runs?.dispatching ?? []).filter((e) => !known.has(e.id));\n if (pending.length === 0) return converted.messages;\n return [...converted.messages, ...pending.map(toDispatchingMessage)];\n }, [converted.messages, runs]);\n const queueItems = runs !== undefined ? runs.queue : converted.queue;\n const steerQueueItems =\n runs !== undefined ? runs.steerQueue : converted.steerQueue;\n if (steerQueueItems !== undefined && queueItems === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n const [queueSeam] = useState(() => ({\n present: queueItems !== undefined,\n }));\n if (queueSeam.present !== (queueItems !== 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\n const queue = useMemo(\n (): ExternalThreadQueueAdapter | undefined =>\n queueItems\n ? createRunQueueAdapter(\n messages,\n queueItems,\n steerQueueItems,\n dispatch,\n dispatchSend,\n )\n : undefined,\n [messages, queueItems, steerQueueItems, dispatch, dispatchSend],\n );\n\n const inputRequests =\n runs !== undefined ? (runs.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,\n ...(inputRequests !== undefined && { inputRequests }),\n ...(runs !== undefined && { runs }),\n }),\n [dispatch, connection.reconnect, state, inputRequests, runs],\n );\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(message)\n : {\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(message));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning:\n runs !== undefined ? runs.status === \"running\" : converted.isRunning,\n isLoading: !attached,\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 && { queue }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () => dispatch({ type: \"run/continue\" }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval)),\n }),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n const runId = runs !== undefined ? runs.runId : converted.runId;\n const args =\n runId === undefined\n ? payload === undefined\n ? []\n : [payload]\n : [{ ...payload, runId }];\n void commands[\"run/stop\"]!(...args).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n return thread;\n};\n\nexport const StatewireThread: {\n <T>(\n options: StatewireThread.RunsOptions<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n <T>(\n options: StatewireThread.Options<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n} = (options: AnyOptions): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options);\n\nexport namespace StatewireThread {\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\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 } & (\n | {\n readonly message: UserMessage;\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 Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: UserMessage;\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 Placement;\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: UserMessage;\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 = AssistantTransportThread.Command | RunCommand;\n\n /** A queued message projected out of the host state, wire shape. */\n export type QueueItem = {\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 /** The live run's id projected out of the host state; stamped onto `run/stop`. */\n readonly runId?: string | null;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the queue capability: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions.\n */\n readonly queue?: readonly QueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly QueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning\n * it (even empty) routes tool results and approvals with a matching\n * pending request through `run/input`. Presence must be stable across\n * conversions.\n */\n readonly inputRequests?: readonly InputRequestState[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus =\n | \"ready\"\n | \"running\"\n | \"stopped\"\n | \"error\"\n | \"input-required\";\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 /** 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 — minted at dispatch, persists through input-required, null in error/stop. */\n readonly runId: string | null;\n readonly status: Exclude<RunStatus, \"ready\">;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The current dispatch's unacked messages — handed to the run, cleared at the messages-ack. */\n readonly dispatching: readonly RunsQueueEntry[];\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\n readonly runLeafMessageId: string | null;\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: RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the selected mount with unsettled commands folded in, ready defaults while resting. */\n export type Runs = {\n readonly status: RunStatus;\n /** The live run's id — non-null in running and input-required; stamped onto `run/stop`. */\n readonly runId: string | null;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The current dispatch's unacked messages — handed to the run, cleared at the messages-ack. */\n readonly dispatching: readonly RunsQueueEntry[];\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\n readonly runLeafMessageId: string | null;\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; present iff the `runs` option is set. */\n runs?: Runs;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /** Converter output in runs mode: app-owned keys only — the lib projects the run mounts itself. */\n export type RunsConverterState = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type RunsStateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata & { runs: Runs },\n ) => RunsConverterState;\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 initialState: T;\n converter: StateConverter<T>;\n runs?: 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 /** Options with the runs read enabled: the lib types the run mounts and the converter returns app-owned keys only. */\n export type RunsOptions<T> = Omit<Options<T>, \"converter\" | \"runs\"> & {\n /** `true` reads the run mounts off the state root; a selector picks a nested mount. */\n runs: true | ((state: T) => unknown);\n converter: RunsStateConverter<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 };\n}\n\ndeclare module \"@assistant-ui/react\" {\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":";;;;;;;;;;;AAkDA,MAAM8C,aAAmC;CACvCE,QAAQ;CACRC,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,aAAa,CAAA;CACbC,OAAO;CACPC,kBAAkB;AACpB;AAEA,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOrC,kBAAkBkC,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,sBAAsBC,YAAgD;CAC1E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,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAI3G,MAAM,mDAAmD;GACrE,MAAM7B,QAAQ2B,SAASlB,KAAAA,IAAYkB,KAAK3B,QAAQwF,UAAUxF;GAC1D,MAAMR,OACJQ,UAAUS,KAAAA,IACN+H,YAAY/H,KAAAA,IACV,CAAA,IACA,CAAC+H,OAAO,IACV,CAAC;IAAE,GAAGA;IAASxI;GAAM,CAAC;GAC5B,SAAc,WAAW,CAAE,GAAGR,IAAI,CAAC,CAACoE,OAAOxD,YAAiB;IAC1DW,OAAOC,QAAQ6C,UAAUzD,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;CACA8D,UAAUlD,UAAUiG;CACpB,OAAOA;AACT;AAEA,MAAavH,mBAORoB,YACH1D,SAASyD,kBAAkB,CAAC,CAACC,OAAO;AAgVtCrD,uBACEoD,oBACAtD,eAAekD,KAAAA,CAAkB,CAAC,CAACuM,IACrC"}
@@ -1,5 +1,6 @@
1
+ import { StatewireThread } from "./StatewireThread.js";
1
2
  import { AssistantTransportThread } from "./AssistantTransportThread.js";
2
- import { AppendMessage, ExternalThreadQueueAdapter } from "@assistant-ui/core";
3
+ import { AppendMessage, ExternalThreadQueueAdapter, ThreadMessage } from "@assistant-ui/core";
3
4
  //#region src/runCommands.d.ts
4
5
  declare const toWireMessage: (message: AppendMessage, id: string) => AssistantTransportThread.RunUserMessage;
5
6
  declare const toQueueItemState: (item: AssistantTransportThread.RunQueueItem) => {
@@ -12,17 +13,18 @@ declare const toQueueItemState: (item: AssistantTransportThread.RunQueueItem) =>
12
13
  mimeType: string;
13
14
  })[];
14
15
  };
16
+ declare const toDispatchingMessage: (item: StatewireThread.RunsQueueEntry) => ThreadMessage;
15
17
  declare const viewedLeafId: (messages: readonly {
16
18
  id: string;
17
19
  }[]) => string | null;
18
20
  declare const resolveEditCommand: (message: AppendMessage) => AssistantTransportThread.RunEditCommand;
19
21
  declare const createRunQueueAdapter: (messages: readonly {
20
22
  id: string;
21
- }[], queueItems: readonly AssistantTransportThread.RunQueueItem[], steerQueueItems: readonly AssistantTransportThread.RunQueueItem[] | undefined, dispatch: (command: AssistantTransportThread.RunCommand) => void) => ExternalThreadQueueAdapter;
23
+ }[], queueItems: readonly AssistantTransportThread.RunQueueItem[], steerQueueItems: readonly AssistantTransportThread.RunQueueItem[] | undefined, dispatch: (command: AssistantTransportThread.RunCommand) => void, dispatchSend: (command: AssistantTransportThread.RunCommand, message: AppendMessage) => void) => ExternalThreadQueueAdapter;
22
24
  declare const resolveReloadCommand: (messages: readonly {
23
25
  id: string;
24
26
  role: string;
25
27
  }[], parentId: string | null) => AssistantTransportThread.RunReloadCommand;
26
28
  //#endregion
27
- export { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, toQueueItemState, toWireMessage, viewedLeafId };
29
+ export { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, toDispatchingMessage, toQueueItemState, toWireMessage, viewedLeafId };
28
30
  //# sourceMappingURL=runCommands.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"runCommands.d.ts","names":[],"sources":["../src/runCommands.ts"],"mappings":";;;cAOa,gBACX,SAAS,eACT,eACC,yBAAyB;cAwCf,mBACX,MAAM,yBAAyB;;;UAAA,yBAAA;;;;;;;cA2BpB,eACX;EAAqB;;cAGV,qBACX,SAAS,kBACR,yBAAyB;cAUf,wBACX;EAAqB;KACrB,qBAAqB,yBAAyB,gBAC9C,0BAA0B,yBAAyB,4BACnD,WAAW,SAAS,yBAAyB,wBAC5C;cAmDU,uBACX;EAAqB;EAAY;KACjC,4BACC,yBAAyB"}
1
+ {"version":3,"file":"runCommands.d.ts","names":[],"sources":["../src/runCommands.ts"],"mappings":";;;;cASa,gBACX,SAAS,eACT,eACC,yBAAyB;cAwCf,mBACX,MAAM,yBAAyB;;;UAAA,yBAAA;;;;;;;cAkBpB,uBACX,MAAM,gBAAgB,mBACrB;cA2BU,eACX;EAAqB;;cAGV,qBACX,SAAS,kBACR,yBAAyB;cAUf,wBACX;EAAqB;KACrB,qBAAqB,yBAAyB,gBAC9C,0BAA0B,yBAAyB,4BACnD,WAAW,SAAS,yBAAyB,qBAC7C,eACE,SAAS,yBAAyB,YAClC,SAAS,2BAEV;cAmDU,uBACX;EAAqB;EAAY;KACjC,4BACC,yBAAyB"}
@@ -38,6 +38,19 @@ const toQueueItemState = (item) => ({
38
38
  ...part.filename !== void 0 && { filename: part.filename }
39
39
  })
40
40
  });
41
+ const toDispatchingMessage = (item) => ({
42
+ id: item.id,
43
+ role: "user",
44
+ createdAt: /* @__PURE__ */ new Date(),
45
+ content: item.parts.map((part) => part.type === "text" ? part : {
46
+ type: "file",
47
+ data: part.url,
48
+ mimeType: part.mediaType,
49
+ ...part.filename !== void 0 && { filename: part.filename }
50
+ }),
51
+ attachments: [],
52
+ metadata: { custom: {} }
53
+ });
41
54
  const placementFields = (placement) => ({
42
55
  ...placement.insertAfter !== void 0 && { insertAfter: placement.insertAfter },
43
56
  ...placement.insertBefore !== void 0 && { insertBefore: placement.insertBefore }
@@ -51,7 +64,7 @@ const resolveEditCommand = (message) => {
51
64
  sourceId: message.sourceId
52
65
  };
53
66
  };
54
- const createRunQueueAdapter = (messages, queueItems, steerQueueItems, dispatch) => {
67
+ const createRunQueueAdapter = (messages, queueItems, steerQueueItems, dispatch, dispatchSend) => {
55
68
  const laneOf = (queueItemId) => {
56
69
  if (steerQueueItems?.some((item) => item.id === queueItemId)) return "steer";
57
70
  if (queueItems.some((item) => item.id === queueItemId)) return "queue";
@@ -74,8 +87,8 @@ const createRunQueueAdapter = (messages, queueItems, steerQueueItems, dispatch)
74
87
  return {
75
88
  items: queueItems.map(toQueueItemState),
76
89
  steerItems: (steerQueueItems ?? []).map(toQueueItemState),
77
- enqueue: (message) => dispatch(sendCommand("queue", message)),
78
- steer: (message) => dispatch(sendCommand("steer", message)),
90
+ enqueue: (message) => dispatchSend(sendCommand("queue", message), message),
91
+ steer: (message) => dispatchSend(sendCommand("steer", message), message),
79
92
  move: (queueItemId, placement) => {
80
93
  const lane = placement.lane ?? laneOf(queueItemId);
81
94
  const fields = {
@@ -117,6 +130,6 @@ const resolveReloadCommand = (messages, parentId) => {
117
130
  };
118
131
  };
119
132
  //#endregion
120
- export { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, toQueueItemState, toWireMessage, viewedLeafId };
133
+ export { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, toDispatchingMessage, toQueueItemState, toWireMessage, viewedLeafId };
121
134
 
122
135
  //# sourceMappingURL=runCommands.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"runCommands.js","names":["AppendMessage","ExternalThreadQueueAdapter","QueuePlacement","AssistantTransportThread","toWireMessage","message","id","RunUserMessage","role","Error","files","FilePart","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","undefined","parts","TextPart","length","const","join","toQueueItemState","item","RunQueueItem","prompt","map","placementFields","placement","insertAfter","insertBefore","viewedLeafId","messages","at","resolveEditCommand","RunEditCommand","sourceId","crypto","randomUUID","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","command","RunCommand","laneOf","queueItemId","some","sendCommand","lane","fields","anchorMessageId","items","steerItems","enqueue","steer","move","messageId","edit","wireMessage","remove","resolveReloadCommand","parentId","RunReloadCommand","index","findIndex","target"],"sources":["../src/runCommands.ts"],"sourcesContent":["import type {\n AppendMessage,\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"@assistant-ui/core\";\nimport type { AssistantTransportThread } from \"./AssistantTransportThread\";\n\nexport const toWireMessage = (\n message: AppendMessage,\n id: string,\n): AssistantTransportThread.RunUserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: AssistantTransportThread.FilePart[] = [];\n const texts: string[] = [];\n const source = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const part of source) {\n if (part.type === \"text\") {\n texts.push(part.text);\n } else if (part.type === \"image\") {\n files.push({ type: \"file\", mediaType: \"image/*\", url: part.image });\n } else if (part.type === \"file\") {\n files.push({\n type: \"file\",\n mediaType: part.mimeType,\n url: part.data,\n ...(part.filename !== undefined && { filename: part.filename }),\n });\n } else {\n throw new Error(`statewire: unsupported message part \"${part.type}\"`);\n }\n }\n // default-safe against host capabilities: files first, one merged text part\n const parts: (\n | AssistantTransportThread.TextPart\n | AssistantTransportThread.FilePart\n )[] = [\n ...files,\n ...(texts.length > 0\n ? [{ type: \"text\" as const, text: texts.join(\"\\n\\n\") }]\n : []),\n ];\n if (parts.length === 0)\n throw new Error(\"statewire: cannot send an empty message\");\n return { id, role: \"user\", parts };\n};\n\nexport const toQueueItemState = (\n item: AssistantTransportThread.RunQueueItem,\n) => ({\n id: item.id,\n prompt: item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n parts: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n});\n\nconst placementFields = (placement: QueuePlacement) => ({\n ...(placement.insertAfter !== undefined && {\n insertAfter: placement.insertAfter,\n }),\n ...(placement.insertBefore !== undefined && {\n insertBefore: placement.insertBefore,\n }),\n});\n\nexport const viewedLeafId = (\n messages: readonly { id: string }[],\n): string | null => messages.at(-1)?.id ?? null;\n\nexport const resolveEditCommand = (\n message: AppendMessage,\n): AssistantTransportThread.RunEditCommand => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n return {\n type: \"run/edit\",\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n };\n};\n\nexport const createRunQueueAdapter = (\n messages: readonly { id: string }[],\n queueItems: readonly AssistantTransportThread.RunQueueItem[],\n steerQueueItems: readonly AssistantTransportThread.RunQueueItem[] | undefined,\n dispatch: (command: AssistantTransportThread.RunCommand) => void,\n): ExternalThreadQueueAdapter => {\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems?.some((item) => item.id === queueItemId))\n return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n // edit-composer sends carry a sourceId; they bypass the lanes into run/edit\n const sendCommand = (\n lane: \"queue\" | \"steer\",\n message: AppendMessage,\n ): AssistantTransportThread.RunCommand => {\n if (message.sourceId != null) return resolveEditCommand(message);\n const fields = {\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\n };\n return lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields };\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: (steerQueueItems ?? []).map(toQueueItemState),\n enqueue: (message) => dispatch(sendCommand(\"queue\", message)),\n steer: (message) => dispatch(sendCommand(\"steer\", message)),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\n messageId: queueItemId,\n ...placementFields(placement),\n };\n dispatch(\n lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields },\n );\n },\n edit: (queueItemId, message) => {\n const wireMessage = toWireMessage(message, queueItemId);\n dispatch(\n laneOf(queueItemId) === \"steer\"\n ? { type: \"run/steer\", message: wireMessage }\n : { type: \"run/enqueue\", message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({ type: \"run/dequeue\", messageId: queueItemId }),\n };\n};\n\nexport const resolveReloadCommand = (\n messages: readonly { id: string; role: string }[],\n parentId: string | null,\n): AssistantTransportThread.RunReloadCommand => {\n const index =\n parentId === null\n ? 0\n : messages.findIndex((message) => message.id === parentId) + 1;\n if (parentId !== null && index === 0)\n throw new Error(`statewire: run/reload parent \"${parentId}\" is unknown`);\n const target = messages[index];\n if (target === undefined || target.role !== \"assistant\")\n throw new Error(\n \"statewire: run/reload requires an assistant message to regenerate\",\n );\n return { type: \"run/reload\", sourceId: target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,EAAA,CAAIf,IAAIJ,gBAAgB;EACxDgC,UAAU7D,YAAYiD,SAASM,YAAY,SAASvD,OAAO,CAAC;EAC5D8D,QAAQ9D,YAAYiD,SAASM,YAAY,SAASvD,OAAO,CAAC;EAC1D+D,OAAOV,aAAalB,cAAc;GAChC,MAAMqB,OAAOrB,UAAUqB,QAAQJ,OAAOC,WAAW;GACjD,MAAMI,SAAS;IACbO,WAAWX;IACX,GAAGnB,gBAAgBC,SAAS;GAC9B;GACAc,SACEO,SAAS,UACL;IAAE1C,MAAM;IAAa,GAAG2C;GAAO,IAC/B;IAAE3C,MAAM;IAAe,GAAG2C;GAAO,CACvC;EACF;EACAQ,OAAOZ,aAAarD,YAAY;GAC9B,MAAMkE,cAAcnE,cAAcC,SAASqD,WAAW;GACtDJ,SACEG,OAAOC,WAAW,MAAM,UACpB;IAAEvC,MAAM;IAAad,SAASkE;GAAY,IAC1C;IAAEpD,MAAM;IAAed,SAASkE;GAAY,CAClD;EACF;EACAC,SAASd,gBACPJ,SAAS;GAAEnC,MAAM;GAAekD,WAAWX;EAAY,CAAC;CAC5D;AACF;AAEA,MAAae,wBACX7B,UACA8B,aAC8C;CAC9C,MAAME,QACJF,aAAa,OACT,IACA9B,SAASiC,WAAWxE,YAAYA,QAAQC,OAAOoE,QAAQ,IAAI;CACjE,IAAIA,aAAa,QAAQE,UAAU,GACjC,MAAM,IAAInE,MAAM,iCAAiCiE,SAAQ,aAAc;CACzE,MAAMI,SAASlC,SAASgC;CACxB,IAAIE,WAAWlD,KAAAA,KAAakD,OAAOtE,SAAS,aAC1C,MAAM,IAAIC,MACR,mEACF;CACF,OAAO;EAAEU,MAAM;EAAc6B,UAAU8B,OAAOxE;CAAG;AACnD"}
1
+ {"version":3,"file":"runCommands.js","names":["AppendMessage","ExternalThreadQueueAdapter","QueuePlacement","ThreadMessage","AssistantTransportThread","StatewireThread","toWireMessage","message","id","RunUserMessage","role","Error","files","FilePart","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","undefined","parts","TextPart","length","const","join","toQueueItemState","item","RunQueueItem","prompt","map","toDispatchingMessage","RunsQueueEntry","createdAt","Date","metadata","custom","placementFields","placement","insertAfter","insertBefore","viewedLeafId","messages","at","resolveEditCommand","RunEditCommand","sourceId","crypto","randomUUID","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","command","RunCommand","dispatchSend","laneOf","queueItemId","some","sendCommand","lane","fields","anchorMessageId","items","steerItems","enqueue","steer","move","messageId","edit","wireMessage","remove","resolveReloadCommand","parentId","RunReloadCommand","index","findIndex","target"],"sources":["../src/runCommands.ts"],"sourcesContent":["import type {\n AppendMessage,\n ExternalThreadQueueAdapter,\n QueuePlacement,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport type { AssistantTransportThread } from \"./AssistantTransportThread\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nexport const toWireMessage = (\n message: AppendMessage,\n id: string,\n): AssistantTransportThread.RunUserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: AssistantTransportThread.FilePart[] = [];\n const texts: string[] = [];\n const source = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const part of source) {\n if (part.type === \"text\") {\n texts.push(part.text);\n } else if (part.type === \"image\") {\n files.push({ type: \"file\", mediaType: \"image/*\", url: part.image });\n } else if (part.type === \"file\") {\n files.push({\n type: \"file\",\n mediaType: part.mimeType,\n url: part.data,\n ...(part.filename !== undefined && { filename: part.filename }),\n });\n } else {\n throw new Error(`statewire: unsupported message part \"${part.type}\"`);\n }\n }\n // default-safe against host capabilities: files first, one merged text part\n const parts: (\n | AssistantTransportThread.TextPart\n | AssistantTransportThread.FilePart\n )[] = [\n ...files,\n ...(texts.length > 0\n ? [{ type: \"text\" as const, text: texts.join(\"\\n\\n\") }]\n : []),\n ];\n if (parts.length === 0)\n throw new Error(\"statewire: cannot send an empty message\");\n return { id, role: \"user\", parts };\n};\n\nexport const toQueueItemState = (\n item: AssistantTransportThread.RunQueueItem,\n) => ({\n id: item.id,\n prompt: item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n parts: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n});\n\nexport const toDispatchingMessage = (\n item: StatewireThread.RunsQueueEntry,\n): ThreadMessage => ({\n id: item.id,\n role: \"user\",\n createdAt: new Date(),\n content: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n attachments: [],\n metadata: { custom: {} },\n});\n\nconst placementFields = (placement: QueuePlacement) => ({\n ...(placement.insertAfter !== undefined && {\n insertAfter: placement.insertAfter,\n }),\n ...(placement.insertBefore !== undefined && {\n insertBefore: placement.insertBefore,\n }),\n});\n\nexport const viewedLeafId = (\n messages: readonly { id: string }[],\n): string | null => messages.at(-1)?.id ?? null;\n\nexport const resolveEditCommand = (\n message: AppendMessage,\n): AssistantTransportThread.RunEditCommand => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n return {\n type: \"run/edit\",\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n };\n};\n\nexport const createRunQueueAdapter = (\n messages: readonly { id: string }[],\n queueItems: readonly AssistantTransportThread.RunQueueItem[],\n steerQueueItems: readonly AssistantTransportThread.RunQueueItem[] | undefined,\n dispatch: (command: AssistantTransportThread.RunCommand) => void,\n dispatchSend: (\n command: AssistantTransportThread.RunCommand,\n message: AppendMessage,\n ) => void,\n): ExternalThreadQueueAdapter => {\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems?.some((item) => item.id === queueItemId))\n return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n // edit-composer sends carry a sourceId; they bypass the lanes into run/edit\n const sendCommand = (\n lane: \"queue\" | \"steer\",\n message: AppendMessage,\n ): AssistantTransportThread.RunCommand => {\n if (message.sourceId != null) return resolveEditCommand(message);\n const fields = {\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\n };\n return lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields };\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: (steerQueueItems ?? []).map(toQueueItemState),\n enqueue: (message) => dispatchSend(sendCommand(\"queue\", message), message),\n steer: (message) => dispatchSend(sendCommand(\"steer\", message), message),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\n messageId: queueItemId,\n ...placementFields(placement),\n };\n dispatch(\n lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields },\n );\n },\n edit: (queueItemId, message) => {\n const wireMessage = toWireMessage(message, queueItemId);\n dispatch(\n laneOf(queueItemId) === \"steer\"\n ? { type: \"run/steer\", message: wireMessage }\n : { type: \"run/enqueue\", message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({ type: \"run/dequeue\", messageId: queueItemId }),\n };\n};\n\nexport const resolveReloadCommand = (\n messages: readonly { id: string; role: string }[],\n parentId: string | null,\n): AssistantTransportThread.RunReloadCommand => {\n const index =\n parentId === null\n ? 0\n : messages.findIndex((message) => message.id === parentId) + 1;\n if (parentId !== null && index === 0)\n throw new Error(`statewire: run/reload parent \"${parentId}\" is unknown`);\n const target = messages[index];\n if (target === undefined || target.role !== \"assistant\")\n throw new Error(\n \"statewire: run/reload requires an assistant message to regenerate\",\n );\n return { type: \"run/reload\", sourceId: target.id };\n};\n"],"mappings":";AASA,MAAaM,iBACXC,SACAC,OAC4C;CAC5C,IAAID,QAAQG,SAAS,QACnB,MAAM,IAA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AAA,KAAayD,OAAO7E,SAAS,aAC1C,MAAM,IAAIC,MACR,mEACF;CACF,OAAO;EAAEU,MAAM;EAAcmC,UAAU+B,OAAO/E;CAAG;AACnD"}
@@ -1 +1 @@
1
- {"version":3,"file":"runsOptimistic.d.ts","names":[],"sources":["../src/runsOptimistic.ts"],"mappings":";;;cA6Ga,iBACX,gBACA,SAAS,UAAU,QAAQ,mBAAmB,2BAC9C,KAAK,gBAAgB"}
1
+ {"version":3,"file":"runsOptimistic.d.ts","names":[],"sources":["../src/runsOptimistic.ts"],"mappings":";;;cAiHa,iBACX,gBACA,SAAS,UAAU,QAAQ,mBAAmB,2BAC9C,KAAK,gBAAgB"}
@@ -5,6 +5,7 @@ const startRun = (draft, runId) => {
5
5
  status: "running",
6
6
  queue: [],
7
7
  steerQueue: [],
8
+ dispatching: [],
8
9
  error: null,
9
10
  runLeafMessageId: null
10
11
  };
@@ -21,6 +22,7 @@ const insert = (lane, entry, { insertAfter, insertBefore }) => {
21
22
  const enqueueOrSteer = (draft, command, runId) => {
22
23
  const run = draft.runs[0];
23
24
  const id = "message" in command ? command.message.id : command.messageId;
25
+ if (run?.dispatching.some((e) => e.id === id)) return;
24
26
  const sourceLane = run === void 0 ? void 0 : [run.queue, run.steerQueue].find((l) => l.some((e) => e.id === id));
25
27
  let entry;
26
28
  let sourceIndex = -1;
@@ -1 +1 @@
1
- {"version":3,"file":"runsOptimistic.js","names":["Statewire","StatewireClient","StatewireThread","LaneEntry","id","role","parts","TextPart","FilePart","metadata","Record","meta","RunEntry","runId","status","RunStatus","queue","steerQueue","inputRequests","response","error","runLeafMessageId","RunsDraft","runs","startRun","draft","entry","insert","lane","insertAfter","insertBefore","Placement","index","undefined","findIndex","e","length","splice","enqueueOrSteer","command","RunEnqueueCommand","RunSteerCommand","run","message","messageId","sourceLane","find","l","some","sourceIndex","dispatching","type","hasPlacement","runsOptimistic","mount","Command","args","ctx","OptimisticContext","seq","method","params","RunDequeueCommand","requestId","RunInputCommand","requests","target","r","every"],"sources":["../src/runsOptimistic.ts"],"sourcesContent":["import type { Statewire, StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\ntype LaneEntry = {\n id: string;\n role: \"user\";\n parts: readonly (StatewireThread.TextPart | StatewireThread.FilePart)[];\n metadata?: Record<string, unknown>;\n meta?: unknown;\n};\n\ntype RunEntry = {\n runId: string | null;\n status: StatewireThread.RunStatus;\n queue: LaneEntry[];\n steerQueue: LaneEntry[];\n inputRequests?: { id: string; response: unknown }[];\n error: unknown;\n runLeafMessageId: string | null;\n};\n\ntype RunsDraft = {\n status: StatewireThread.RunStatus;\n runs: RunEntry[];\n};\n\nconst startRun = (draft: RunsDraft, runId: string): void => {\n const entry = (draft.runs[0] ??= {\n runId: null,\n status: \"running\",\n queue: [],\n steerQueue: [],\n error: null,\n runLeafMessageId: null,\n });\n entry.status = \"running\";\n entry.runId = runId;\n entry.error = null;\n delete entry.inputRequests;\n draft.status = \"running\";\n};\n\nconst insert = (\n lane: LaneEntry[],\n entry: LaneEntry,\n { insertAfter, insertBefore }: StatewireThread.Placement,\n): void => {\n const index =\n insertAfter !== undefined\n ? insertAfter === null\n ? 0\n : lane.findIndex((e) => e.id === insertAfter) + 1\n : insertBefore === undefined || insertBefore === null\n ? lane.length\n : lane.findIndex((e) => e.id === insertBefore);\n lane.splice(index < 0 ? lane.length : index, 0, entry);\n};\n\nconst enqueueOrSteer = (\n draft: RunsDraft,\n command: StatewireThread.RunEnqueueCommand | StatewireThread.RunSteerCommand,\n runId: string,\n): void => {\n const run = draft.runs[0];\n const id = \"message\" in command ? command.message.id : command.messageId;\n const sourceLane =\n run === undefined\n ? undefined\n : [run.queue, run.steerQueue].find((l) => l.some((e) => e.id === id));\n\n let entry: LaneEntry;\n let sourceIndex = -1;\n if (sourceLane !== undefined) {\n sourceIndex = sourceLane.findIndex((e) => e.id === id);\n entry = sourceLane.splice(sourceIndex, 1)[0]!;\n if (\"message\" in command) {\n entry.parts = command.message.parts;\n if (command.message.metadata !== undefined)\n entry.metadata = command.message.metadata;\n }\n } else {\n if (!(\"message\" in command)) return;\n entry = { ...command.message };\n }\n\n const dispatching =\n command.type === \"run/steer\"\n ? draft.status !== \"running\"\n : sourceLane === undefined &&\n (draft.status === \"ready\" ||\n ((draft.status === \"stopped\" || draft.status === \"error\") &&\n run !== undefined &&\n run.queue.length === 0 &&\n run.steerQueue.length === 0));\n if (dispatching) {\n if (command.type === \"run/steer\" && run !== undefined) run.steerQueue = [];\n startRun(draft, runId);\n return;\n }\n\n if (run === undefined) return;\n const lane = command.type === \"run/steer\" ? run.steerQueue : run.queue;\n const hasPlacement =\n command.insertAfter !== undefined || command.insertBefore !== undefined;\n if (sourceLane === lane && !hasPlacement) lane.splice(sourceIndex, 0, entry);\n else insert(lane, entry, command);\n};\n\n/** The run dialect's optimistic reducer: folds an unsettled `run/*` command into the mount draft. */\nexport const runsOptimistic = (\n mount: unknown,\n command: Statewire.Command<Record<string, (...args: any[]) => unknown>>,\n ctx: StatewireClient.OptimisticContext,\n): void => {\n const draft = mount as RunsDraft;\n const runId = `optimistic-${ctx.seq}`;\n switch (command.method) {\n case \"run/enqueue\":\n case \"run/steer\": {\n enqueueOrSteer(\n draft,\n command.params[0] as\n | StatewireThread.RunEnqueueCommand\n | StatewireThread.RunSteerCommand,\n runId,\n );\n break;\n }\n case \"run/edit\":\n case \"run/reload\": {\n startRun(draft, runId);\n break;\n }\n case \"run/continue\": {\n const run = draft.runs[0];\n if (run !== undefined) run.steerQueue = [];\n startRun(draft, runId);\n break;\n }\n case \"run/dequeue\": {\n const { messageId } = command\n .params[0] as StatewireThread.RunDequeueCommand;\n const run = draft.runs[0];\n if (run === undefined) break;\n for (const lane of [run.queue, run.steerQueue]) {\n const index = lane.findIndex((e) => e.id === messageId);\n if (index !== -1) lane.splice(index, 1);\n }\n break;\n }\n case \"run/input\": {\n const { requestId, response } = command\n .params[0] as StatewireThread.RunInputCommand;\n const requests = draft.runs[0]?.inputRequests;\n const target = requests?.find((r) => r.id === requestId);\n if (target === undefined) break;\n target.response = response;\n if (requests!.every((r) => r.response !== null)) startRun(draft, runId);\n break;\n }\n default:\n break;\n }\n};\n"],"mappings":";AA0BA,MAAMwB,YAAYC,OAAkBZ,UAAwB;CAC1D,MAAMa,QAASD,MAAMF,KAAK,OAAO;EAC/BV,OAAO;EACPC,QAAQ;EACRE,OAAO,CAAA;EACPC,YAAY,CAAA;EACZG,OAAO;EACPC,kBAAkB;CACpB;CACAK,MAAMZ,SAAS;CACfY,MAAMb,QAAQA;CACda,MAAMN,QAAQ;CACd,OAAOM,MAAMR;CACbO,MAAMX,SAAS;AACjB;AAEA,MAAMa,UACJC,MACAF,OACA,EAAEG,aAAaC,mBACN;CACT,MAAME,QACJH,gBAAgBI,KAAAA,IACZJ,gBAAgB,OACd,IACAD,KAAKM,WAAWC,MAAMA,EAAE/B,OAAOyB,WAAW,IAAI,IAChDC,iBAAiBG,KAAAA,KAAaH,iBAAiB,OAC7CF,KAAKQ,SACLR,KAAKM,WAAWC,MAAMA,EAAE/B,OAAO0B,YAAY;CACnDF,KAAKS,OAAOL,QAAQ,IAAIJ,KAAKQ,SAASJ,OAAO,GAAGN,KAAK;AACvD;AAEA,MAAMY,kBACJb,OACAc,SACA1B,UACS;CACT,MAAM6B,MAAMjB,MAAMF,KAAK;CACvB,MAAMnB,KAAK,aAAamC,UAAUA,QAAQI,QAAQvC,KAAKmC,QAAQK;CAC/D,MAAMC,aACJH,QAAQT,KAAAA,IACJA,KAAAA,IACA,CAACS,IAAI1B,OAAO0B,IAAIzB,UAAU,CAAC,CAAC6B,MAAMC,MAAMA,EAAEC,MAAMb,MAAMA,EAAE/B,OAAOA,EAAE,CAAC;CAExE,IAAIsB;CACJ,IAAIuB,cAAc;CAClB,IAAIJ,eAAeZ,KAAAA,GAAW;EAC5BgB,cAAcJ,WAAWX,WAAWC,MAAMA,EAAE/B,OAAOA,EAAE;EACrDsB,QAAQmB,WAAWR,OAAOY,aAAa,CAAC,CAAC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,IAAIzB,aAAa,CAAA;GACxCO,SAASC,OAAOZ,KAAK;GACrB;EACF;EACA,KAAK,eAAe;GAClB,MAAM,EAAE+B,cAAcL,QACnBsB,OAAO;GACV,MAAMnB,MAAMjB,MAAMF,KAAK;GACvB,IAAImB,QAAQT,KAAAA,GAAW;GACvB,KAAK,MAAML,QAAQ,CAACc,IAAI1B,OAAO0B,IAAIzB,UAAU,GAAG;IAC9C,MAAMe,QAAQJ,KAAKM,WAAWC,MAAMA,EAAE/B,OAAOwC,SAAS;IACtD,IAAIZ,UAAU,IAAIJ,KAAKS,OAAOL,OAAO,CAAC;GACxC;GACA;EACF;EACA,KAAK,aAAa;GAChB,MAAM,EAAE+B,WAAW5C,aAAaoB,QAC7BsB,OAAO;GACV,MAAMI,WAAWxC,MAAMF,KAAK,EAAE,EAAEL;GAChC,MAAMgD,SAASD,UAAUnB,MAAMqB,MAAMA,EAAE/D,OAAO2D,SAAS;GACvD,IAAIG,WAAWjC,KAAAA,GAAW;GAC1BiC,OAAO/C,WAAWA;GAClB,IAAI8C,SAAUG,OAAOD,MAAMA,EAAEhD,aAAa,IAAI,GAAGK,SAASC,OAAOZ,KAAK;GACtE;EACF;CAGF;AACF"}
1
+ {"version":3,"file":"runsOptimistic.js","names":["Statewire","StatewireClient","StatewireThread","LaneEntry","id","role","parts","TextPart","FilePart","metadata","Record","meta","RunEntry","runId","status","RunStatus","queue","steerQueue","dispatching","inputRequests","response","error","runLeafMessageId","RunsDraft","runs","startRun","draft","entry","insert","lane","insertAfter","insertBefore","Placement","index","undefined","findIndex","e","length","splice","enqueueOrSteer","command","RunEnqueueCommand","RunSteerCommand","run","message","messageId","some","sourceLane","find","l","sourceIndex","type","hasPlacement","runsOptimistic","mount","Command","args","ctx","OptimisticContext","seq","method","params","RunDequeueCommand","requestId","RunInputCommand","requests","target","r","every"],"sources":["../src/runsOptimistic.ts"],"sourcesContent":["import type { Statewire, StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\ntype LaneEntry = {\n id: string;\n role: \"user\";\n parts: readonly (StatewireThread.TextPart | StatewireThread.FilePart)[];\n metadata?: Record<string, unknown>;\n meta?: unknown;\n};\n\ntype RunEntry = {\n runId: string | null;\n status: StatewireThread.RunStatus;\n queue: LaneEntry[];\n steerQueue: LaneEntry[];\n dispatching: LaneEntry[];\n inputRequests?: { id: string; response: unknown }[];\n error: unknown;\n runLeafMessageId: string | null;\n};\n\ntype RunsDraft = {\n status: StatewireThread.RunStatus;\n runs: RunEntry[];\n};\n\nconst startRun = (draft: RunsDraft, runId: string): void => {\n const entry = (draft.runs[0] ??= {\n runId: null,\n status: \"running\",\n queue: [],\n steerQueue: [],\n dispatching: [],\n error: null,\n runLeafMessageId: null,\n });\n entry.status = \"running\";\n entry.runId = runId;\n entry.error = null;\n delete entry.inputRequests;\n draft.status = \"running\";\n};\n\nconst insert = (\n lane: LaneEntry[],\n entry: LaneEntry,\n { insertAfter, insertBefore }: StatewireThread.Placement,\n): void => {\n const index =\n insertAfter !== undefined\n ? insertAfter === null\n ? 0\n : lane.findIndex((e) => e.id === insertAfter) + 1\n : insertBefore === undefined || insertBefore === null\n ? lane.length\n : lane.findIndex((e) => e.id === insertBefore);\n lane.splice(index < 0 ? lane.length : index, 0, entry);\n};\n\nconst enqueueOrSteer = (\n draft: RunsDraft,\n command: StatewireThread.RunEnqueueCommand | StatewireThread.RunSteerCommand,\n runId: string,\n): void => {\n const run = draft.runs[0];\n const id = \"message\" in command ? command.message.id : command.messageId;\n // In dispatch limbo the canonical state already tells the story: no fold.\n if (run?.dispatching.some((e) => e.id === id)) return;\n const sourceLane =\n run === undefined\n ? undefined\n : [run.queue, run.steerQueue].find((l) => l.some((e) => e.id === id));\n\n let entry: LaneEntry;\n let sourceIndex = -1;\n if (sourceLane !== undefined) {\n sourceIndex = sourceLane.findIndex((e) => e.id === id);\n entry = sourceLane.splice(sourceIndex, 1)[0]!;\n if (\"message\" in command) {\n entry.parts = command.message.parts;\n if (command.message.metadata !== undefined)\n entry.metadata = command.message.metadata;\n }\n } else {\n if (!(\"message\" in command)) return;\n entry = { ...command.message };\n }\n\n const dispatching =\n command.type === \"run/steer\"\n ? draft.status !== \"running\"\n : sourceLane === undefined &&\n (draft.status === \"ready\" ||\n ((draft.status === \"stopped\" || draft.status === \"error\") &&\n run !== undefined &&\n run.queue.length === 0 &&\n run.steerQueue.length === 0));\n if (dispatching) {\n if (command.type === \"run/steer\" && run !== undefined) run.steerQueue = [];\n startRun(draft, runId);\n return;\n }\n\n if (run === undefined) return;\n const lane = command.type === \"run/steer\" ? run.steerQueue : run.queue;\n const hasPlacement =\n command.insertAfter !== undefined || command.insertBefore !== undefined;\n if (sourceLane === lane && !hasPlacement) lane.splice(sourceIndex, 0, entry);\n else insert(lane, entry, command);\n};\n\n/** The run dialect's optimistic reducer: folds an unsettled `run/*` command into the mount draft. */\nexport const runsOptimistic = (\n mount: unknown,\n command: Statewire.Command<Record<string, (...args: any[]) => unknown>>,\n ctx: StatewireClient.OptimisticContext,\n): void => {\n const draft = mount as RunsDraft;\n const runId = `optimistic-${ctx.seq}`;\n switch (command.method) {\n case \"run/enqueue\":\n case \"run/steer\": {\n enqueueOrSteer(\n draft,\n command.params[0] as\n | StatewireThread.RunEnqueueCommand\n | StatewireThread.RunSteerCommand,\n runId,\n );\n break;\n }\n case \"run/edit\":\n case \"run/reload\": {\n startRun(draft, runId);\n break;\n }\n case \"run/continue\": {\n const run = draft.runs[0];\n if (run !== undefined) run.steerQueue = [];\n startRun(draft, runId);\n break;\n }\n case \"run/dequeue\": {\n const { messageId } = command\n .params[0] as StatewireThread.RunDequeueCommand;\n const run = draft.runs[0];\n if (run === undefined) break;\n for (const lane of [run.queue, run.steerQueue]) {\n const index = lane.findIndex((e) => e.id === messageId);\n if (index !== -1) lane.splice(index, 1);\n }\n break;\n }\n case \"run/input\": {\n const { requestId, response } = command\n .params[0] as StatewireThread.RunInputCommand;\n const requests = draft.runs[0]?.inputRequests;\n const target = requests?.find((r) => r.id === requestId);\n if (target === undefined) break;\n target.response = response;\n if (requests!.every((r) => r.response !== null)) startRun(draft, runId);\n break;\n }\n default:\n break;\n }\n};\n"],"mappings":";AA2BA,MAAMyB,YAAYC,OAAkBb,UAAwB;CAC1D,MAAMc,QAASD,MAAMF,KAAK,OAAO;EAC/BX,OAAO;EACPC,QAAQ;EACRE,OAAO,CAAA;EACPC,YAAY,CAAA;EACZC,aAAa,CAAA;EACbG,OAAO;EACPC,kBAAkB;CACpB;CACAK,MAAMb,SAAS;CACfa,MAAMd,QAAQA;CACdc,MAAMN,QAAQ;CACd,OAAOM,MAAMR;CACbO,MAAMZ,SAAS;AACjB;AAEA,MAAMc,UACJC,MACAF,OACA,EAAEG,aAAaC,mBACN;CACT,MAAME,QACJH,gBAAgBI,KAAAA,IACZJ,gBAAgB,OACd,IACAD,KAAKM,WAAWC,MAAMA,EAAEhC,OAAO0B,WAAW,IAAI,IAChDC,iBAAiBG,KAAAA,KAAaH,iBAAiB,OAC7CF,KAAKQ,SACLR,KAAKM,WAAWC,MAAMA,EAAEhC,OAAO2B,YAAY;CACnDF,KAAKS,OAAOL,QAAQ,IAAIJ,KAAKQ,SAASJ,OAAO,GAAGN,KAAK;AACvD;AAEA,MAAMY,kBACJb,OACAc,SACA3B,UACS;CACT,MAAM8B,MAAMjB,MAAMF,KAAK;CACvB,MAAMpB,KAAK,aAAaoC,UAAUA,QAAQI,QAAQxC,KAAKoC,QAAQK;CAE/D,IAAIF,KAAKzB,YAAY4B,MAAMV,MAAMA,EAAEhC,OAAOA,EAAE,GAAG;CAC/C,MAAM2C,aACJJ,QAAQT,KAAAA,IACJA,KAAAA,IACA,CAACS,IAAI3B,OAAO2B,IAAI1B,UAAU,CAAC,CAAC+B,MAAMC,MAAMA,EAAEH,MAAMV,MAAMA,EAAEhC,OAAOA,EAAE,CAAC;CAExE,IAAIuB;CACJ,IAAIuB,cAAc;CAClB,IAAIH,eAAeb,KAAAA,GAAW;EAC5BgB,cAAcH,WAAWZ,W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AEF,KAAK,gBAAgB;GACnB,MAAM8B,MAAMjB,MAAMF,KAAK;GACvB,IAAImB,QAAQT,KAAAA,GAAWS,IAAI1B,aAAa,CAAA;GACxCQ,SAASC,OAAOb,KAAK;GACrB;EACF;EACA,KAAK,eAAe;GAClB,MAAM,EAAEgC,cAAcL,QACnBqB,OAAO;GACV,MAAMlB,MAAMjB,MAAMF,KAAK;GACvB,IAAImB,QAAQT,KAAAA,GAAW;GACvB,KAAK,MAAML,QAAQ,CAACc,IAAI3B,OAAO2B,IAAI1B,UAAU,GAAG;IAC9C,MAAMgB,QAAQJ,KAAKM,WAAWC,MAAMA,EAAEhC,OAAOyC,SAAS;IACtD,IAAIZ,UAAU,IAAIJ,KAAKS,OAAOL,OAAO,CAAC;GACxC;GACA;EACF;EACA,KAAK,aAAa;GAChB,MAAM,EAAE8B,WAAW3C,aAAaoB,QAC7BqB,OAAO;GACV,MAAMI,WAAWvC,MAAMF,KAAK,EAAE,EAAEL;GAChC,MAAM+C,SAASD,UAAUjB,MAAMmB,MAAMA,EAAE/D,OAAO2D,SAAS;GACvD,IAAIG,WAAWhC,KAAAA,GAAW;GAC1BgC,OAAO9C,WAAWA;GAClB,IAAI6C,SAAUG,OAAOD,MAAMA,EAAE/C,aAAa,IAAI,GAAGK,SAASC,OAAOb,KAAK;GACtE;EACF;CAGF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/react-statewire",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "assistant-ui thread binding for statewire backends",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -331,6 +331,7 @@ const useAssistantTransportThread = (
331
331
  queueProjection,
332
332
  steerProjection,
333
333
  dispatch,
334
+ (command) => dispatch(command),
334
335
  )
335
336
  : undefined,
336
337
  [converted.messages, queueProjection, steerProjection, dispatch],
@@ -24,6 +24,7 @@ type ServerRunEntry = {
24
24
  parts: { type: "text"; text: string }[];
25
25
  }[];
26
26
  steerQueue: ServerRunEntry["queue"];
27
+ dispatching: ServerRunEntry["queue"];
27
28
  error: { message: string } | null;
28
29
  runLeafMessageId: string | null;
29
30
  inputRequests?: {
@@ -55,6 +56,7 @@ const withRun = (
55
56
  runId: null,
56
57
  queue: [],
57
58
  steerQueue: [],
59
+ dispatching: [],
58
60
  error: null,
59
61
  runLeafMessageId: null,
60
62
  ...entry,
@@ -320,6 +322,38 @@ describe("StatewireThread runs mode", () => {
320
322
  );
321
323
  });
322
324
 
325
+ it("projects dispatching items as in-flight messages, deduped by id", async () => {
326
+ const server = createServer({
327
+ messages: [{ id: "m1", role: "user", text: "hi" }],
328
+ ...withRun({
329
+ status: "running",
330
+ runId: "run-1",
331
+ dispatching: [
332
+ { id: "m1", role: "user", parts: [{ type: "text", text: "hi" }] },
333
+ { id: "d1", role: "user", parts: [{ type: "text", text: "go" }] },
334
+ ],
335
+ }),
336
+ });
337
+ const { aui, runs } = mountThread({ transport: server.transport });
338
+
339
+ await waitFor(() => expect(runs().dispatching).toHaveLength(2));
340
+ const messages = aui().thread().getState().messages;
341
+ expect(messages.map((m) => m.id)).toEqual(["m1", "d1"]);
342
+ expect(messages[1]!.role).toBe("user");
343
+
344
+ act(() => {
345
+ server.cell.state!.messages.push({ id: "d1", role: "user", text: "go" });
346
+ server.cell.state!.runs[0]!.dispatching = [];
347
+ });
348
+ await waitFor(() => expect(runs().dispatching).toHaveLength(0));
349
+ expect(
350
+ aui()
351
+ .thread()
352
+ .getState()
353
+ .messages.map((m) => m.id),
354
+ ).toEqual(["m1", "d1"]);
355
+ });
356
+
323
357
  it("folds a pending steer into the lane while running", async () => {
324
358
  const server = createRemoteServer(
325
359
  withRun({ status: "running", runId: "run-1" }),
@@ -79,7 +79,8 @@ const createServer = (init?: {
79
79
  const cell: {
80
80
  state?: ServerState;
81
81
  hold?: boolean;
82
- resolvers?: { resolve: () => void };
82
+ rejectSends?: boolean;
83
+ resolvers?: { resolve: () => void; reject: (error: Error) => void };
83
84
  } = {};
84
85
  const transport = resource(() => {
85
86
  const [state] = useStatewireState<ServerState>(() => ({
@@ -130,9 +131,10 @@ const createServer = (init?: {
130
131
  | StatewireThread.RunSteerCommand,
131
132
  ) => {
132
133
  received.push(command);
134
+ if (cell.rejectSends) throw new StatewireReject("unknown command");
133
135
  if (cell.hold) {
134
- return new Promise<void>((resolve) => {
135
- cell.resolvers = { resolve };
136
+ return new Promise<void>((resolve, reject) => {
137
+ cell.resolvers = { resolve, reject };
136
138
  });
137
139
  }
138
140
  if ("messageId" in command) {
@@ -440,6 +442,86 @@ describe("StatewireThread", () => {
440
442
  await waitFor(() => expect(metas.at(-1)!.pendingCommands).toEqual([]));
441
443
  });
442
444
 
445
+ describe("composer restore on rejected sends", () => {
446
+ it("restores the composer text and surfaces the error when the send is rejected", async () => {
447
+ const server = createServer();
448
+ server.cell.rejectSends = true;
449
+ const errors: Error[] = [];
450
+ const updates: Statewire.CommandUpdate<
451
+ Record<string, (...args: any[]) => unknown>
452
+ >[] = [];
453
+ const { aui } = mountThread({
454
+ transport: server.transport,
455
+ converter,
456
+ onError: (error) => {
457
+ errors.push(error);
458
+ },
459
+ onCommandChange: (update) => {
460
+ updates.push(update);
461
+ },
462
+ });
463
+ await waitFor(() =>
464
+ expect(aui().thread().getState().isLoading).toBe(false),
465
+ );
466
+
467
+ aui().thread().composer().setText("hello");
468
+ aui().thread().composer().send();
469
+ expect(aui().thread().composer().getState().text).toBe("");
470
+
471
+ await waitFor(() => expect(errors).toHaveLength(1));
472
+ expect(errors[0]!.message).toContain("unknown command");
473
+ expect(updates.at(-1)).toMatchObject({
474
+ status: "settled",
475
+ failure: { fate: "rejected" },
476
+ });
477
+ await waitFor(() =>
478
+ expect(aui().thread().composer().getState().text).toBe("hello"),
479
+ );
480
+ });
481
+
482
+ it("keeps the composer cleared when the send is accepted", async () => {
483
+ const server = createServer();
484
+ const { aui } = mountThread({ transport: server.transport, converter });
485
+ await waitFor(() =>
486
+ expect(aui().thread().getState().isLoading).toBe(false),
487
+ );
488
+
489
+ aui().thread().composer().setText("hello");
490
+ aui().thread().composer().send();
491
+
492
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["hello"]));
493
+ await new Promise((r) => setTimeout(r, 20));
494
+ expect(aui().thread().composer().getState().text).toBe("");
495
+ });
496
+
497
+ it("does not clobber text typed after the send", async () => {
498
+ const server = createServer();
499
+ server.cell.hold = true;
500
+ const errors: Error[] = [];
501
+ const { aui } = mountThread({
502
+ transport: server.transport,
503
+ converter,
504
+ onError: (error) => {
505
+ errors.push(error);
506
+ },
507
+ });
508
+ await waitFor(() =>
509
+ expect(aui().thread().getState().isLoading).toBe(false),
510
+ );
511
+
512
+ aui().thread().composer().setText("hello");
513
+ aui().thread().composer().send();
514
+ await waitFor(() => expect(server.received).toHaveLength(1));
515
+ aui().thread().composer().setText("new draft");
516
+
517
+ server.cell.resolvers!.reject(new StatewireReject("unknown command"));
518
+
519
+ await waitFor(() => expect(errors).toHaveLength(1));
520
+ await new Promise((r) => setTimeout(r, 20));
521
+ expect(aui().thread().composer().getState().text).toBe("new draft");
522
+ });
523
+ });
524
+
443
525
  describe("onStateChange / onConnectionChange", () => {
444
526
  it("fires onStateChange with the attach snapshot, then once per state change", async () => {
445
527
  const server = createServer({
@@ -655,6 +737,31 @@ describe("StatewireThread", () => {
655
737
  );
656
738
  });
657
739
 
740
+ it("restores the composer text when a queue-lane send is rejected", async () => {
741
+ const server = createServer();
742
+ server.cell.rejectSends = true;
743
+ const errors: Error[] = [];
744
+ const { aui } = mountThread({
745
+ transport: server.transport,
746
+ converter: queueConverter,
747
+ onError: (error) => {
748
+ errors.push(error);
749
+ },
750
+ });
751
+ await waitFor(() =>
752
+ expect(aui().thread().getState().capabilities.queue).toBe(true),
753
+ );
754
+
755
+ aui().thread().composer().setText("hello");
756
+ aui().thread().composer().send();
757
+ expect(aui().thread().composer().getState().text).toBe("");
758
+
759
+ await waitFor(() => expect(errors).toHaveLength(1));
760
+ await waitFor(() =>
761
+ expect(aui().thread().composer().getState().text).toBe("hello"),
762
+ );
763
+ });
764
+
658
765
  it("steers by default when the composer sends mid-run", async () => {
659
766
  const server = createServer();
660
767
  const { aui } = mountThread({
@@ -32,6 +32,7 @@ import {
32
32
  createRunQueueAdapter,
33
33
  resolveEditCommand,
34
34
  resolveReloadCommand,
35
+ toDispatchingMessage,
35
36
  toWireMessage,
36
37
  viewedLeafId,
37
38
  } from "./runCommands";
@@ -52,6 +53,7 @@ const READY_RUNS: StatewireThread.Runs = {
52
53
  runId: null,
53
54
  queue: [],
54
55
  steerQueue: [],
56
+ dispatching: [],
55
57
  error: null,
56
58
  runLeafMessageId: null,
57
59
  };
@@ -151,14 +153,35 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
151
153
  const dispatch = useCallback(
152
154
  (command: StatewireThread.Command) => {
153
155
  setPending((prev) => [...prev, command]);
154
- void commands[command.type]!(command).catch((error: Error) => {
156
+ const settled = commands[command.type]!(command);
157
+ settled.catch((error: Error) => {
155
158
  retire(command);
156
159
  latest.current.onError?.(error);
157
160
  });
161
+ return settled;
158
162
  },
159
163
  [commands, retire],
160
164
  );
161
165
 
166
+ const threadRef = useRef<ClientOutput<"thread"> | null>(null);
167
+ const dispatchSend = useCallback(
168
+ (command: StatewireThread.Command, message: AppendMessage) => {
169
+ if (message.sourceId != null) return void dispatch(command);
170
+ const text = message.content
171
+ .flatMap((part) => (part.type === "text" ? [part.text] : []))
172
+ .join("\n\n");
173
+ void dispatch(command).catch(() => {
174
+ // Rejected send: put the text back unless the user typed since.
175
+ // ExternalThread's setText is live-ref-backed and takes an updater.
176
+ const setText = threadRef.current!.composer().setText as (
177
+ next: string | ((prev: string) => string),
178
+ ) => void;
179
+ setText((prev) => (prev === "" ? text : prev));
180
+ });
181
+ },
182
+ [dispatch],
183
+ );
184
+
162
185
  const runs = useMemo((): StatewireThread.Runs | undefined => {
163
186
  if (runsOption === undefined) return undefined;
164
187
  const mount = (runsOption === true ? state : runsOption(state)) as
@@ -172,6 +195,7 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
172
195
  runId: entry.runId,
173
196
  queue: entry.queue,
174
197
  steerQueue: entry.steerQueue,
198
+ dispatching: entry.dispatching,
175
199
  ...(entry.inputRequests !== undefined && {
176
200
  inputRequests: entry.inputRequests,
177
201
  }),
@@ -200,6 +224,13 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
200
224
  ) as StatewireThread.State,
201
225
  [converter, state, metadata],
202
226
  );
227
+ // Dispatch limbo renders as in-flight messages; ids already converted win.
228
+ const messages = useMemo((): StatewireThread.State["messages"] => {
229
+ const known = new Set(converted.messages.map((m) => m.id));
230
+ const pending = (runs?.dispatching ?? []).filter((e) => !known.has(e.id));
231
+ if (pending.length === 0) return converted.messages;
232
+ return [...converted.messages, ...pending.map(toDispatchingMessage)];
233
+ }, [converted.messages, runs]);
203
234
  const queueItems = runs !== undefined ? runs.queue : converted.queue;
204
235
  const steerQueueItems =
205
236
  runs !== undefined ? runs.steerQueue : converted.steerQueue;
@@ -221,13 +252,14 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
221
252
  (): ExternalThreadQueueAdapter | undefined =>
222
253
  queueItems
223
254
  ? createRunQueueAdapter(
224
- converted.messages,
255
+ messages,
225
256
  queueItems,
226
257
  steerQueueItems,
227
258
  dispatch,
259
+ dispatchSend,
228
260
  )
229
261
  : undefined,
230
- [converted.messages, queueItems, steerQueueItems, dispatch],
262
+ [messages, queueItems, steerQueueItems, dispatch, dispatchSend],
231
263
  );
232
264
 
233
265
  const inputRequests =
@@ -255,28 +287,29 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
255
287
  );
256
288
 
257
289
  const handleAppend = (message: AppendMessage) => {
258
- dispatch(
290
+ dispatchSend(
259
291
  message.sourceId != null
260
292
  ? resolveEditCommand(message)
261
293
  : {
262
294
  type: "run/steer",
263
295
  message: toWireMessage(message, crypto.randomUUID()),
264
- anchorMessageId: viewedLeafId(converted.messages),
296
+ anchorMessageId: viewedLeafId(messages),
265
297
  },
298
+ message,
266
299
  );
267
300
  };
268
301
 
269
302
  const handleReload = (parentId: string | null) => {
270
- dispatch(resolveReloadCommand(converted.messages, parentId));
303
+ dispatch(resolveReloadCommand(messages, parentId));
271
304
  };
272
305
 
273
306
  const handleEdit = (message: AppendMessage) => {
274
307
  dispatch(resolveEditCommand(message));
275
308
  };
276
309
 
277
- return useResource(
310
+ const thread = useResource(
278
311
  ExternalThread({
279
- messages: converted.messages as readonly ExternalThreadMessage[],
312
+ messages: messages as readonly ExternalThreadMessage[],
280
313
  isRunning:
281
314
  runs !== undefined ? runs.status === "running" : converted.isRunning,
282
315
  isLoading: !attached,
@@ -320,6 +353,8 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
320
353
  },
321
354
  }),
322
355
  );
356
+ threadRef.current = thread;
357
+ return thread;
323
358
  };
324
359
 
325
360
  export const StatewireThread: {
@@ -522,6 +557,8 @@ export namespace StatewireThread {
522
557
  readonly status: Exclude<RunStatus, "ready">;
523
558
  readonly queue: readonly RunsQueueEntry[];
524
559
  readonly steerQueue: readonly RunsQueueEntry[];
560
+ /** The current dispatch's unacked messages — handed to the run, cleared at the messages-ack. */
561
+ readonly dispatching: readonly RunsQueueEntry[];
525
562
  /** The parked pending set; present only in input-required. */
526
563
  readonly inputRequests?: readonly InputRequestState[];
527
564
  readonly error: RunsError | null;
@@ -543,6 +580,8 @@ export namespace StatewireThread {
543
580
  readonly runId: string | null;
544
581
  readonly queue: readonly RunsQueueEntry[];
545
582
  readonly steerQueue: readonly RunsQueueEntry[];
583
+ /** The current dispatch's unacked messages — handed to the run, cleared at the messages-ack. */
584
+ readonly dispatching: readonly RunsQueueEntry[];
546
585
  /** The parked pending set; present only in input-required. */
547
586
  readonly inputRequests?: readonly InputRequestState[];
548
587
  readonly error: RunsError | null;
@@ -2,8 +2,10 @@ import type {
2
2
  AppendMessage,
3
3
  ExternalThreadQueueAdapter,
4
4
  QueuePlacement,
5
+ ThreadMessage,
5
6
  } from "@assistant-ui/core";
6
7
  import type { AssistantTransportThread } from "./AssistantTransportThread";
8
+ import type { StatewireThread } from "./StatewireThread";
7
9
 
8
10
  export const toWireMessage = (
9
11
  message: AppendMessage,
@@ -67,6 +69,26 @@ export const toQueueItemState = (
67
69
  ),
68
70
  });
69
71
 
72
+ export const toDispatchingMessage = (
73
+ item: StatewireThread.RunsQueueEntry,
74
+ ): ThreadMessage => ({
75
+ id: item.id,
76
+ role: "user",
77
+ createdAt: new Date(),
78
+ content: item.parts.map((part) =>
79
+ part.type === "text"
80
+ ? part
81
+ : {
82
+ type: "file" as const,
83
+ data: part.url,
84
+ mimeType: part.mediaType,
85
+ ...(part.filename !== undefined && { filename: part.filename }),
86
+ },
87
+ ),
88
+ attachments: [],
89
+ metadata: { custom: {} },
90
+ });
91
+
70
92
  const placementFields = (placement: QueuePlacement) => ({
71
93
  ...(placement.insertAfter !== undefined && {
72
94
  insertAfter: placement.insertAfter,
@@ -97,6 +119,10 @@ export const createRunQueueAdapter = (
97
119
  queueItems: readonly AssistantTransportThread.RunQueueItem[],
98
120
  steerQueueItems: readonly AssistantTransportThread.RunQueueItem[] | undefined,
99
121
  dispatch: (command: AssistantTransportThread.RunCommand) => void,
122
+ dispatchSend: (
123
+ command: AssistantTransportThread.RunCommand,
124
+ message: AppendMessage,
125
+ ) => void,
100
126
  ): ExternalThreadQueueAdapter => {
101
127
  const laneOf = (queueItemId: string): "queue" | "steer" => {
102
128
  if (steerQueueItems?.some((item) => item.id === queueItemId))
@@ -121,8 +147,8 @@ export const createRunQueueAdapter = (
121
147
  return {
122
148
  items: queueItems.map(toQueueItemState),
123
149
  steerItems: (steerQueueItems ?? []).map(toQueueItemState),
124
- enqueue: (message) => dispatch(sendCommand("queue", message)),
125
- steer: (message) => dispatch(sendCommand("steer", message)),
150
+ enqueue: (message) => dispatchSend(sendCommand("queue", message), message),
151
+ steer: (message) => dispatchSend(sendCommand("steer", message), message),
126
152
  move: (queueItemId, placement) => {
127
153
  const lane = placement.lane ?? laneOf(queueItemId);
128
154
  const fields = {
@@ -18,6 +18,7 @@ const mount = (entry?: Draft): Draft =>
18
18
  runId: null,
19
19
  queue: [],
20
20
  steerQueue: [],
21
+ dispatching: [],
21
22
  error: null,
22
23
  runLeafMessageId: null,
23
24
  ...entry,
@@ -108,6 +109,23 @@ describe("runsOptimistic", () => {
108
109
  expect(run(draft).queue.map((e: Draft) => e.id)).toEqual(["a", "x", "b"]);
109
110
  });
110
111
 
112
+ it("skips the fold for a message in dispatch limbo", () => {
113
+ const draft = mount({
114
+ status: "running",
115
+ runId: "r",
116
+ dispatching: [message("d1")],
117
+ });
118
+ apply(draft, "run/enqueue", {
119
+ type: "run/enqueue",
120
+ message: message("d1"),
121
+ anchorMessageId: null,
122
+ });
123
+ apply(draft, "run/steer", { type: "run/steer", messageId: "d1" });
124
+ expect(run(draft).queue).toEqual([]);
125
+ expect(run(draft).steerQueue).toEqual([]);
126
+ expect(run(draft).dispatching.map((e: Draft) => e.id)).toEqual(["d1"]);
127
+ });
128
+
111
129
  it("applies moves, edits of queued items, and dequeue", () => {
112
130
  const draft = mount({
113
131
  status: "running",
@@ -165,6 +183,7 @@ describe("runsOptimistic", () => {
165
183
  status: "running",
166
184
  queue: [],
167
185
  steerQueue: [],
186
+ dispatching: [],
168
187
  error: null,
169
188
  runLeafMessageId: null,
170
189
  });
@@ -14,6 +14,7 @@ type RunEntry = {
14
14
  status: StatewireThread.RunStatus;
15
15
  queue: LaneEntry[];
16
16
  steerQueue: LaneEntry[];
17
+ dispatching: LaneEntry[];
17
18
  inputRequests?: { id: string; response: unknown }[];
18
19
  error: unknown;
19
20
  runLeafMessageId: string | null;
@@ -30,6 +31,7 @@ const startRun = (draft: RunsDraft, runId: string): void => {
30
31
  status: "running",
31
32
  queue: [],
32
33
  steerQueue: [],
34
+ dispatching: [],
33
35
  error: null,
34
36
  runLeafMessageId: null,
35
37
  });
@@ -63,6 +65,8 @@ const enqueueOrSteer = (
63
65
  ): void => {
64
66
  const run = draft.runs[0];
65
67
  const id = "message" in command ? command.message.id : command.messageId;
68
+ // In dispatch limbo the canonical state already tells the story: no fold.
69
+ if (run?.dispatching.some((e) => e.id === id)) return;
66
70
  const sourceLane =
67
71
  run === undefined
68
72
  ? undefined