@assistant-ui/react-statewire 0.26.0 → 0.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cAgDa;cAEA,oBAAqB,oBAAkB,gBAAgB;cA2cvD,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C,UAAU,KAAK,gBAAgB,UAAU;;cAGzC;aACD;aACA,sBAAsB;;;cAIrB;IACV,QAAQ;IACR,MAAM,OAAO;IACb;;cAGU;KACT;;IAED,cAAc,SAAS,YAAY;IACnC;IACA;IACA,QAAQ;;IAER;IACA,wBAAwB;IACxB,MAAM;;IAEN,cAAc;;IAEd,gBAAgB;;IAEhB,YAAY;;cAGF;aACD;aACA;;cAGC;aACD;aACA;aACA;aACA;;cAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;cAIV;aACD;aACA;;OAGN,eAAe;aACT,MAAM;;aAEN;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU,oBAAoB;cAEpB,kBAAkB;cAElB;aACD;aACA;aACA;;cAGC;aACD;;aAEA;aACA,SAAS;aACT;;aAEA;;cAGC;aACD;aACA;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;cACC,cAAc;;;cAId,eACR,uBACA,2BACA;cAEQ,gBAAgB;cAEhB;aACD;aACA;aACA;aACA,UAAU;;;cAIT,oBAAoB;aACrB,WAAW;;aAEX,OAAO;;;cAIN;aACD;aACA;;cAGC;aACD;aACA;;cAGC;aACD;;aAEA;aACA;;aAEA;;cAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;cAEQ,UAAU,aAAa;;cAGvB;aACD;aACA,iBAAiB,WAAW;;;cAI3B;;cAGA,kEAKR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C5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB;MAC1B,qBAAqB,gBAAgB"}
1
+ {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cAgDa;cAEA,oBAAqB,oBAAkB,gBAAgB;cAkdvD,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C,UAAU,KAAK,gBAAgB,UAAU;;cAGzC;aACD;aACA,sBAAsB;;;cAIrB;IACV,QAAQ;IACR,MAAM,OAAO;IACb;;cAGU;KACT;;IAED,cAAc,SAAS,YAAY;IACnC;IACA;IACA,QAAQ;;IAER;IACA,wBAAwB;IACxB,MAAM;;IAEN,cAAc;;IAEd,gBAAgB;;IAEhB,YAAY;;cAGF;aACD;aACA;;cAGC;aACD;aACA;aACA;aACA;;cAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;cAIV;aACD;aACA;;OAGN,eAAe;aACT,MAAM;;aAEN;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU,oBAAoB;cAEpB,kBAAkB;cAElB;aACD;aACA;aACA;;cAGC;aACD;;aAEA;aACA,SAAS;aACT;;aAEA;;cAGC;aACD;aACA;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;cACC,cAAc;;;cAId,eACR,uBACA,2BACA;cAEQ,gBAAgB;cAEhB;aACD;aACA;aACA;aACA,UAAU;;;cAIT,oBAAoB;aACrB,WAAW;;aAEX,OAAO;;;cAIN;aACD;aACA;;cAGC;aACD;aACA;;cAGC;aACD;;aAEA;aACA;;aAEA;;cAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;cAEQ,UAAU,aAAa;;cAGvB;aACD;aACA,iBAAiB,WAAW;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;MACR,YAAY,gBAAgB;MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB;MAC1B,qBAAqB,gBAAgB"}
@@ -61,8 +61,12 @@ const useStatewireThread = (options) => {
61
61
  return state_0.messages?.some((m) => m.id === command_1.message.id) ?? false;
62
62
  }
63
63
  });
64
+ const discarded = useRef(/* @__PURE__ */ new WeakSet());
64
65
  useEffect(() => {
65
- for (const entry_0 of failed) if (failedRunCommand(entry_0) === void 0) discardFailed(entry_0);
66
+ for (const entry_0 of failed) if (failedRunCommand(entry_0) === void 0 && !discarded.current.has(entry_0)) {
67
+ discarded.current.add(entry_0);
68
+ discardFailed(entry_0);
69
+ }
66
70
  }, [failed, discardFailed]);
67
71
  const clientRef = useAssistantClientRef();
