@assistant-ui/react-statewire 0.27.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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"}
@@ -27,7 +27,7 @@ const failedRunCommand = (entry) => {
27
27
  if (command?.message === void 0) return void 0;
28
28
  return command;
29
29
  };
30
- const presentStatus = (status, connection) => status !== "running" || connection.status === "connected" || connection.status === "disconnected" && connection.reason === "idle" ? status : connection.status === "connecting" && connection.cause === "reconnect" && connection.code === "evicted" ? "evicted" : "disconnected";
30
+ const presentStatus = (status, connection) => status !== "running" || connection.status === "connected" || connection.status === "standby" && connection.reason === "idle" ? status : connection.status === "retrying" && connection.cause === "reconnect" && connection.code === "evicted" ? "evicted" : "disconnected";
31
31
  const ambientContextOf = (context) => ({
32
32
  ...context.system !== void 0 && { system: context.system },
33
33
  ...context.tools !== void 0 && { tools: toToolsJSONSchema(context.tools) },
@@ -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,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,QA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;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 === \"standby\" && connection.reason === \"idle\")\n ? status\n : connection.status === \"retrying\" &&\n connection.cause === \"reconnect\" &&\n connection.code === \"evicted\"\n ? \"evicted\"\n : \"disconnected\";\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\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,aAAaE,WAAWE,WAAW,SACtDJ,SACAE,WAAWF,WAAW,cAC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B;CACA,MAAM,CAACM,aAAarO,gBAAgB,EAAEsO,YAAYvK,KAAAA,EAAqB,EAAE;CACzElE,gBAAgB;EACd,MAAMwG,YAAUiH;EAChB,IAAIjH,cAAYtC,KAAAA,GAAW;EAG3B,MAAMwK,aAAaF,UAAUC,eAAejI;EAC5CgI,UAAUC,aAAajI;EACvB,IAAIyH,cAAc,MAAME,iBAAiBpE,WAAW,GAAG;GACrD,IAAI,CAAC2E,YAAYlI,UAAQmI,MAAM;GAC/B;EACF;EACAnI,UAAQoI,MAAM;GAAE5F,MAAMiF;GAAW/B,aAAaiC;EAAiB,CAAC;CAClE,GAAG;EAACK;EAAWf;EAAiBQ;EAAWE;CAAgB,CAAC;CAE5D,OAAOrC;AACT;AAEA,MAAahJ,mBACXsC,YAEAhF,SAAS+E,kBAAkB,CAAC,CAACC,OAAuC;AA8ZtExE,uBACEuE,oBACA1E,eAAeyD,KAAAA,CAAkB,CAAC,CAACsP,IACrC"}
@@ -1,5 +1,6 @@
1
1
  import { StatewireThread } from "./StatewireThread.js";
2
2
  import { StatewireClient } from "statewire";
3
+ import { KeyValueSessionStorage } from "statewire/storage";
3
4
  //#region src/localStorage.d.ts
4
5
  /** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */
5
6
  declare const LocalStorageComposerDrafts: import("@assistant-ui/tap").Resource<StatewireThread.ComposerStorage, [LocalStorageComposerDrafts.Options]>;
@@ -7,6 +8,9 @@ declare const LocalStorageComposerDrafts: import("@assistant-ui/tap").Resource<S
7
8
  declare const LocalStorageSession: import("@assistant-ui/tap").Resource<StatewireClient.SessionStorage, [LocalStorageSession.Options]>;
8
9
  declare namespace LocalStorageSession {
9
10
  type Options = {
11
+ legacyProtocol?: KeyValueSessionStorage.Options["legacyProtocol"];
12
+ retention?: KeyValueSessionStorage.Options["retention"];
13
+ onError?: KeyValueSessionStorage.Options["onError"];
10
14
  /** Upgrade incompatible queued commands, or return null to discard the saved session. */
11
15
  migrate?: StatewireClient.SessionStorage["migrate"];
12
16
  /** The thread whose session this storage holds. */
@@ -1 +1 @@
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"}
1
+ {"version":3,"file":"localStorage.d.ts","names":[],"sources":["../src/localStorage.ts"],"mappings":";;;;;cA2Ja,wDAA0B,SAAA,gBAAA,kBAAA,2BAAA;;cA2F1B,iDAAmB,SAAA,gBAAA,iBAAA,oBAAA;kBAEf;OACH;IACV,iBAAiB,uBAAuB;IACxC,YAAY,uBAAuB;IACnC,UAAU,uBAAuB;;IAEjC,UAAU,gBAAgB;;IAE1B;;IAEA,QAAQ;;;kBAIK;OACH;;IAEV;;IAEA,QAAQ;;IAER;;IAEA"}
@@ -1,5 +1,6 @@
1
1
  import { useEffect, useMemo } from "@assistant-ui/tap/react-shim";
2
- import { resource } from "@assistant-ui/tap";
2
+ import { resource, useResource } from "@assistant-ui/tap";
3
+ import { KeyValueSessionStorage } from "statewire/storage";
3
4
  //#region src/localStorage.ts
4
5
  const PREFIX = "aui:composer-draft:";
5
6
  const SESSION_PREFIX = "aui:statewire-session:";
@@ -26,23 +27,6 @@ const isStoredAttachment = (value) => {
26
27
  return typeof value["id"] === "string" && typeof value["type"] === "string" && typeof value["name"] === "string" && isOptionalString(value["contentType"]) && value["file"] === void 0 && isRecord(status) && status["type"] === "complete" && Array.isArray(value["content"]) && value["content"].every(isUserMessagePart);
27
28
  };
28
29
  const isStoredDraft = (value) => isRecord(value) && typeof value["text"] === "string" && Array.isArray(value["attachments"]) && value["attachments"].every(isStoredAttachment) && typeof value["ts"] === "number" && Number.isFinite(value["ts"]);
29
- const isPositiveSafeInteger = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
30
- const isSessionCommand = (value) => isRecord(value) && isPositiveSafeInteger(value["seq"]) && typeof value["method"] === "string" && Array.isArray(value["params"]);
31
- const isSessionVerdict = (value) => isRecord(value) && isPositiveSafeInteger(value["seq"]) && (value["type"] === "result" || value["type"] === "rejected" || value["type"] === "failed" || value["type"] === "crashed" || value["type"] === "expired") && isOptionalString(value["code"]) && isOptionalString(value["message"]);
32
- const isSendFailure = (value) => {
33
- if (!isRecord(value)) return false;
34
- switch (value["fate"]) {
35
- case "rejected": return value["cause"] === "server" && isOptionalString(value["code"]) && isOptionalString(value["message"]);
36
- case "failed": return value["cause"] === "server" && isOptionalString(value["message"]);
37
- case "crashed":
38
- case "expired": return value["cause"] === "server";
39
- case "aborted": return (value["cause"] === "unmount" || value["cause"] === "stream-gone" || value["cause"] === "session-lost") && (value["predecessorLost"] === void 0 || value["predecessorLost"] === true);
40
- case "lost": return value["cause"] === "unmount" || value["cause"] === "stream-gone" || value["cause"] === "session-lost";
41
- default: return false;
42
- }
43
- };
44
- const isFailedCommand = (value) => isRecord(value) && typeof value["command"] === "string" && Array.isArray(value["params"]) && isSendFailure(value["failure"]) && typeof value["ts"] === "number" && Number.isFinite(value["ts"]) && isPositiveSafeInteger(value["seq"]);
45
- const isSessionRecord = (value) => isRecord(value) && typeof value["clientId"] === "string" && isPositiveSafeInteger(value["nextSeq"]) && isPositiveSafeInteger(value["ctxNextSeq"]) && Array.isArray(value["commands"]) && value["commands"].every(isSessionCommand) && (value["verdicts"] === void 0 || Array.isArray(value["verdicts"]) && value["verdicts"].every(isSessionVerdict)) && (value["failed"] === void 0 || Array.isArray(value["failed"]) && value["failed"].every(isFailedCommand));
46
30
  const loadStored = (key, validate) => {
47
31
  const raw = localStorage.getItem(key);
48
32
  if (raw === null) return null;
@@ -106,19 +90,44 @@ const useLocalStorageComposerDrafts = ({ threadId, key = (id) => id, ttl = 7 * D
106
90
  /** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */
107
91
  const LocalStorageComposerDrafts = resource(useLocalStorageComposerDrafts);
108
92
  const SESSION_LOCK_PREFIX = "aui:statewire-session-lock:";
109
- const useLocalStorageSession = ({ threadId, migrate, key = (id) => id }) => {
93
+ const SESSION_ACTIVE_PREFIX = "aui:statewire-session-active:";
94
+ const sessionBackend = {
95
+ getItem: (key) => localStorage.getItem(key),
96
+ setItem: (key, value) => localStorage.setItem(key, value),
97
+ removeItem: (key) => localStorage.removeItem(key),
98
+ getAllKeys: () => Array.from({ length: localStorage.length }, (_, index) => localStorage.key(index)).filter((key) => key !== null),
99
+ withUnused: (key, action) => navigator.locks.request(SESSION_ACTIVE_PREFIX + key, { ifAvailable: true }, (lock) => lock === null ? void 0 : navigator.locks.request(SESSION_LOCK_PREFIX + key.slice(22), { ifAvailable: true }, (lock) => lock === null ? void 0 : action()))
100
+ };
101
+ const useLocalStorageSession = ({ threadId, migrate, key = (id) => id, legacyProtocol, retention, onError }) => {
110
102
  if (typeof localStorage === "undefined") throw new Error("statewire: LocalStorageSession requires localStorage");
111
103
  if (typeof navigator === "undefined" || navigator.locks === void 0) throw new Error("statewire: LocalStorageSession requires the Web Locks API (navigator.locks)");
112
104
  const storageKey = SESSION_PREFIX + key(threadId);
113
105
  const lockName = SESSION_LOCK_PREFIX + key(threadId);
106
+ useEffect(() => {
107
+ let release;
108
+ let disposed = false;
109
+ navigator.locks.request(SESSION_ACTIVE_PREFIX + storageKey, { mode: "shared" }, () => {
110
+ if (disposed) return;
111
+ return new Promise((resolve) => {
112
+ release = resolve;
113
+ });
114
+ }).catch((error) => onError?.(error));
115
+ return () => {
116
+ disposed = true;
117
+ release?.();
118
+ };
119
+ }, [storageKey, onError]);
120
+ const storage = useResource(KeyValueSessionStorage({
121
+ backend: sessionBackend,
122
+ key: key(threadId),
123
+ namespace: SESSION_PREFIX,
124
+ ...migrate === void 0 ? {} : { migrate },
125
+ ...legacyProtocol === void 0 ? {} : { legacyProtocol },
126
+ ...retention === void 0 ? {} : { retention },
127
+ ...onError === void 0 ? {} : { onError }
128
+ }));
114
129
  return useMemo(() => ({
115
- load: () => {
116
- return loadStored(storageKey, isSessionRecord);
117
- },
118
- save: (record) => {
119
- localStorage.setItem(storageKey, JSON.stringify(record));
120
- },
121
- ...migrate !== void 0 && { migrate },
130
+ ...storage,
122
131
  lock: (fn) => navigator.locks.request(lockName, async () => fn()),
123
132
  subscribe: (listener) => {
124
133
  const onStorage = (event) => {
@@ -128,9 +137,9 @@ const useLocalStorageSession = ({ threadId, migrate, key = (id) => id }) => {
128
137
  return () => window.removeEventListener("storage", onStorage);
129
138
  }
130
139
  }), [
140
+ storage,
131
141
  storageKey,
132
- lockName,
133
- migrate
142
+ lockName
134
143
  ]);
135
144
  };
136
145
  /** 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. */
@@ -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","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,sBA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.js","names":["useEffect","useMemo","resource","useResource","KeyValueSessionStorage","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","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","SESSION_ACTIVE_PREFIX","sessionBackend","Backend","getAllKeys","withUnused","action","navigator","locks","request","ifAvailable","lock","useLocalStorageSession","migrate","legacyProtocol","retention","onError","LocalStorageSession","SessionStorage","lockName","release","disposed","mode","Promise","resolve","catch","error","storage","backend","namespace","fn","subscribe","listener","onStorage","event","StorageEvent","window","addEventListener","removeEventListener"],"sources":["../src/localStorage.ts"],"sourcesContent":["import { useEffect, useMemo } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport { KeyValueSessionStorage } from \"statewire/storage\";\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 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 SESSION_ACTIVE_PREFIX = \"aui:statewire-session-active:\";\n\nconst sessionBackend: KeyValueSessionStorage.Backend = {\n getItem: (key) => localStorage.getItem(key),\n setItem: (key, value) => localStorage.setItem(key, value),\n removeItem: (key) => localStorage.removeItem(key),\n getAllKeys: () =>\n Array.from({ length: localStorage.length }, (_, index) =>\n localStorage.key(index),\n ).filter((key): key is string => key !== null),\n withUnused: (key, action) =>\n navigator.locks.request(\n SESSION_ACTIVE_PREFIX + key,\n { ifAvailable: true },\n (lock) =>\n lock === null\n ? undefined\n : navigator.locks.request(\n SESSION_LOCK_PREFIX + key.slice(SESSION_PREFIX.length),\n { ifAvailable: true },\n (lock) => (lock === null ? undefined : action()),\n ),\n ),\n};\n\nconst useLocalStorageSession = ({\n threadId,\n migrate,\n key = (id) => id,\n legacyProtocol,\n retention,\n onError,\n}: LocalStorageSession.Options): StatewireClient.SessionStorage => {\n if (typeof localStorage === \"undefined\")\n throw new Error(\"statewire: LocalStorageSession requires localStorage\");\n if (typeof navigator === \"undefined\" || navigator.locks === undefined)\n throw new Error(\n \"statewire: LocalStorageSession requires the Web Locks API (navigator.locks)\",\n );\n const storageKey = SESSION_PREFIX + key(threadId);\n const lockName = SESSION_LOCK_PREFIX + key(threadId);\n useEffect(() => {\n let release: (() => void) | undefined;\n let disposed = false;\n void navigator.locks\n .request(SESSION_ACTIVE_PREFIX + storageKey, { mode: \"shared\" }, () => {\n if (disposed) return;\n return new Promise<void>((resolve) => {\n release = resolve;\n });\n })\n .catch((error: unknown) => onError?.(error));\n return () => {\n disposed = true;\n release?.();\n };\n }, [storageKey, onError]);\n const storage = useResource(\n KeyValueSessionStorage({\n backend: sessionBackend,\n key: key(threadId),\n namespace: SESSION_PREFIX,\n ...(migrate === undefined ? {} : { migrate }),\n ...(legacyProtocol === undefined ? {} : { legacyProtocol }),\n ...(retention === undefined ? {} : { retention }),\n ...(onError === undefined ? {} : { onError }),\n }),\n );\n return useMemo(\n (): StatewireClient.SessionStorage => ({\n ...storage,\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 [storage, 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 legacyProtocol?: KeyValueSessionStorage.Options[\"legacyProtocol\"];\n retention?: KeyValueSessionStorage.Options[\"retention\"];\n onError?: KeyValueSessionStorage.Options[\"onError\"];\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":";;;;AAMA,MAAMO,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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AO,CAAC;CACxB,MAAMW,UAAUnG,YACdC,uBAAuB;EACrBmG,SAAS1B;EACT7C,KAAKA,IAAI8B,QAAQ;EACjB0C,WAAWhG;EACX,GAAIgF,YAAYnE,KAAAA,IAAY,CAAC,IAAI,EAAEmE,QAAQ;EAC3C,GAAIC,mBAAmBpE,KAAAA,IAAY,CAAC,IAAI,EAAEoE,eAAe;EACzD,GAAIC,cAAcrE,KAAAA,IAAY,CAAC,IAAI,EAAEqE,UAAU;EAC/C,GAAIC,YAAYtE,KAAAA,IAAY,CAAC,IAAI,EAAEsE,QAAQ;CAC7C,CAAC,CACH;CACA,OAAO1F,eACkC;EACrC,GAAGqG;EACHhB,OAAOmB,OAAOvB,UAAUC,MAAMC,QAAQU,UAAU,YAAYW,GAAG,CAAC;EAChEC,YAAYC,aAAa;GACvB,MAAMC,aAAaC,UAAwB;IACzC,IAAIA,MAAM7E,QAAQoC,YAAYuC,SAAS;GACzC;GACAI,OAAOC,iBAAiB,WAAWJ,SAAS;GAC5C,aAAaG,OAAOE,oBAAoB,WAAWL,SAAS;EAC9D;CACF,IACA;EAACN;EAASlC;EAAY0B;CAAQ,CAChC;AACF;;AAGA,MAAaF,sBAAsB1F,SAASqF,sBAAsB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/react-statewire",
3
- "version": "0.27.0",
3
+ "version": "0.28.0",
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.17.0"
41
+ "statewire": "^0.18.0"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "@assistant-ui/core": ">=0.3.12",
@@ -936,7 +936,7 @@ describe("StatewireThread connection presentation", () => {
936
936
  await waitFor(() => expect(threadStatus(aui())).toBe(status));
937
937
  server.fin("error");
938
938
 
939
- await waitFor(() => expect(statuses).toContain("connecting"));
939
+ await waitFor(() => expect(statuses).toContain("retrying"));
940
940
  expect(threadStatus(aui())).toBe(status);
941
941
  },
942
942
  );
@@ -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<
@@ -564,11 +595,9 @@ describe("StatewireThread", () => {
564
595
 
565
596
  await waitFor(() => expect(statuses).toEqual(["connected"]));
566
597
  await mock.finish("gone");
567
- await waitFor(() =>
568
- expect(statuses).toEqual(["connected", "disconnected"]),
569
- );
598
+ await waitFor(() => expect(statuses).toEqual(["connected", "stopped"]));
570
599
  await new Promise((r) => setTimeout(r, 20));
571
- expect(statuses).toEqual(["connected", "disconnected"]);
600
+ expect(statuses).toEqual(["connected", "stopped"]);
572
601
  });
573
602
 
574
603
  it("stays quiet on unrelated re-renders and callback identity changes", async () => {
@@ -1296,7 +1325,7 @@ describe("StatewireThread", () => {
1296
1325
  expect(seen).toEqual(["connecting", "connected"]);
1297
1326
 
1298
1327
  await mock.finish("gone", "taken over");
1299
- await waitFor(() => expect(seen.at(-1)).toBe("disconnected"));
1328
+ await waitFor(() => expect(seen.at(-1)).toBe("stopped"));
1300
1329
  });
1301
1330
 
1302
1331
  it("reports connected without re-converting on a local transport", async () => {
@@ -1320,7 +1349,7 @@ describe("StatewireThread", () => {
1320
1349
 
1321
1350
  await waitFor(() => expect(threadStatus(aui())).toBe("ready"));
1322
1351
  await mock.finish("gone");
1323
- await waitFor(() => expect(seen.at(-1)).toBe("disconnected"));
1352
+ await waitFor(() => expect(seen.at(-1)).toBe("stopped"));
1324
1353
 
1325
1354
  asStatewireExtras(aui().thread().getState().extras).reconnect();
1326
1355
 
@@ -101,9 +101,9 @@ const presentStatus = (
101
101
  ): StatewireThread.ThreadStatus =>
102
102
  status !== "running" ||
103
103
  connection.status === "connected" ||
104
- (connection.status === "disconnected" && connection.reason === "idle")
104
+ (connection.status === "standby" && connection.reason === "idle")
105
105
  ? status
106
- : connection.status === "connecting" &&
106
+ : connection.status === "retrying" &&
107
107
  connection.cause === "reconnect" &&
108
108
  connection.code === "evicted"
109
109
  ? "evicted"
@@ -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
 
@@ -141,7 +141,14 @@ describe("LocalStorageSession", () => {
141
141
  Object.defineProperty(navigator, "locks", {
142
142
  configurable: true,
143
143
  value: {
144
- request: (name: string, cb: () => Promise<unknown>) => {
144
+ request: (
145
+ name: string,
146
+ options: (() => Promise<unknown>) | object,
147
+ callback?: () => Promise<unknown>,
148
+ ) => {
149
+ const cb = typeof options === "function" ? options : callback!;
150
+ if (name.startsWith("aui:statewire-session-active:"))
151
+ return Promise.resolve().then(() => cb());
145
152
  requested.push(name);
146
153
  const run = chain.then(() => cb());
147
154
  chain = run.then(
@@ -180,14 +187,16 @@ describe("LocalStorageSession", () => {
180
187
  ],
181
188
  };
182
189
  root.getValue().save(record);
183
- expect(JSON.parse(localStorage.getItem(`${SESSION_PREFIX}t1`)!)).toEqual(
184
- record,
185
- );
190
+ expect(JSON.parse(localStorage.getItem(`${SESSION_PREFIX}t1`)!)).toEqual({
191
+ ...record,
192
+ statewireStorageVersion: 1,
193
+ savedAt: expect.any(Number),
194
+ });
186
195
  expect(root.getValue().load()).toEqual(record);
187
196
  root.unmount();
188
197
  });
189
198
 
190
- it("discards malformed session records during load", () => {
199
+ it("rejects malformed session records without deleting them", () => {
191
200
  const root = mountSession({ threadId: "t1" });
192
201
  for (const raw of [
193
202
  "{",
@@ -227,8 +236,8 @@ describe("LocalStorageSession", () => {
227
236
  }),
228
237
  ]) {
229
238
  localStorage.setItem(`${SESSION_PREFIX}t1`, raw);
230
- expect(root.getValue().load()).toBeNull();
231
- expect(localStorage.getItem(`${SESSION_PREFIX}t1`)).toBeNull();
239
+ expect(() => root.getValue().load()).toThrow();
240
+ expect(localStorage.getItem(`${SESSION_PREFIX}t1`)).toBe(raw);
232
241
  }
233
242
  root.unmount();
234
243
  });
@@ -289,6 +298,60 @@ describe("LocalStorageSession", () => {
289
298
  root.unmount();
290
299
  });
291
300
 
301
+ it("skips other tabs' active sessions and busy record locks during retention", async () => {
302
+ const prefix = "aui:statewire-session-active:";
303
+ const keys = ["other-active", "other-writing", "unused"];
304
+ for (const key of keys)
305
+ localStorage.setItem(
306
+ `${SESSION_PREFIX}${key}`,
307
+ JSON.stringify({
308
+ clientId: key,
309
+ nextSeq: 1,
310
+ ctxNextSeq: 1,
311
+ commands: [],
312
+ savedAt: 1,
313
+ }),
314
+ );
315
+ const calls: { name: string; options: LockOptions | undefined }[] = [];
316
+ const request = (
317
+ name: string,
318
+ options: LockOptions | LockGrantedCallback<unknown>,
319
+ callback?: LockGrantedCallback<unknown>,
320
+ ) => {
321
+ const args = typeof options === "function" ? undefined : options;
322
+ const fn = typeof options === "function" ? options : callback!;
323
+ calls.push({ name, options: args });
324
+ const unavailable =
325
+ name === `${prefix}${SESSION_PREFIX}other-active` ||
326
+ name === `${SESSION_LOCK_PREFIX}other-writing`;
327
+ return Promise.resolve().then(() =>
328
+ fn(unavailable ? null : ({} as Lock)),
329
+ );
330
+ };
331
+ Object.defineProperty(navigator, "locks", {
332
+ configurable: true,
333
+ value: { request },
334
+ });
335
+ const root = mountSession({
336
+ threadId: "current",
337
+ retention: { maxAgeMs: 1 },
338
+ });
339
+ await vi.waitFor(() =>
340
+ expect(localStorage.getItem(`${SESSION_PREFIX}unused`)).toBeNull(),
341
+ );
342
+ expect(
343
+ localStorage.getItem(`${SESSION_PREFIX}other-active`),
344
+ ).not.toBeNull();
345
+ expect(
346
+ localStorage.getItem(`${SESSION_PREFIX}other-writing`),
347
+ ).not.toBeNull();
348
+ expect(
349
+ calls.find(({ name }) => name === `${SESSION_LOCK_PREFIX}other-writing`)
350
+ ?.options,
351
+ ).toEqual({ ifAvailable: true });
352
+ root.unmount();
353
+ });
354
+
292
355
  it("throws without localStorage", () => {
293
356
  vi.stubGlobal("localStorage", undefined);
294
357
  expect(() => mountSession({ threadId: "t1" })).toThrow(
@@ -1,5 +1,6 @@
1
1
  import { useEffect, useMemo } from "react";
2
- import { resource } from "@assistant-ui/tap";
2
+ import { resource, useResource } from "@assistant-ui/tap";
3
+ import { KeyValueSessionStorage } from "statewire/storage";
3
4
  import type { StatewireClient } from "statewire";
4
5
  import type { StatewireThread } from "./StatewireThread";
5
6
 
@@ -76,91 +77,6 @@ const isStoredDraft = (value: unknown): value is StoredDraft =>
76
77
  typeof value["ts"] === "number" &&
77
78
  Number.isFinite(value["ts"]);
78
79
 
79
- const isPositiveSafeInteger = (value: unknown): value is number =>
80
- typeof value === "number" && Number.isSafeInteger(value) && value > 0;
81
-
82
- const isSessionCommand = (
83
- value: unknown,
84
- ): value is StatewireClient.SessionCommand =>
85
- isRecord(value) &&
86
- isPositiveSafeInteger(value["seq"]) &&
87
- typeof value["method"] === "string" &&
88
- Array.isArray(value["params"]);
89
-
90
- const isSessionVerdict = (
91
- value: unknown,
92
- ): value is StatewireClient.SessionVerdict =>
93
- isRecord(value) &&
94
- isPositiveSafeInteger(value["seq"]) &&
95
- (value["type"] === "result" ||
96
- value["type"] === "rejected" ||
97
- value["type"] === "failed" ||
98
- value["type"] === "crashed" ||
99
- value["type"] === "expired") &&
100
- isOptionalString(value["code"]) &&
101
- isOptionalString(value["message"]);
102
-
103
- const isSendFailure = (
104
- value: unknown,
105
- ): value is StatewireClient.SendFailure => {
106
- if (!isRecord(value)) return false;
107
- switch (value["fate"]) {
108
- case "rejected":
109
- return (
110
- value["cause"] === "server" &&
111
- isOptionalString(value["code"]) &&
112
- isOptionalString(value["message"])
113
- );
114
- case "failed":
115
- return value["cause"] === "server" && isOptionalString(value["message"]);
116
- case "crashed":
117
- case "expired":
118
- return value["cause"] === "server";
119
- case "aborted":
120
- return (
121
- (value["cause"] === "unmount" ||
122
- value["cause"] === "stream-gone" ||
123
- value["cause"] === "session-lost") &&
124
- (value["predecessorLost"] === undefined ||
125
- value["predecessorLost"] === true)
126
- );
127
- case "lost":
128
- return (
129
- value["cause"] === "unmount" ||
130
- value["cause"] === "stream-gone" ||
131
- value["cause"] === "session-lost"
132
- );
133
- default:
134
- return false;
135
- }
136
- };
137
-
138
- const isFailedCommand = (
139
- value: unknown,
140
- ): value is StatewireClient.FailedCommand =>
141
- isRecord(value) &&
142
- typeof value["command"] === "string" &&
143
- Array.isArray(value["params"]) &&
144
- isSendFailure(value["failure"]) &&
145
- typeof value["ts"] === "number" &&
146
- Number.isFinite(value["ts"]) &&
147
- isPositiveSafeInteger(value["seq"]);
148
-
149
- const isSessionRecord = (
150
- value: unknown,
151
- ): value is StatewireClient.SessionRecord =>
152
- isRecord(value) &&
153
- typeof value["clientId"] === "string" &&
154
- isPositiveSafeInteger(value["nextSeq"]) &&
155
- isPositiveSafeInteger(value["ctxNextSeq"]) &&
156
- Array.isArray(value["commands"]) &&
157
- value["commands"].every(isSessionCommand) &&
158
- (value["verdicts"] === undefined ||
159
- (Array.isArray(value["verdicts"]) &&
160
- value["verdicts"].every(isSessionVerdict))) &&
161
- (value["failed"] === undefined ||
162
- (Array.isArray(value["failed"]) && value["failed"].every(isFailedCommand)));
163
-
164
80
  const loadStored = <T>(
165
81
  key: string,
166
82
  validate: (value: unknown) => value is T,
@@ -243,30 +159,77 @@ export const LocalStorageComposerDrafts = resource(
243
159
 
244
160
  const SESSION_LOCK_PREFIX = "aui:statewire-session-lock:";
245
161
 
162
+ const SESSION_ACTIVE_PREFIX = "aui:statewire-session-active:";
163
+
164
+ const sessionBackend: KeyValueSessionStorage.Backend = {
165
+ getItem: (key) => localStorage.getItem(key),
166
+ setItem: (key, value) => localStorage.setItem(key, value),
167
+ removeItem: (key) => localStorage.removeItem(key),
168
+ getAllKeys: () =>
169
+ Array.from({ length: localStorage.length }, (_, index) =>
170
+ localStorage.key(index),
171
+ ).filter((key): key is string => key !== null),
172
+ withUnused: (key, action) =>
173
+ navigator.locks.request(
174
+ SESSION_ACTIVE_PREFIX + key,
175
+ { ifAvailable: true },
176
+ (lock) =>
177
+ lock === null
178
+ ? undefined
179
+ : navigator.locks.request(
180
+ SESSION_LOCK_PREFIX + key.slice(SESSION_PREFIX.length),
181
+ { ifAvailable: true },
182
+ (lock) => (lock === null ? undefined : action()),
183
+ ),
184
+ ),
185
+ };
186
+
246
187
  const useLocalStorageSession = ({
247
188
  threadId,
248
189
  migrate,
249
190
  key = (id) => id,
191
+ legacyProtocol,
192
+ retention,
193
+ onError,
250
194
  }: LocalStorageSession.Options): StatewireClient.SessionStorage => {
251
195
  if (typeof localStorage === "undefined")
252
196
  throw new Error("statewire: LocalStorageSession requires localStorage");
253
- // localStorage is shared across tabs: record mutations must serialize.
254
197
  if (typeof navigator === "undefined" || navigator.locks === undefined)
255
198
  throw new Error(
256
199
  "statewire: LocalStorageSession requires the Web Locks API (navigator.locks)",
257
200
  );
258
-
259
201
  const storageKey = SESSION_PREFIX + key(threadId);
260
202
  const lockName = SESSION_LOCK_PREFIX + key(threadId);
203
+ useEffect(() => {
204
+ let release: (() => void) | undefined;
205
+ let disposed = false;
206
+ void navigator.locks
207
+ .request(SESSION_ACTIVE_PREFIX + storageKey, { mode: "shared" }, () => {
208
+ if (disposed) return;
209
+ return new Promise<void>((resolve) => {
210
+ release = resolve;
211
+ });
212
+ })
213
+ .catch((error: unknown) => onError?.(error));
214
+ return () => {
215
+ disposed = true;
216
+ release?.();
217
+ };
218
+ }, [storageKey, onError]);
219
+ const storage = useResource(
220
+ KeyValueSessionStorage({
221
+ backend: sessionBackend,
222
+ key: key(threadId),
223
+ namespace: SESSION_PREFIX,
224
+ ...(migrate === undefined ? {} : { migrate }),
225
+ ...(legacyProtocol === undefined ? {} : { legacyProtocol }),
226
+ ...(retention === undefined ? {} : { retention }),
227
+ ...(onError === undefined ? {} : { onError }),
228
+ }),
229
+ );
261
230
  return useMemo(
262
231
  (): StatewireClient.SessionStorage => ({
263
- load: () => {
264
- return loadStored(storageKey, isSessionRecord);
265
- },
266
- save: (record) => {
267
- localStorage.setItem(storageKey, JSON.stringify(record));
268
- },
269
- ...(migrate !== undefined && { migrate }),
232
+ ...storage,
270
233
  lock: (fn) => navigator.locks.request(lockName, async () => fn()),
271
234
  subscribe: (listener) => {
272
235
  const onStorage = (event: StorageEvent) => {
@@ -276,7 +239,7 @@ const useLocalStorageSession = ({
276
239
  return () => window.removeEventListener("storage", onStorage);
277
240
  },
278
241
  }),
279
- [storageKey, lockName, migrate],
242
+ [storage, storageKey, lockName],
280
243
  );
281
244
  };
282
245
 
@@ -285,6 +248,9 @@ export const LocalStorageSession = resource(useLocalStorageSession);
285
248
 
286
249
  export namespace LocalStorageSession {
287
250
  export type Options = {
251
+ legacyProtocol?: KeyValueSessionStorage.Options["legacyProtocol"];
252
+ retention?: KeyValueSessionStorage.Options["retention"];
253
+ onError?: KeyValueSessionStorage.Options["onError"];
288
254
  /** Upgrade incompatible queued commands, or return null to discard the saved session. */
289
255
  migrate?: StatewireClient.SessionStorage["migrate"];
290
256
  /** The thread whose session this storage holds. */