68
72
  const setContextRef = useRef(setContext);
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","useResources","withKey","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","CompleteAttachment","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","createBranchCommandAdapter","createRunQueueAdapter","resolveEditCommand","retryCommand","resolveReloadCommand","sendFields","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","symbolStatewireExtras","Symbol","asStatewireExtras","extras","StatewireThread","Extras","Error","NO_INPUT_REQUESTS","InputRequestState","RESTING_RUNS","Runs","runId","queue","steerQueue","failed","failedRunCommand","entry","FailedCommand","RunEnqueueCommand","RunSteerCommand","RunEditCommand","message","UserMessage","command","undefined","params","ReturnType","presentStatus","status","ThreadStatus","connection","ConnectionState","reason","cause","code","ambientContextOf","context","system","tools","callSettings","config","useStatewireThread","options","Options","latest","current","pending","setPending","Command","retire","prev","includes","filter","c","state","commands","setContext","isBusy","discardFailed","transport","onError","error","storage","initialState","optimistic","draft","ctx","materialize","onCommandChange","update","onStateChange","onConnectionChange","failureCovered","messages","id","some","m","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","subscribe","dispatch","settled","type","catch","threadRef","dispatchSend","sourceId","text","content","flatMap","part","join","setText","composer","next","runs","entries","RunState","failedEntries","failure","RunsFailedEntry","sendFailure","length","epoch","dispatching","stopping","nextDispatch","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","converted","State","liveRunId","branches","takeFailed","messageId","find","f","sendCommand","reconnect","retryFailed","popFailed","parts","p","handleAppend","crypto","randomUUID","handleReload","parentId","handleEdit","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","unstable_switchBranch","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","composerStorage","read","getState","isEmpty","attachment","addAttachment","name","contentType","draftText","composerAttachments","draftAttachments","map","file","_file","record","draftSync","writingFor","isBaseline","clear","write","T","UserCommands","Commands","Transport","ComposerDraft","ComposerStorage","Promise","TextPart","FilePart","mediaType","url","filename","role","Placement","insertAfter","insertBefore","RunSendCommand","TType","runAnchorMessageId","RunDequeueCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","BranchMetadata","siblings","SwitchBranchCommand","branchId","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","RunsQueueEntry","SendFailure","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","RunsError","MaterializeEffects","append","rollback","to","RunsState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","session","SessionStorage","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","messageSwitchBranch","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n resource,\n useResource,\n useResources,\n withKey,\n} from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/core/store\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/core/store\";\nimport type { Assistant } from \"@assistant-ui/core\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n CompleteAttachment,\n FeedbackAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n SpeechSynthesisAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport {\n createBranchCommandAdapter,\n createRunQueueAdapter,\n resolveEditCommand,\n retryCommand,\n resolveReloadCommand,\n sendFields,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nexport const symbolStatewireExtras = Symbol(\"statewire-extras\");\n\nexport const asStatewireExtras = (extras: unknown): StatewireThread.Extras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolStatewireExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using StatewireThread\",\n );\n\n return extras as StatewireThread.Extras;\n};\n\nconst NO_INPUT_REQUESTS: readonly StatewireThread.InputRequestState[] = [];\n\nconst RESTING_RUNS: StatewireThread.Runs = {\n runId: null,\n queue: [],\n steerQueue: [],\n failed: [],\n};\n\n/** The failed run sends the thread can project: enqueue/steer/edit invocations carrying a message. */\nconst failedRunCommand = (\n entry: StatewireClient.FailedCommand,\n):\n | ((\n | StatewireThread.RunEnqueueCommand\n | StatewireThread.RunSteerCommand\n | StatewireThread.RunEditCommand\n ) & { message: StatewireThread.UserMessage })\n | undefined => {\n if (\n entry.command !== \"run/enqueue\" &&\n entry.command !== \"run/steer\" &&\n entry.command !== \"run/edit\"\n )\n return undefined;\n const command = entry.params[0] as\n | { message?: StatewireThread.UserMessage }\n | undefined;\n if (command?.message === undefined) return undefined;\n return command as ReturnType<typeof failedRunCommand>;\n};\n\n// Derived presentation while the connection can't vouch for progress:\n// live-claiming \"running\" reads as evicted/disconnected; facts pass through.\nconst presentStatus = (\n status: StatewireThread.ThreadStatus,\n connection: StatewireClient.ConnectionState,\n): StatewireThread.ThreadStatus =>\n status !== \"running\" ||\n connection.status === \"connected\" ||\n (connection.status === \"disconnected\" && connection.reason === \"idle\")\n ? status\n : connection.status === \"connecting\" &&\n connection.cause === \"reconnect\" &&\n connection.code === \"evicted\"\n ? \"evicted\"\n : \"disconnected\";\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const {\n state,\n commands,\n connection,\n setContext,\n isBusy,\n failed,\n discardFailed,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n onError: (error) => latest.current.onError?.(error),\n storage: options.storage,\n initialState: options.initialState,\n optimistic: (draft, command, ctx) => {\n runsOptimistic(draft, command, ctx);\n latest.current.optimistic?.(draft, command, ctx);\n },\n materialize: (draft: {}) => latest.current.materialize?.(draft),\n onCommandChange: (update, ctx) => {\n if (update.status === \"applied\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n failureCovered: (state, entry) => {\n const command = failedRunCommand(entry);\n if (command === undefined) return false;\n const messages = (state as { messages?: readonly { id: string }[] })\n .messages;\n return messages?.some((m) => m.id === command.message.id) ?? false;\n },\n });\n\n // Failures the thread cannot project stay onError-only, as before the lane.\n useEffect(() => {\n for (const entry of failed) {\n if (failedRunCommand(entry) === undefined) discardFailed(entry);\n }\n }, [failed, discardFailed]);\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n setContextRef.current(value);\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n const { status, runs } = useMemo((): {\n status: StatewireThread.ThreadStatus;\n runs: StatewireThread.Runs;\n } => {\n const entries = (\n state as { runs?: readonly StatewireThread.RunState[] } | undefined\n )?.runs;\n const entry = entries?.[0];\n const failedEntries = failed.flatMap(\n (failure): StatewireThread.RunsFailedEntry[] => {\n const command = failedRunCommand(failure);\n return command === undefined\n ? []\n : [{ ...command.message, sendFailure: failure.failure }];\n },\n );\n return {\n status: presentStatus(\n entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n connection,\n ),\n runs:\n entry === undefined && failedEntries.length === 0\n ? RESTING_RUNS\n : {\n ...(entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n ...(entry.epoch !== undefined && { epoch: entry.epoch }),\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && {\n stopping: entry.stopping,\n }),\n ...(entry.nextDispatch !== undefined && {\n nextDispatch: entry.nextDispatch,\n }),\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n ...(entry.error !== undefined && { error: entry.error }),\n }),\n failed: failedEntries,\n },\n };\n }, [state, connection, failed]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n runs,\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n (): StatewireThread.State => converter(state, metadata),\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const liveRunId = runs.runId;\n\n const queue = useMemo(\n () =>\n createRunQueueAdapter(\n messages,\n liveRunId,\n runs.queue,\n runs.steerQueue,\n dispatch,\n dispatchSend,\n ),\n [messages, liveRunId, runs, dispatch, dispatchSend],\n );\n\n const branches = useMemo(\n () => createBranchCommandAdapter(messages, dispatch),\n [messages, dispatch],\n );\n\n const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo((): StatewireThread.Extras => {\n const takeFailed = (messageId: string): StatewireClient.FailedCommand => {\n const entry = failed.find(\n (f) => failedRunCommand(f)?.message.id === messageId,\n );\n if (entry === undefined)\n throw new Error(`statewire: unknown failed entry \"${messageId}\"`);\n return entry;\n };\n return {\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n retryFailed: (messageId) => {\n const entry = takeFailed(messageId);\n const command = retryCommand(\n messages,\n liveRunId,\n failedRunCommand(entry)!,\n );\n discardFailed(entry);\n void dispatch(command);\n },\n discardFailed: (messageId) => discardFailed(takeFailed(messageId)),\n popFailed: (messageId) => {\n const entry = takeFailed(messageId);\n discardFailed(entry);\n return failedRunCommand(entry)!\n .message.parts.flatMap((p) => (p.type === \"text\" ? [p.text] : []))\n .join(\"\\n\\n\");\n },\n };\n }, [\n dispatch,\n connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n failed,\n discardFailed,\n messages,\n liveRunId,\n ]);\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message, liveRunId)\n : {\n type: \"run/steer\",\n ...sendFields(\n messages,\n liveRunId,\n toWireMessage(message, crypto.randomUUID()),\n ),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId, liveRunId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message, liveRunId));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning: status === \"running\",\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\n onNew: handleAppend,\n queue,\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () =>\n dispatch({\n type: \"run/continue\",\n ...(liveRunId !== null && { runId: liveRunId }),\n }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(options.capabilities?.unstable_switchBranch && { branches }),\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n void commands[\"run/stop\"]!({\n ...payload,\n runId: runs.runId,\n ...(runs.epoch !== undefined && { epoch: runs.epoch }),\n }).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n\n const composerStorage = useResources(\n options.storage?.composer !== undefined\n ? [withKey(\"composer\", options.storage.composer)]\n : [],\n )[0];\n\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n const composer = threadRef.current!.composer();\n const draft = storage.read();\n if (draft === undefined || !composer.getState().isEmpty) return;\n composer.setText(draft.text);\n for (const attachment of draft.attachments) {\n composer\n .addAttachment({\n id: attachment.id,\n type: attachment.type,\n name: attachment.name,\n ...(attachment.contentType !== undefined && {\n contentType: attachment.contentType,\n }),\n content: attachment.content,\n })\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n }\n }, [composerStorage]);\n\n const { text: draftText, attachments: composerAttachments } =\n thread.getState().composer;\n const draftAttachments = useMemo(\n () =>\n composerAttachments\n .filter(\n (attachment): attachment is CompleteAttachment =>\n attachment.status.type === \"complete\",\n )\n .map(({ file: _file, ...record }) => record),\n [composerAttachments],\n );\n const [draftSync] = useState(() => ({ writingFor: undefined as unknown }));\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n // First run per storage is the baseline, not a change: never clear the\n // stored draft the restore effect is about to load.\n const isBaseline = draftSync.writingFor !== storage;\n draftSync.writingFor = storage;\n if (draftText === \"\" && draftAttachments.length === 0) {\n if (!isBaseline) storage.clear();\n return;\n }\n storage.write({ text: draftText, attachments: draftAttachments });\n }, [draftSync, composerStorage, draftText, draftAttachments]);\n\n return thread;\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\n\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n /** A composer draft as persisted: the text plus the completed attachments. */\n export type ComposerDraft = {\n readonly text: string;\n readonly attachments: readonly CompleteAttachment[];\n };\n\n /** Composer draft storage seam; `write` must persist synchronously in the caller's flow. */\n export type ComposerStorage = {\n read(): ComposerDraft | undefined;\n write(draft: ComposerDraft): void;\n clear(): void;\n };\n\n export type Extras = {\n [symbolStatewireExtras]: true;\n /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */\n sendCommand: (command: Command) => Promise<unknown>;\n reconnect: () => void;\n state: unknown;\n status: ThreadStatus;\n /** Negation of the server's broadcast idle level (a transport without idle is always busy). */\n isBusy: boolean;\n inputRequests: readonly InputRequestState[];\n runs: Runs;\n /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */\n retryFailed: (messageId: string) => void;\n /** Removes the failed entry; keyed by the entry's message id. */\n discardFailed: (messageId: string) => void;\n /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */\n popFailed: (messageId: string) => string;\n };\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n type RunSendCommand<TType extends \"run/enqueue\" | \"run/steer\"> = {\n readonly type: TType;\n /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: UserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunEnqueueCommand = RunSendCommand<\"run/enqueue\">;\n\n export type RunSteerCommand = RunSendCommand<\"run/steer\">;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly runId: string;\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n readonly runId?: string;\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly runId?: string;\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state; a present `response` key marks the entry answered. */\n export type InputRequestState = InputRequest & {\n readonly response?: InputResponse;\n /** The answer's `run/input` meta; absent when the answer carried none. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** Per-message branch metadata read from `metadata.custom.branch`: the message's own branch id and the fan-out's branch ids in creation order (own id included). */\n export type BranchMetadata = {\n readonly id: number;\n readonly siblings: readonly number[];\n };\n\n export type SwitchBranchCommand = {\n readonly type: \"message/switch-branch\";\n readonly branchId: number;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus = \"running\" | \"stopped\" | \"error\" | \"input-required\";\n\n /** The thread's status: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status; `\"evicted\"` and `\"disconnected\"` are client-derived from the connection, never replicated. */\n export type ThreadStatus =\n | \"loading\"\n | \"ready\"\n | \"evicted\"\n | \"disconnected\"\n | RunStatus;\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */\n export type RunsFailedEntry = RunsQueueEntry & {\n readonly sendFailure: StatewireClient.SendFailure;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** The run-starting op's meta; present only when carried. */\n readonly rootMeta?: ReadonlyJSONValue;\n /** Present when input outcomes ride the dispatch; visible until applied. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The stopping window: present while a stop of the live run is underway; `\"message-edit\"` / `\"message-reload\"` pair with `nextDispatch`. */\n export type RunsStopping = {\n readonly reason: \"stop\" | \"message-edit\" | \"message-reload\";\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */\n readonly epoch?: number;\n readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: \"ready\" | RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the state with unsettled commands folded in, resting defaults while no entry is live. */\n export type Runs = {\n /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */\n readonly epoch?: number;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */\n readonly failed: readonly RunsFailedEntry[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `connected`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\n runs: Runs;\n };\n\n /** Converter output: app-owned keys only — the lib projects the run mounts itself. */\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n /** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */\n initialState: T;\n converter: StateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, applied, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n /** The host supports `message/switch-branch` (thread-global branch switching driven by `metadata.custom.branch`). */\n unstable_switchBranch?: boolean | undefined;\n }\n | undefined;\n /**\n * Durable drafts: the mounted composer storage restores on mount, mirrors\n * every change, and clears when the draft is consumed. The session storage\n * holds this thread's lane identity and its un-durable commands, which\n * resend under their original seqs on the next mount.\n */\n storage?:\n | {\n composer?: ResourceElement<ComposerStorage> | undefined;\n session?: ResourceElement<StatewireClient.SessionStorage> | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/core\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n messageSwitchBranch: StatewireThread.SwitchBranchCommand;\n }\n }\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;AAgDA,MAAa2C,wBAAwBC,OAAO,kBAAkB;AAE9D,MAAaC,qBAAqBC,WAA4C;CAC5E,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEH,yBAAyBG,SAE3B,MAAM,IAAIG,MACR,mEACF;CAEF,OAAOH;AACT;AAEA,MAAMI,oBAAkE,CAAA;AAExE,MAAME,eAAqC;CACzCE,OAA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;CAEpB,MAAM,EAAEzE,MAAMiF,WAAW/B,aAAagC,wBACpCpC,OAAO6B,SAAS,CAAC,CAACrE;CACpB,MAAM6E,mBAAmB9N,cAErB6N,oBACGhI,QACE2H,iBACCA,aAAWnJ,OAAOiE,SAAS,UAC/B,CAAC,CACAyF,KAAK,EAAEC,MAAMC,OAAO,GAAGC,aAAaA,MAAM,GAC/C,CAACL,mBAAmB,CACtB;CACA,MAAM,CAACM,aAAajO,gBAAgB,EAAEkO,YAAYnK,KAAAA,EAAqB,EAAE;CACzElE,gBAAgB;EACd,MAAMwG,YAAU6G;EAChB,IAAI7G,cAAYtC,KAAAA,GAAW;EAG3B,MAAMoK,aAAaF,UAAUC,eAAe7H;EAC5C4H,UAAUC,aAAa7H;EACvB,IAAIqH,cAAc,MAAME,iBAAiBpE,WAAW,GAAG;GACrD,IAAI,CAAC2E,YAAY9H,UAAQ+H,MAAM;GAC/B;EACF;EACA/H,UAAQgI,MAAM;GAAE5F,MAAMiF;GAAW/B,aAAaiC;EAAiB,CAAC;CAClE,GAAG;EAACK;EAAWf;EAAiBQ;EAAWE;CAAgB,CAAC;CAE5D,OAAOrC;AACT;AAEA,MAAa5I,mBACXsC,YAEAhF,SAAS+E,kBAAkB,CAAC,CAACC,OAAuC;AA8ZtExE,uBACEuE,oBACA1E,eAAeyD,KAAAA,CAAkB,CAAC,CAACkP,IACrC"}
1
+ {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","useResources","withKey","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","CompleteAttachment","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","createBranchCommandAdapter","createRunQueueAdapter","resolveEditCommand","retryCommand","resolveReloadCommand","sendFields","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","symbolStatewireExtras","Symbol","asStatewireExtras","extras","StatewireThread","Extras","Error","NO_INPUT_REQUESTS","InputRequestState","RESTING_RUNS","Runs","runId","queue","steerQueue","failed","failedRunCommand","entry","FailedCommand","RunEnqueueCommand","RunSteerCommand","RunEditCommand","message","UserMessage","command","undefined","params","ReturnType","presentStatus","status","ThreadStatus","connection","ConnectionState","reason","cause","code","ambientContextOf","context","system","tools","callSettings","config","useStatewireThread","options","Options","latest","current","pending","setPending","Command","retire","prev","includes","filter","c","state","commands","setContext","isBusy","discardFailed","transport","onError","error","storage","initialState","optimistic","draft","ctx","materialize","onCommandChange","update","onStateChange","onConnectionChange","failureCovered","messages","id","some","m","discarded","WeakSet","has","add","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","subscribe","dispatch","settled","type","catch","threadRef","dispatchSend","sourceId","text","content","flatMap","part","join","setText","composer","next","runs","entries","RunState","failedEntries","failure","RunsFailedEntry","sendFailure","length","epoch","dispatching","stopping","nextDispatch","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","converted","State","liveRunId","branches","takeFailed","messageId","find","f","sendCommand","reconnect","retryFailed","popFailed","parts","p","handleAppend","crypto","randomUUID","handleReload","parentId","handleEdit","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","unstable_switchBranch","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","composerStorage","read","getState","isEmpty","attachment","addAttachment","name","contentType","draftText","composerAttachments","draftAttachments","map","file","_file","record","draftSync","writingFor","isBaseline","clear","write","T","UserCommands","Commands","Transport","ComposerDraft","ComposerStorage","Promise","TextPart","FilePart","mediaType","url","filename","role","Placement","insertAfter","insertBefore","RunSendCommand","TType","runAnchorMessageId","RunDequeueCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","BranchMetadata","siblings","SwitchBranchCommand","branchId","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","RunsQueueEntry","SendFailure","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","RunsError","MaterializeEffects","append","rollback","to","RunsState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","session","SessionStorage","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","messageSwitchBranch","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n resource,\n useResource,\n useResources,\n withKey,\n} from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/core/store\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/core/store\";\nimport type { Assistant } from \"@assistant-ui/core\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n CompleteAttachment,\n FeedbackAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n SpeechSynthesisAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport {\n createBranchCommandAdapter,\n createRunQueueAdapter,\n resolveEditCommand,\n retryCommand,\n resolveReloadCommand,\n sendFields,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nexport const symbolStatewireExtras = Symbol(\"statewire-extras\");\n\nexport const asStatewireExtras = (extras: unknown): StatewireThread.Extras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolStatewireExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using StatewireThread\",\n );\n\n return extras as StatewireThread.Extras;\n};\n\nconst NO_INPUT_REQUESTS: readonly StatewireThread.InputRequestState[] = [];\n\nconst RESTING_RUNS: StatewireThread.Runs = {\n runId: null,\n queue: [],\n steerQueue: [],\n failed: [],\n};\n\n/** The failed run sends the thread can project: enqueue/steer/edit invocations carrying a message. */\nconst failedRunCommand = (\n entry: StatewireClient.FailedCommand,\n):\n | ((\n | StatewireThread.RunEnqueueCommand\n | StatewireThread.RunSteerCommand\n | StatewireThread.RunEditCommand\n ) & { message: StatewireThread.UserMessage })\n | undefined => {\n if (\n entry.command !== \"run/enqueue\" &&\n entry.command !== \"run/steer\" &&\n entry.command !== \"run/edit\"\n )\n return undefined;\n const command = entry.params[0] as\n | { message?: StatewireThread.UserMessage }\n | undefined;\n if (command?.message === undefined) return undefined;\n return command as ReturnType<typeof failedRunCommand>;\n};\n\n// Derived presentation while the connection can't vouch for progress:\n// live-claiming \"running\" reads as evicted/disconnected; facts pass through.\nconst presentStatus = (\n status: StatewireThread.ThreadStatus,\n connection: StatewireClient.ConnectionState,\n): StatewireThread.ThreadStatus =>\n status !== \"running\" ||\n connection.status === \"connected\" ||\n (connection.status === \"disconnected\" && connection.reason === \"idle\")\n ? status\n : connection.status === \"connecting\" &&\n connection.cause === \"reconnect\" &&\n connection.code === \"evicted\"\n ? \"evicted\"\n : \"disconnected\";\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const {\n state,\n commands,\n connection,\n setContext,\n isBusy,\n failed,\n discardFailed,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n onError: (error) => latest.current.onError?.(error),\n storage: options.storage,\n initialState: options.initialState,\n optimistic: (draft, command, ctx) => {\n runsOptimistic(draft, command, ctx);\n latest.current.optimistic?.(draft, command, ctx);\n },\n materialize: (draft: {}) => latest.current.materialize?.(draft),\n onCommandChange: (update, ctx) => {\n if (update.status === \"applied\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n failureCovered: (state, entry) => {\n const command = failedRunCommand(entry);\n if (command === undefined) return false;\n const messages = (state as { messages?: readonly { id: string }[] })\n .messages;\n return messages?.some((m) => m.id === command.message.id) ?? false;\n },\n });\n\n const discarded = useRef(new WeakSet<StatewireClient.FailedCommand>());\n // Effects can replay before the updated failed lane reaches the binding.\n useEffect(() => {\n for (const entry of failed) {\n if (\n failedRunCommand(entry) === undefined &&\n !discarded.current.has(entry)\n ) {\n discarded.current.add(entry);\n discardFailed(entry);\n }\n }\n }, [failed, discardFailed]);\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n setContextRef.current(value);\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n const { status, runs } = useMemo((): {\n status: StatewireThread.ThreadStatus;\n runs: StatewireThread.Runs;\n } => {\n const entries = (\n state as { runs?: readonly StatewireThread.RunState[] } | undefined\n )?.runs;\n const entry = entries?.[0];\n const failedEntries = failed.flatMap(\n (failure): StatewireThread.RunsFailedEntry[] => {\n const command = failedRunCommand(failure);\n return command === undefined\n ? []\n : [{ ...command.message, sendFailure: failure.failure }];\n },\n );\n return {\n status: presentStatus(\n entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n connection,\n ),\n runs:\n entry === undefined && failedEntries.length === 0\n ? RESTING_RUNS\n : {\n ...(entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n ...(entry.epoch !== undefined && { epoch: entry.epoch }),\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && {\n stopping: entry.stopping,\n }),\n ...(entry.nextDispatch !== undefined && {\n nextDispatch: entry.nextDispatch,\n }),\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n ...(entry.error !== undefined && { error: entry.error }),\n }),\n failed: failedEntries,\n },\n };\n }, [state, connection, failed]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n runs,\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n (): StatewireThread.State => converter(state, metadata),\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const liveRunId = runs.runId;\n\n const queue = useMemo(\n () =>\n createRunQueueAdapter(\n messages,\n liveRunId,\n runs.queue,\n runs.steerQueue,\n dispatch,\n dispatchSend,\n ),\n [messages, liveRunId, runs, dispatch, dispatchSend],\n );\n\n const branches = useMemo(\n () => createBranchCommandAdapter(messages, dispatch),\n [messages, dispatch],\n );\n\n const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo((): StatewireThread.Extras => {\n const takeFailed = (messageId: string): StatewireClient.FailedCommand => {\n const entry = failed.find(\n (f) => failedRunCommand(f)?.message.id === messageId,\n );\n if (entry === undefined)\n throw new Error(`statewire: unknown failed entry \"${messageId}\"`);\n return entry;\n };\n return {\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n retryFailed: (messageId) => {\n const entry = takeFailed(messageId);\n const command = retryCommand(\n messages,\n liveRunId,\n failedRunCommand(entry)!,\n );\n discardFailed(entry);\n void dispatch(command);\n },\n discardFailed: (messageId) => discardFailed(takeFailed(messageId)),\n popFailed: (messageId) => {\n const entry = takeFailed(messageId);\n discardFailed(entry);\n return failedRunCommand(entry)!\n .message.parts.flatMap((p) => (p.type === \"text\" ? [p.text] : []))\n .join(\"\\n\\n\");\n },\n };\n }, [\n dispatch,\n connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n failed,\n discardFailed,\n messages,\n liveRunId,\n ]);\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message, liveRunId)\n : {\n type: \"run/steer\",\n ...sendFields(\n messages,\n liveRunId,\n toWireMessage(message, crypto.randomUUID()),\n ),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId, liveRunId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message, liveRunId));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning: status === \"running\",\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\n onNew: handleAppend,\n queue,\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () =>\n dispatch({\n type: \"run/continue\",\n ...(liveRunId !== null && { runId: liveRunId }),\n }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(options.capabilities?.unstable_switchBranch && { branches }),\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n void commands[\"run/stop\"]!({\n ...payload,\n runId: runs.runId,\n ...(runs.epoch !== undefined && { epoch: runs.epoch }),\n }).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n\n const composerStorage = useResources(\n options.storage?.composer !== undefined\n ? [withKey(\"composer\", options.storage.composer)]\n : [],\n )[0];\n\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n const composer = threadRef.current!.composer();\n const draft = storage.read();\n if (draft === undefined || !composer.getState().isEmpty) return;\n composer.setText(draft.text);\n for (const attachment of draft.attachments) {\n composer\n .addAttachment({\n id: attachment.id,\n type: attachment.type,\n name: attachment.name,\n ...(attachment.contentType !== undefined && {\n contentType: attachment.contentType,\n }),\n content: attachment.content,\n })\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n }\n }, [composerStorage]);\n\n const { text: draftText, attachments: composerAttachments } =\n thread.getState().composer;\n const draftAttachments = useMemo(\n () =>\n composerAttachments\n .filter(\n (attachment): attachment is CompleteAttachment =>\n attachment.status.type === \"complete\",\n )\n .map(({ file: _file, ...record }) => record),\n [composerAttachments],\n );\n const [draftSync] = useState(() => ({ writingFor: undefined as unknown }));\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n // First run per storage is the baseline, not a change: never clear the\n // stored draft the restore effect is about to load.\n const isBaseline = draftSync.writingFor !== storage;\n draftSync.writingFor = storage;\n if (draftText === \"\" && draftAttachments.length === 0) {\n if (!isBaseline) storage.clear();\n return;\n }\n storage.write({ text: draftText, attachments: draftAttachments });\n }, [draftSync, composerStorage, draftText, draftAttachments]);\n\n return thread;\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\n\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n /** A composer draft as persisted: the text plus the completed attachments. */\n export type ComposerDraft = {\n readonly text: string;\n readonly attachments: readonly CompleteAttachment[];\n };\n\n /** Composer draft storage seam; `write` must persist synchronously in the caller's flow. */\n export type ComposerStorage = {\n read(): ComposerDraft | undefined;\n write(draft: ComposerDraft): void;\n clear(): void;\n };\n\n export type Extras = {\n [symbolStatewireExtras]: true;\n /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */\n sendCommand: (command: Command) => Promise<unknown>;\n reconnect: () => void;\n state: unknown;\n status: ThreadStatus;\n /** Negation of the server's broadcast idle level (a transport without idle is always busy). */\n isBusy: boolean;\n inputRequests: readonly InputRequestState[];\n runs: Runs;\n /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */\n retryFailed: (messageId: string) => void;\n /** Removes the failed entry; keyed by the entry's message id. */\n discardFailed: (messageId: string) => void;\n /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */\n popFailed: (messageId: string) => string;\n };\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n type RunSendCommand<TType extends \"run/enqueue\" | \"run/steer\"> = {\n readonly type: TType;\n /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: UserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunEnqueueCommand = RunSendCommand<\"run/enqueue\">;\n\n export type RunSteerCommand = RunSendCommand<\"run/steer\">;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly runId: string;\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n readonly runId?: string;\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly runId?: string;\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state; a present `response` key marks the entry answered. */\n export type InputRequestState = InputRequest & {\n readonly response?: InputResponse;\n /** The answer's `run/input` meta; absent when the answer carried none. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** Per-message branch metadata read from `metadata.custom.branch`: the message's own branch id and the fan-out's branch ids in creation order (own id included). */\n export type BranchMetadata = {\n readonly id: number;\n readonly siblings: readonly number[];\n };\n\n export type SwitchBranchCommand = {\n readonly type: \"message/switch-branch\";\n readonly branchId: number;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus = \"running\" | \"stopped\" | \"error\" | \"input-required\";\n\n /** The thread's status: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status; `\"evicted\"` and `\"disconnected\"` are client-derived from the connection, never replicated. */\n export type ThreadStatus =\n | \"loading\"\n | \"ready\"\n | \"evicted\"\n | \"disconnected\"\n | RunStatus;\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */\n export type RunsFailedEntry = RunsQueueEntry & {\n readonly sendFailure: StatewireClient.SendFailure;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** The run-starting op's meta; present only when carried. */\n readonly rootMeta?: ReadonlyJSONValue;\n /** Present when input outcomes ride the dispatch; visible until applied. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The stopping window: present while a stop of the live run is underway; `\"message-edit\"` / `\"message-reload\"` pair with `nextDispatch`. */\n export type RunsStopping = {\n readonly reason: \"stop\" | \"message-edit\" | \"message-reload\";\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */\n readonly epoch?: number;\n readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: \"ready\" | RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the state with unsettled commands folded in, resting defaults while no entry is live. */\n export type Runs = {\n /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */\n readonly epoch?: number;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */\n readonly failed: readonly RunsFailedEntry[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `connected`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\n runs: Runs;\n };\n\n /** Converter output: app-owned keys only — the lib projects the run mounts itself. */\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n /** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */\n initialState: T;\n converter: StateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, applied, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n /** The host supports `message/switch-branch` (thread-global branch switching driven by `metadata.custom.branch`). */\n unstable_switchBranch?: boolean | undefined;\n }\n | undefined;\n /**\n * Durable drafts: the mounted composer storage restores on mount, mirrors\n * every change, and clears when the draft is consumed. The session storage\n * holds this thread's lane identity and its un-durable commands, which\n * resend under their original seqs on the next mount.\n */\n storage?:\n | {\n composer?: ResourceElement<ComposerStorage> | undefined;\n session?: ResourceElement<StatewireClient.SessionStorage> | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/core\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n messageSwitchBranch: StatewireThread.SwitchBranchCommand;\n }\n }\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;AAgDA,MAAa2C,wBAAwBC,OAAO,kBAAkB;AAE9D,MAAaC,qBAAqBC,WAA4C;CAC5E,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEH,yBAAyBG,SAE3B,MAAM,IAAIG,MACR,mEACF;CAEF,OAAOH;AACT;AAEA,MAAMI,oBAAkE,CAAA;AAExE,MAAME,eAAqC;CACzCE,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,QAAQ,CAAA;AACV;;AAGA,MAAMC,oBACJC,UAOe;CACf,IACEA,MAAMO,YAAY,iBAClBP,MAAMO,YAAY,eAClBP,MAAMO,YAAY,YAElB,OAAOC,KAAAA;CACT,MAAMD,UAAUP,MAAMS,OAAO;CAG7B,IAAIF,SAASF,YAAYG,KAAAA,GAAW,OAAOA,KAAAA;CAC3C,OAAOD;AACT;AAIA,MAAMI,iBACJC,QACAE,eAEAF,WAAW,aACXE,WAAWF,WAAW,eACrBE,WAAWF,WAAW,kBAAkBE,WAAWE,WAAW,SAC3DJ,SACAE,WAAWF,WAAW,gBACpBE,WAAWG,UAAU,eACrBH,WAAWI,SAAS,YACpB,YACA;AAER,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWb,KAAAA,KAAa,EAAEa,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQE,UAAUd,KAAAA,KAAa,EACjCc,OAAOxD,kBAAkBsD,QAAQE,KAAK,EACxC;CACA,GAAIF,QAAQG,iBAAiBf,KAAAA,KAAa,EACxCe,cAAcH,QAAQG,aACxB;CACA,GAAIH,QAAQI,WAAWhB,KAAAA,KAAa,EAAEgB,QAAQJ,QAAQI,OAAO;AAC/D;AAEA,MAAMC,sBACJC,YAC2B;CAC3B,MAAME,SAASpF,OAAOkF,OA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,OAAOrC;AACT;AAEA,MAAahJ,mBACXsC,YAEAhF,SAAS+E,kBAAkB,CAAC,CAACC,OAAuC;AA8ZtExE,uBACEuE,oBACA1E,eAAeyD,KAAAA,CAAkB,CAAC,CAACsP,IACrC"}
@@ -1,4 +1,5 @@
1
1
  import { StatewireThread } from "./StatewireThread.js";
2
+ import { StatewireClient } from "statewire";
2
3
  //#region src/localStorage.d.ts
3
4
  /** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */
4
5
  declare const LocalStorageComposerDrafts: import("@assistant-ui/tap").Resource<StatewireThread.ComposerStorage, [LocalStorageComposerDrafts.Options]>;
@@ -6,6 +7,8 @@ declare const LocalStorageComposerDrafts: import("@assistant-ui/tap").Resource<S
6
7
  declare const LocalStorageSession: import("@assistant-ui/tap").Resource<StatewireClient.SessionStorage, [LocalStorageSession.Options]>;
7
8
  declare namespace LocalStorageSession {
8
9
  type Options = {
10
+ /** Upgrade incompatible queued commands, or return null to discard the saved session. */
11
+ migrate?: StatewireClient.SessionStorage["migrate"];
9
12
  /** The thread whose session this storage holds. */
10
13
  threadId: string;
11
14
  /** Derives the storage key from the thread id; defaults to the id itself. */
@@ -1 +1 @@
1
- {"version":3,"file":"localStorage.d.ts","names":[],"sources":["../src/localStorage.ts"],"mappings":";;;cA+Oa,wDAA0B,SAAA,gBAAA,kBAAA,2BAAA;;cA0C1B,iDAAmB,SAAA,gBAAA,iBAAA,oBAAA;kBAEf;OACH;;IAEV;;IAEA,QAAQ;;;kBAIK;OACH;;IAEV;;IAEA,QAAQ;;IAER;;IAEA"}
1
+ {"version":3,"file":"localStorage.d.ts","names":[],"sources":["../src/localStorage.ts"],"mappings":";;;;cA+Oa,wDAA0B,SAAA,gBAAA,kBAAA,2BAAA;;cA4C1B,iDAAmB,SAAA,gBAAA,iBAAA,oBAAA;kBAEf;OACH;;IAEV,UAAU,gBAAgB;;IAE1B;;IAEA,QAAQ;;;kBAIK;OACH;;IAEV;;IAEA,QAAQ;;IAER;;IAEA"}
@@ -106,7 +106,7 @@ const useLocalStorageComposerDrafts = ({ threadId, key = (id) => id, ttl = 7 * D
106
106
  /** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */
107
107
  const LocalStorageComposerDrafts = resource(useLocalStorageComposerDrafts);
108
108
  const SESSION_LOCK_PREFIX = "aui:statewire-session-lock:";
109
- const useLocalStorageSession = ({ threadId, key = (id) => id }) => {
109
+ const useLocalStorageSession = ({ threadId, migrate, key = (id) => id }) => {
110
110
  if (typeof localStorage === "undefined") throw new Error("statewire: LocalStorageSession requires localStorage");
111
111
  if (typeof navigator === "undefined" || navigator.locks === void 0) throw new Error("statewire: LocalStorageSession requires the Web Locks API (navigator.locks)");
112
112
  const storageKey = SESSION_PREFIX + key(threadId);
@@ -118,6 +118,7 @@ const useLocalStorageSession = ({ threadId, key = (id) => id }) => {
118
118
  save: (record) => {
119
119
  localStorage.setItem(storageKey, JSON.stringify(record));
120
120
  },
121
+ ...migrate !== void 0 && { migrate },
121
122
  lock: (fn) => navigator.locks.request(lockName, async () => fn()),
122
123
  subscribe: (listener) => {
123
124
  const onStorage = (event) => {
@@ -126,7 +127,11 @@ const useLocalStorageSession = ({ threadId, key = (id) => id }) => {
126
127
  window.addEventListener("storage", onStorage);
127
128
  return () => window.removeEventListener("storage", onStorage);
128
129
  }
129
- }), [storageKey, lockName]);
130
+ }), [
131
+ storageKey,
132
+ lockName,
133
+ migrate
134
+ ]);
130
135
  };
131
136
  /** Session storage on localStorage, keyed per thread: the lane identity plus the commands awaiting a durable verdict; sharers serialize through a per-key Web Lock. */
132
137
  const LocalStorageSession = resource(useLocalStorageSession);
@@ -1 +1 @@
1
- {"version":3,"file":"localStorage.js","names":["useEffect","useMemo","resource","StatewireClient","StatewireThread","PREFIX","SESSION_PREFIX","DAY","StoredDraft","text","attachments","ComposerDraft","ts","isRecord","value","Record","Array","isArray","isOptionalString","undefined","isUserMessagePart","audio","StoredAttachment","isStoredAttachment","status","every","isStoredDraft","Number","isFinite","isPositiveSafeInteger","isSafeInteger","isSessionCommand","SessionCommand","isSessionVerdict","SessionVerdict","isSendFailure","SendFailure","isFailedCommand","FailedCommand","isSessionRecord","SessionRecord","loadStored","key","validate","T","raw","localStorage","getItem","JSON","parse","removeItem","sweep","ttl","max","entries","keys","from","length","_","index","startsWith","stored","push","now","Date","fresh","filter","sort","a","b","slice","useLocalStorageComposerDrafts","threadId","id","LocalStorageComposerDrafts","Options","ComposerStorage","Error","storageKey","read","write","draft","setItem","stringify","clear","SESSION_LOCK_PREFIX","useLocalStorageSession","LocalStorageSession","SessionStorage","navigator","locks","lockName","load","save","record","lock","fn","request","subscribe","listener","onStorage","event","StorageEvent","window","addEventListener","removeEventListener"],"sources":["../src/localStorage.ts"],"sourcesContent":["import { useEffect, useMemo } from \"react\";\nimport { resource } from \"@assistant-ui/tap\";\nimport type { StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nconst PREFIX = \"aui:composer-draft:\";\nconst SESSION_PREFIX = \"aui:statewire-session:\";\nconst DAY = 86_400_000;\n\ntype StoredDraft = {\n text: string;\n attachments: StatewireThread.ComposerDraft[\"attachments\"];\n ts: number;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isOptionalString = (value: unknown): boolean =>\n value === undefined || typeof value === \"string\";\n\nconst isUserMessagePart = (value: unknown): boolean => {\n if (!isRecord(value)) return false;\n switch (value[\"type\"]) {\n case \"text\":\n return typeof value[\"text\"] === \"string\";\n case \"image\":\n return (\n typeof value[\"image\"] === \"string\" &&\n isOptionalString(value[\"filename\"])\n );\n case \"file\":\n return (\n typeof value[\"data\"] === \"string\" &&\n typeof value[\"mimeType\"] === \"string\" &&\n isOptionalString(value[\"filename\"])\n );\n case \"data\":\n return typeof value[\"name\"] === \"string\";\n case \"audio\": {\n const audio = value[\"audio\"];\n return (\n isRecord(audio) &&\n typeof audio[\"data\"] === \"string\" &&\n (audio[\"format\"] === \"mp3\" || audio[\"format\"] === \"wav\")\n );\n }\n default:\n return false;\n }\n};\n\ntype StoredAttachment = StoredDraft[\"attachments\"][number];\n\nconst isStoredAttachment = (value: unknown): value is StoredAttachment => {\n if (!isRecord(value)) return false;\n const status = value[\"status\"];\n return (\n typeof value[\"id\"] === \"string\" &&\n typeof value[\"type\"] === \"string\" &&\n typeof value[\"name\"] === \"string\" &&\n isOptionalString(value[\"contentType\"]) &&\n value[\"file\"] === undefined &&\n isRecord(status) &&\n status[\"type\"] === \"complete\" &&\n Array.isArray(value[\"content\"]) &&\n value[\"content\"].every(isUserMessagePart)\n );\n};\n\nconst isStoredDraft = (value: unknown): value is StoredDraft =>\n isRecord(value) &&\n typeof value[\"text\"] === \"string\" &&\n Array.isArray(value[\"attachments\"]) &&\n value[\"attachments\"].every(isStoredAttachment) &&\n typeof value[\"ts\"] === \"number\" &&\n Number.isFinite(value[\"ts\"]);\n\nconst isPositiveSafeInteger = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isSafeInteger(value) && value > 0;\n\nconst isSessionCommand = (\n value: unknown,\n): value is StatewireClient.SessionCommand =>\n isRecord(value) &&\n isPositiveSafeInteger(value[\"seq\"]) &&\n typeof value[\"method\"] === \"string\" &&\n Array.isArray(value[\"params\"]);\n\nconst isSessionVerdict = (\n value: unknown,\n): value is StatewireClient.SessionVerdict =>\n isRecord(value) &&\n isPositiveSafeInteger(value[\"seq\"]) &&\n (value[\"type\"] === \"result\" ||\n value[\"type\"] === \"rejected\" ||\n value[\"type\"] === \"failed\" ||\n value[\"type\"] === \"crashed\" ||\n value[\"type\"] === \"expired\") &&\n isOptionalString(value[\"code\"]) &&\n isOptionalString(value[\"message\"]);\n\nconst isSendFailure = (\n value: unknown,\n): value is StatewireClient.SendFailure => {\n if (!isRecord(value)) return false;\n switch (value[\"fate\"]) {\n case \"rejected\":\n return (\n value[\"cause\"] === \"server\" &&\n isOptionalString(value[\"code\"]) &&\n isOptionalString(value[\"message\"])\n );\n case \"failed\":\n return value[\"cause\"] === \"server\" && isOptionalString(value[\"message\"]);\n case \"crashed\":\n case \"expired\":\n return value[\"cause\"] === \"server\";\n case \"aborted\":\n return (\n (value[\"cause\"] === \"unmount\" ||\n value[\"cause\"] === \"stream-gone\" ||\n value[\"cause\"] === \"session-lost\") &&\n (value[\"predecessorLost\"] === undefined ||\n value[\"predecessorLost\"] === true)\n );\n case \"lost\":\n return (\n value[\"cause\"] === \"unmount\" ||\n value[\"cause\"] === \"stream-gone\" ||\n value[\"cause\"] === \"session-lost\"\n );\n default:\n return false;\n }\n};\n\nconst isFailedCommand = (\n value: unknown,\n): value is StatewireClient.FailedCommand =>\n isRecord(value) &&\n typeof value[\"command\"] === \"string\" &&\n Array.isArray(value[\"params\"]) &&\n isSendFailure(value[\"failure\"]) &&\n typeof value[\"ts\"] === \"number\" &&\n Number.isFinite(value[\"ts\"]) &&\n isPositiveSafeInteger(value[\"seq\"]);\n\nconst isSessionRecord = (\n value: unknown,\n): value is StatewireClient.SessionRecord =>\n isRecord(value) &&\n typeof value[\"clientId\"] === \"string\" &&\n isPositiveSafeInteger(value[\"nextSeq\"]) &&\n isPositiveSafeInteger(value[\"ctxNextSeq\"]) &&\n Array.isArray(value[\"commands\"]) &&\n value[\"commands\"].every(isSessionCommand) &&\n (value[\"verdicts\"] === undefined ||\n (Array.isArray(value[\"verdicts\"]) &&\n value[\"verdicts\"].every(isSessionVerdict))) &&\n (value[\"failed\"] === undefined ||\n (Array.isArray(value[\"failed\"]) && value[\"failed\"].every(isFailedCommand)));\n\nconst loadStored = <T>(\n key: string,\n validate: (value: unknown) => value is T,\n): T | null => {\n const raw = localStorage.getItem(key);\n if (raw === null) return null;\n try {\n const value: unknown = JSON.parse(raw);\n if (validate(value)) return value;\n } catch {}\n localStorage.removeItem(key);\n return null;\n};\n\nconst sweep = (ttl: number, max: number) => {\n const entries: { key: string; ts: number }[] = [];\n const keys = Array.from({ length: localStorage.length }, (_, index) =>\n localStorage.key(index),\n );\n for (const key of keys) {\n if (key === null || !key.startsWith(PREFIX)) continue;\n const stored = loadStored(key, isStoredDraft);\n if (stored !== null) entries.push({ key, ts: stored.ts });\n }\n const now = Date.now();\n const fresh = entries.filter(({ key, ts }) => {\n if (now - ts <= ttl) return true;\n localStorage.removeItem(key);\n return false;\n });\n fresh.sort((a, b) => b.ts - a.ts);\n for (const { key } of fresh.slice(max)) localStorage.removeItem(key);\n};\n\nconst useLocalStorageComposerDrafts = ({\n threadId,\n key = (id) => id,\n ttl = 7 * DAY,\n max = 50,\n}: LocalStorageComposerDrafts.Options): StatewireThread.ComposerStorage => {\n if (typeof localStorage === \"undefined\")\n throw new Error(\n \"statewire: LocalStorageComposerDrafts requires localStorage\",\n );\n\n useEffect(() => {\n sweep(ttl, max);\n }, [ttl, max]);\n\n const storageKey = PREFIX + key(threadId);\n return useMemo(\n (): StatewireThread.ComposerStorage => ({\n read: () => {\n const stored = loadStored(storageKey, isStoredDraft);\n if (stored === null) return undefined;\n return { text: stored.text, attachments: stored.attachments };\n },\n write: (draft) => {\n if (draft.text === \"\" && draft.attachments.length === 0) {\n localStorage.removeItem(storageKey);\n return;\n }\n localStorage.setItem(\n storageKey,\n JSON.stringify({ ...draft, ts: Date.now() }),\n );\n },\n clear: () => {\n localStorage.removeItem(storageKey);\n },\n }),\n [storageKey],\n );\n};\n\n/** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */\nexport const LocalStorageComposerDrafts = resource(\n useLocalStorageComposerDrafts,\n);\n\nconst SESSION_LOCK_PREFIX = \"aui:statewire-session-lock:\";\n\nconst useLocalStorageSession = ({\n threadId,\n key = (id) => id,\n}: LocalStorageSession.Options): StatewireClient.SessionStorage => {\n if (typeof localStorage === \"undefined\")\n throw new Error(\"statewire: LocalStorageSession requires localStorage\");\n // localStorage is shared across tabs: record mutations must serialize.\n if (typeof navigator === \"undefined\" || navigator.locks === undefined)\n throw new Error(\n \"statewire: LocalStorageSession requires the Web Locks API (navigator.locks)\",\n );\n\n const storageKey = SESSION_PREFIX + key(threadId);\n const lockName = SESSION_LOCK_PREFIX + key(threadId);\n return useMemo(\n (): StatewireClient.SessionStorage => ({\n load: () => {\n return loadStored(storageKey, isSessionRecord);\n },\n save: (record) => {\n localStorage.setItem(storageKey, JSON.stringify(record));\n },\n lock: (fn) => navigator.locks.request(lockName, async () => fn()),\n subscribe: (listener) => {\n const onStorage = (event: StorageEvent) => {\n if (event.key === storageKey) listener();\n };\n window.addEventListener(\"storage\", onStorage);\n return () => window.removeEventListener(\"storage\", onStorage);\n },\n }),\n [storageKey, lockName],\n );\n};\n\n/** Session storage on localStorage, keyed per thread: the lane identity plus the commands awaiting a durable verdict; sharers serialize through a per-key Web Lock. */\nexport const LocalStorageSession = resource(useLocalStorageSession);\n\nexport namespace LocalStorageSession {\n export type Options = {\n /** The thread whose session this storage holds. */\n threadId: string;\n /** Derives the storage key from the thread id; defaults to the id itself. */\n key?: ((threadId: string) => string) | undefined;\n };\n}\n\nexport namespace LocalStorageComposerDrafts {\n export type Options = {\n /** The thread whose draft this storage holds. */\n threadId: string;\n /** Derives the storage key from the thread id; defaults to the id itself. */\n key?: ((threadId: string) => string) | undefined;\n /** Draft lifetime in milliseconds, enforced by the mount sweep. Default 7 days. */\n ttl?: number | undefined;\n /** Newest drafts kept across all keys, enforced by the mount sweep. Default 50. */\n max?: number | undefined;\n };\n}\n"],"mappings":";;;AAKA,MAAMK,SAAS;AACf,MAAMC,iBAAiB;AACvB,MAAMC,MAAM;AAQZ,MAAMM,YAAYC,UAChB,OAAOA,UAAU,YAAYA,UAAU,QAAQ,CAACE,MAAMC,QAAQH,KAAK;AAErE,MAAMI,oBAAoBJ,UACxBA,UAAUK,KAAAA,KAAa,OAAOL,UAAU;AAE1C,MAAMM,qBAAqBN,UAA4B;CACrD,IAAI,CAACD,SAASC,KAAK,GAAG,OAAO;CAC7B,QAAQA,MAAM,SAAd;EACE,KAAK,QACH,OAAO,OAAOA,MAAM,YAAY;EAClC,KAAK,SACH,OACE,OAA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K,GAAG,CAAC;EAChEE,YAAYC,aAAa;GACvB,MAAMC,aAAaC,UAAwB;IACzC,IAAIA,MAAM3D,QAAQoC,YAAYqB,SAAS;GACzC;GACAI,OAAOC,iBAAiB,WAAWJ,SAAS;GAC5C,aAAaG,OAAOE,oBAAoB,WAAWL,SAAS;EAC9D;CACF,IACA,CAACtB,YAAYa,QAAQ,CACvB;AACF;;AAGA,MAAaJ,sBAAsBrF,SAASoF,sBAAsB"}
1
+ {"version":3,"file":"localStorage.js","names":["useEffect","useMemo","resource","StatewireClient","StatewireThread","PREFIX","SESSION_PREFIX","DAY","StoredDraft","text","attachments","ComposerDraft","ts","isRecord","value","Record","Array","isArray","isOptionalString","undefined","isUserMessagePart","audio","StoredAttachment","isStoredAttachment","status","every","isStoredDraft","Number","isFinite","isPositiveSafeInteger","isSafeInteger","isSessionCommand","SessionCommand","isSessionVerdict","SessionVerdict","isSendFailure","SendFailure","isFailedCommand","FailedCommand","isSessionRecord","SessionRecord","loadStored","key","validate","T","raw","localStorage","getItem","JSON","parse","removeItem","sweep","ttl","max","entries","keys","from","length","_","index","startsWith","stored","push","now","Date","fresh","filter","sort","a","b","slice","useLocalStorageComposerDrafts","threadId","id","LocalStorageComposerDrafts","Options","ComposerStorage","Error","storageKey","read","write","draft","setItem","stringify","clear","SESSION_LOCK_PREFIX","useLocalStorageSession","migrate","LocalStorageSession","SessionStorage","navigator","locks","lockName","load","save","record","lock","fn","request","subscribe","listener","onStorage","event","StorageEvent","window","addEventListener","removeEventListener"],"sources":["../src/localStorage.ts"],"sourcesContent":["import { useEffect, useMemo } from \"react\";\nimport { resource } from \"@assistant-ui/tap\";\nimport type { StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nconst PREFIX = \"aui:composer-draft:\";\nconst SESSION_PREFIX = \"aui:statewire-session:\";\nconst DAY = 86_400_000;\n\ntype StoredDraft = {\n text: string;\n attachments: StatewireThread.ComposerDraft[\"attachments\"];\n ts: number;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isOptionalString = (value: unknown): boolean =>\n value === undefined || typeof value === \"string\";\n\nconst isUserMessagePart = (value: unknown): boolean => {\n if (!isRecord(value)) return false;\n switch (value[\"type\"]) {\n case \"text\":\n return typeof value[\"text\"] === \"string\";\n case \"image\":\n return (\n typeof value[\"image\"] === \"string\" &&\n isOptionalString(value[\"filename\"])\n );\n case \"file\":\n return (\n typeof value[\"data\"] === \"string\" &&\n typeof value[\"mimeType\"] === \"string\" &&\n isOptionalString(value[\"filename\"])\n );\n case \"data\":\n return typeof value[\"name\"] === \"string\";\n case \"audio\": {\n const audio = value[\"audio\"];\n return (\n isRecord(audio) &&\n typeof audio[\"data\"] === \"string\" &&\n (audio[\"format\"] === \"mp3\" || audio[\"format\"] === \"wav\")\n );\n }\n default:\n return false;\n }\n};\n\ntype StoredAttachment = StoredDraft[\"attachments\"][number];\n\nconst isStoredAttachment = (value: unknown): value is StoredAttachment => {\n if (!isRecord(value)) return false;\n const status = value[\"status\"];\n return (\n typeof value[\"id\"] === \"string\" &&\n typeof value[\"type\"] === \"string\" &&\n typeof value[\"name\"] === \"string\" &&\n isOptionalString(value[\"contentType\"]) &&\n value[\"file\"] === undefined &&\n isRecord(status) &&\n status[\"type\"] === \"complete\" &&\n Array.isArray(value[\"content\"]) &&\n value[\"content\"].every(isUserMessagePart)\n );\n};\n\nconst isStoredDraft = (value: unknown): value is StoredDraft =>\n isRecord(value) &&\n typeof value[\"text\"] === \"string\" &&\n Array.isArray(value[\"attachments\"]) &&\n value[\"attachments\"].every(isStoredAttachment) &&\n typeof value[\"ts\"] === \"number\" &&\n Number.isFinite(value[\"ts\"]);\n\nconst isPositiveSafeInteger = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isSafeInteger(value) && value > 0;\n\nconst isSessionCommand = (\n value: unknown,\n): value is StatewireClient.SessionCommand =>\n isRecord(value) &&\n isPositiveSafeInteger(value[\"seq\"]) &&\n typeof value[\"method\"] === \"string\" &&\n Array.isArray(value[\"params\"]);\n\nconst isSessionVerdict = (\n value: unknown,\n): value is StatewireClient.SessionVerdict =>\n isRecord(value) &&\n isPositiveSafeInteger(value[\"seq\"]) &&\n (value[\"type\"] === \"result\" ||\n value[\"type\"] === \"rejected\" ||\n value[\"type\"] === \"failed\" ||\n value[\"type\"] === \"crashed\" ||\n value[\"type\"] === \"expired\") &&\n isOptionalString(value[\"code\"]) &&\n isOptionalString(value[\"message\"]);\n\nconst isSendFailure = (\n value: unknown,\n): value is StatewireClient.SendFailure => {\n if (!isRecord(value)) return false;\n switch (value[\"fate\"]) {\n case \"rejected\":\n return (\n value[\"cause\"] === \"server\" &&\n isOptionalString(value[\"code\"]) &&\n isOptionalString(value[\"message\"])\n );\n case \"failed\":\n return value[\"cause\"] === \"server\" && isOptionalString(value[\"message\"]);\n case \"crashed\":\n case \"expired\":\n return value[\"cause\"] === \"server\";\n case \"aborted\":\n return (\n (value[\"cause\"] === \"unmount\" ||\n value[\"cause\"] === \"stream-gone\" ||\n value[\"cause\"] === \"session-lost\") &&\n (value[\"predecessorLost\"] === undefined ||\n value[\"predecessorLost\"] === true)\n );\n case \"lost\":\n return (\n value[\"cause\"] === \"unmount\" ||\n value[\"cause\"] === \"stream-gone\" ||\n value[\"cause\"] === \"session-lost\"\n );\n default:\n return false;\n }\n};\n\nconst isFailedCommand = (\n value: unknown,\n): value is StatewireClient.FailedCommand =>\n isRecord(value) &&\n typeof value[\"command\"] === \"string\" &&\n Array.isArray(value[\"params\"]) &&\n isSendFailure(value[\"failure\"]) &&\n typeof value[\"ts\"] === \"number\" &&\n Number.isFinite(value[\"ts\"]) &&\n isPositiveSafeInteger(value[\"seq\"]);\n\nconst isSessionRecord = (\n value: unknown,\n): value is StatewireClient.SessionRecord =>\n isRecord(value) &&\n typeof value[\"clientId\"] === \"string\" &&\n isPositiveSafeInteger(value[\"nextSeq\"]) &&\n isPositiveSafeInteger(value[\"ctxNextSeq\"]) &&\n Array.isArray(value[\"commands\"]) &&\n value[\"commands\"].every(isSessionCommand) &&\n (value[\"verdicts\"] === undefined ||\n (Array.isArray(value[\"verdicts\"]) &&\n value[\"verdicts\"].every(isSessionVerdict))) &&\n (value[\"failed\"] === undefined ||\n (Array.isArray(value[\"failed\"]) && value[\"failed\"].every(isFailedCommand)));\n\nconst loadStored = <T>(\n key: string,\n validate: (value: unknown) => value is T,\n): T | null => {\n const raw = localStorage.getItem(key);\n if (raw === null) return null;\n try {\n const value: unknown = JSON.parse(raw);\n if (validate(value)) return value;\n } catch {}\n localStorage.removeItem(key);\n return null;\n};\n\nconst sweep = (ttl: number, max: number) => {\n const entries: { key: string; ts: number }[] = [];\n const keys = Array.from({ length: localStorage.length }, (_, index) =>\n localStorage.key(index),\n );\n for (const key of keys) {\n if (key === null || !key.startsWith(PREFIX)) continue;\n const stored = loadStored(key, isStoredDraft);\n if (stored !== null) entries.push({ key, ts: stored.ts });\n }\n const now = Date.now();\n const fresh = entries.filter(({ key, ts }) => {\n if (now - ts <= ttl) return true;\n localStorage.removeItem(key);\n return false;\n });\n fresh.sort((a, b) => b.ts - a.ts);\n for (const { key } of fresh.slice(max)) localStorage.removeItem(key);\n};\n\nconst useLocalStorageComposerDrafts = ({\n threadId,\n key = (id) => id,\n ttl = 7 * DAY,\n max = 50,\n}: LocalStorageComposerDrafts.Options): StatewireThread.ComposerStorage => {\n if (typeof localStorage === \"undefined\")\n throw new Error(\n \"statewire: LocalStorageComposerDrafts requires localStorage\",\n );\n\n useEffect(() => {\n sweep(ttl, max);\n }, [ttl, max]);\n\n const storageKey = PREFIX + key(threadId);\n return useMemo(\n (): StatewireThread.ComposerStorage => ({\n read: () => {\n const stored = loadStored(storageKey, isStoredDraft);\n if (stored === null) return undefined;\n return { text: stored.text, attachments: stored.attachments };\n },\n write: (draft) => {\n if (draft.text === \"\" && draft.attachments.length === 0) {\n localStorage.removeItem(storageKey);\n return;\n }\n localStorage.setItem(\n storageKey,\n JSON.stringify({ ...draft, ts: Date.now() }),\n );\n },\n clear: () => {\n localStorage.removeItem(storageKey);\n },\n }),\n [storageKey],\n );\n};\n\n/** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */\nexport const LocalStorageComposerDrafts = resource(\n useLocalStorageComposerDrafts,\n);\n\nconst SESSION_LOCK_PREFIX = \"aui:statewire-session-lock:\";\n\nconst useLocalStorageSession = ({\n threadId,\n migrate,\n key = (id) => id,\n}: LocalStorageSession.Options): StatewireClient.SessionStorage => {\n if (typeof localStorage === \"undefined\")\n throw new Error(\"statewire: LocalStorageSession requires localStorage\");\n // localStorage is shared across tabs: record mutations must serialize.\n if (typeof navigator === \"undefined\" || navigator.locks === undefined)\n throw new Error(\n \"statewire: LocalStorageSession requires the Web Locks API (navigator.locks)\",\n );\n\n const storageKey = SESSION_PREFIX + key(threadId);\n const lockName = SESSION_LOCK_PREFIX + key(threadId);\n return useMemo(\n (): StatewireClient.SessionStorage => ({\n load: () => {\n return loadStored(storageKey, isSessionRecord);\n },\n save: (record) => {\n localStorage.setItem(storageKey, JSON.stringify(record));\n },\n ...(migrate !== undefined && { migrate }),\n lock: (fn) => navigator.locks.request(lockName, async () => fn()),\n subscribe: (listener) => {\n const onStorage = (event: StorageEvent) => {\n if (event.key === storageKey) listener();\n };\n window.addEventListener(\"storage\", onStorage);\n return () => window.removeEventListener(\"storage\", onStorage);\n },\n }),\n [storageKey, lockName, migrate],\n );\n};\n\n/** Session storage on localStorage, keyed per thread: the lane identity plus the commands awaiting a durable verdict; sharers serialize through a per-key Web Lock. */\nexport const LocalStorageSession = resource(useLocalStorageSession);\n\nexport namespace LocalStorageSession {\n export type Options = {\n /** Upgrade incompatible queued commands, or return null to discard the saved session. */\n migrate?: StatewireClient.SessionStorage[\"migrate\"];\n /** The thread whose session this storage holds. */\n threadId: string;\n /** Derives the storage key from the thread id; defaults to the id itself. */\n key?: ((threadId: string) => string) | undefined;\n };\n}\n\nexport namespace LocalStorageComposerDrafts {\n export type Options = {\n /** The thread whose draft this storage holds. */\n threadId: string;\n /** Derives the storage key from the thread id; defaults to the id itself. */\n key?: ((threadId: string) => string) | undefined;\n /** Draft lifetime in milliseconds, enforced by the mount sweep. Default 7 days. */\n ttl?: number | undefined;\n /** Newest drafts kept across all keys, enforced by the mount sweep. Default 50. */\n max?: number | undefined;\n };\n}\n"],"mappings":";;;AAKA,MAAMK,SAAS;AACf,MAAMC,iBAAiB;AACvB,MAAMC,MAAM;AAQZ,MAAMM,YAAYC,UAChB,OAAOA,UAAU,YAAYA,UAAU,QAAQ,CAACE,MAAMC,QAAQH,KAAK;AAErE,MAAMI,oBAAoBJ,UACxBA,UAAUK,KAAAA,KAAa,OAAOL,UAAU;AAE1C,MAAMM,qBAAqBN,UAA4B;CACrD,IAAI,CAACD,SAASC,KAAK,GAAG,OAAO;CAC7B,QAAQA,MAAM,SAAd;EACE,KAAK,QACH,OAAO,OAAOA,MAAM,YAAY;EAClC,KAAK,SACH,OACE,OAAOA,MAAM,aAAa,YAC1BI,iBAAiBJ,MAAM,WAAW;EAEtC,KAAK,QACH,OACE,OAAOA,MAAM,YAAY,YACzB,OAAOA,MAAM,gBAAgB,YAC7BI,iBAAiBJ,MAAM,WAAW;EAEtC,KAAK,QACH,OAAO,OAAOA,MAAM,YAAY;EAClC,KAAK,SAAS;GACZ,MAAMO,QAAQP,MAAM;GACpB,OACED,SAASQ,KAAK,KACd,OAAOA,MAAM,YAAY,aACxBA,MAAM,cAAc,SAASA,MAAM,cAAc;EAEtD;EACA,SACE,OAAO;CACX;AACF;AAIA,MAAME,sBAAsBT,UAA8C;CACxE,IAAI,CAACD,SAASC,KAAK,GAAG,OAAO;CAC7B,MAAMU,SAASV,MAAM;CACrB,OACE,OAAOA,MAAM,UAAU,YACvB,OAAOA,MAAM,YAAY,YACzB,OAAOA,MAAM,YAAY,YACzBI,iBAAiBJ,MAAM,cAAc,KACrCA,MAAM,YAAYK,KAAAA,KAClBN,SAASW,MAAM,KACfA,OAAO,YAAY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AAU,CACb;AACF;;AAGA,MAAaJ,6BAA6BxE,SACxCqE,6BACF;AAEA,MAAMc,sBAAsB;AAE5B,MAAMC,0BAA0B,EAC9Bd,UACAe,SACA7C,OAAO+B,OAAOA,SACmD;CACjE,IAAI,OAAO3B,iBAAiB,aAC1B,MAAM,IAAI+B,MAAM,sDAAsD;CAExE,IAAI,OAAOa,cAAc,eAAeA,UAAUC,UAAUxE,KAAAA,GAC1D,MAAM,IAAI0D,MACR,6EACF;CAEF,MAAMC,aAAaxE,iBAAiBoC,IAAI8B,QAAQ;CAChD,MAAMoB,WAAWP,sBAAsB3C,IAAI8B,QAAQ;CACnD,OAAOvE,eACkC;EACrC4F,YAAY;GACV,OAAOpD,WAAWqC,YAAYvC,eAAe;EAC/C;EACAuD,OAAOC,WAAW;GAChBjD,aAAaoC,QAAQJ,YAAY9B,KAAKmC,UAAUY,MAAM,CAAC;EACzD;EACA,GAAIR,YAAYpE,KAAAA,KAAa,EAAEoE,QAAQ;EACvCS,OAAOC,OAAOP,UAAUC,MAAMO,QAAQN,UAAU,YAAYK,GAAG,CAAC;EAChEE,YAAYC,aAAa;GACvB,MAAMC,aAAaC,UAAwB;IACzC,IAAIA,MAAM5D,QAAQoC,YAAYsB,SAAS;GACzC;GACAI,OAAOC,iBAAiB,WAAWJ,SAAS;GAC5C,aAAaG,OAAOE,oBAAoB,WAAWL,SAAS;EAC9D;CACF,IACA;EAACvB;EAAYc;EAAUL;CAAO,CAChC;AACF;;AAGA,MAAaC,sBAAsBtF,SAASoF,sBAAsB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/react-statewire",
3
- "version": "0.26.0",
3
+ "version": "0.27.1",
4
4
  "description": "assistant-ui thread binding for statewire backends",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -38,7 +38,7 @@
38
38
  "@assistant-ui/store": "^0.3.0",
39
39
  "@assistant-ui/tap": "^0.9.7",
40
40
  "assistant-stream": "^0.3.37",
41
- "statewire": "^0.16.0"
41
+ "statewire": "^0.17.0"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "@assistant-ui/core": ">=0.3.12",
@@ -89,12 +89,18 @@ const createSettlingServer = (init?: Partial<ServerState>) => {
89
89
  frame({
90
90
  ops: [
91
91
  {
92
- op: "replace",
93
- path: [],
92
+ op: "mount",
93
+ protocol: "default",
94
+ main: true,
94
95
  value: { ...INITIAL_STATE, ...init },
95
96
  },
96
97
  ],
97
- syn: { seq: rec.seq, ctxSeq: rec.ctxSeq },
98
+ syn: {
99
+ seq: rec.seq,
100
+ ctxSeq: rec.ctxSeq,
101
+ version: "2026-09-07",
102
+ protocols: [{ name: "default", version: "2026-09-07" }],
103
+ },
98
104
  }),
99
105
  ),
100
106
  );
@@ -183,12 +183,18 @@ const createRemoteServer = (
183
183
  frame({
184
184
  ops: [
185
185
  {
186
- op: "replace",
187
- path: [],
186
+ op: "mount",
187
+ protocol: "default",
188
+ main: true,
188
189
  value: { ...INITIAL_STATE, ...init },
189
190
  },
190
191
  ],
191
- syn: { seq: rec.seq, ctxSeq: rec.ctxSeq },
192
+ syn: {
193
+ seq: rec.seq,
194
+ ctxSeq: rec.ctxSeq,
195
+ version: "2026-09-07",
196
+ protocols: [{ name: "default", version: "2026-09-07" }],
197
+ },
192
198
  }),
193
199
  ),
194
200
  );
@@ -415,6 +415,37 @@ describe("StatewireThread", () => {
415
415
  await waitFor(() => expect(metas.at(-1)!.pendingCommands).toEqual([]));
416
416
  });
417
417
 
418
+ it("discards an unprojected rejection once when another command triggers a render", async () => {
419
+ const mock = createMockTransport<ServerState>(INITIAL_STATE);
420
+ const errors: Error[] = [];
421
+ const { aui } = mountThread({
422
+ transport: mock.transport,
423
+ converter,
424
+ onError: (error) => errors.push(error),
425
+ });
426
+ await waitFor(() => expect(threadStatus(aui())).toBe("ready"));
427
+ const send = () =>
428
+ sendCommand(aui, {
429
+ type: "run/input",
430
+ requestId: "request",
431
+ response: { type: "resume", value: {} },
432
+ });
433
+ act(() => {
434
+ send();
435
+ });
436
+ await waitFor(() => expect(mock.commands).toHaveLength(1));
437
+ await act(async () => {
438
+ await mock.sendEnvelope({
439
+ cmd: [{ seq: 1, type: "rejected", message: "retry" }],
440
+ });
441
+ });
442
+ await waitFor(() => expect(errors).toHaveLength(1));
443
+ act(() => {
444
+ send();
445
+ });
446
+ await waitFor(() => expect(mock.commands).toHaveLength(2));
447
+ });
448
+
418
449
  it("reports the command lifecycle through onCommandChange after retiring the pending command", async () => {
419
450
  const server = createServer();
420
451
  const updates: Statewire.CommandUpdate<
@@ -173,10 +173,17 @@ const useStatewireThread = (
173
173
  },
174
174
  });
175
175
 
176
- // Failures the thread cannot project stay onError-only, as before the lane.
176
+ const discarded = useRef(new WeakSet<StatewireClient.FailedCommand>());
177
+ // Effects can replay before the updated failed lane reaches the binding.
177
178
  useEffect(() => {
178
179
  for (const entry of failed) {
179
- if (failedRunCommand(entry) === undefined) discardFailed(entry);
180
+ if (
181
+ failedRunCommand(entry) === undefined &&
182
+ !discarded.current.has(entry)
183
+ ) {
184
+ discarded.current.add(entry);
185
+ discardFailed(entry);
186
+ }
180
187
  }
181
188
  }, [failed, discardFailed]);
182
189
 
@@ -172,6 +172,7 @@ describe("LocalStorageSession", () => {
172
172
  commands: [
173
173
  {
174
174
  seq: 2,
175
+ protocol: "default",
175
176
  method: "run/steer",
176
177
  params: [{ text: "hi" }],
177
178
  meta: { requestId: "r-2" },
@@ -245,6 +245,7 @@ const SESSION_LOCK_PREFIX = "aui:statewire-session-lock:";
245
245
 
246
246
  const useLocalStorageSession = ({
247
247
  threadId,
248
+ migrate,
248
249
  key = (id) => id,
249
250
  }: LocalStorageSession.Options): StatewireClient.SessionStorage => {
250
251
  if (typeof localStorage === "undefined")
@@ -265,6 +266,7 @@ const useLocalStorageSession = ({
265
266
  save: (record) => {
266
267
  localStorage.setItem(storageKey, JSON.stringify(record));
267
268
  },
269
+ ...(migrate !== undefined && { migrate }),
268
270
  lock: (fn) => navigator.locks.request(lockName, async () => fn()),
269
271
  subscribe: (listener) => {
270
272
  const onStorage = (event: StorageEvent) => {
@@ -274,7 +276,7 @@ const useLocalStorageSession = ({
274
276
  return () => window.removeEventListener("storage", onStorage);
275
277
  },
276
278
  }),
277
- [storageKey, lockName],
279
+ [storageKey, lockName, migrate],
278
280
  );
279
281
  };
280
282
 
@@ -283,6 +285,8 @@ export const LocalStorageSession = resource(useLocalStorageSession);
283
285
 
284
286
  export namespace LocalStorageSession {
285
287
  export type Options = {
288
+ /** Upgrade incompatible queued commands, or return null to discard the saved session. */
289
+ migrate?: StatewireClient.SessionStorage["migrate"];
286
290
  /** The thread whose session this storage holds. */
287
291
  threadId: string;
288
292
  /** Derives the storage key from the thread id; defaults to the id itself. */