@assistant-ui/react-statewire 0.21.0 → 0.23.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":"runCommands.js","names":["AppendMessage","ExternalThreadBranchAdapter","ExternalThreadQueueAdapter","QueuePlacement","StatewireThread","toWireMessage","message","id","UserMessage","role","Error","files","FilePart","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","undefined","parts","TextPart","length","const","join","toQueueItemState","item","RunQueueItem","prompt","map","placementFields","placement","insertAfter","insertBefore","viewedLeafId","messages","status","i","resolveEditCommand","runId","RunEditCommand","sourceId","index","findIndex","m","crypto","randomUUID","runAnchorMessageId","sendFields","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","command","RunCommand","dispatchSend","liveRunId","laneOf","queueItemId","some","sendCommand","lane","fields","items","steerItems","enqueue","steer","move","messageId","edit","wireMessage","remove","branchOf","metadata","custom","Record","BranchMetadata","branch","siblings","Number","isInteger","Array","isArray","every","includes","createBranchCommandAdapter","SwitchBranchCommand","getBranches","find","sibling","String","switchToBranch","branchId","target","resolveReloadCommand","parentId","RunReloadCommand"],"sources":["../src/runCommands.ts"],"sourcesContent":["import type {\n AppendMessage,\n ExternalThreadBranchAdapter,\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"@assistant-ui/core\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nexport const toWireMessage = (\n message: AppendMessage,\n id: string,\n): StatewireThread.UserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: StatewireThread.FilePart[] = [];\n const texts: string[] = [];\n const source = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const part of source) {\n if (part.type === \"text\") {\n texts.push(part.text);\n } else if (part.type === \"image\") {\n files.push({ type: \"file\", mediaType: \"image/*\", url: part.image });\n } else if (part.type === \"file\") {\n files.push({\n type: \"file\",\n mediaType: part.mimeType,\n url: part.data,\n ...(part.filename !== undefined && { filename: part.filename }),\n });\n } else {\n throw new Error(`statewire: unsupported message part \"${part.type}\"`);\n }\n }\n // default-safe against host capabilities: files first, one merged text part\n const parts: (StatewireThread.TextPart | StatewireThread.FilePart)[] = [\n ...files,\n ...(texts.length > 0\n ? [{ type: \"text\" as const, text: texts.join(\"\\n\\n\") }]\n : []),\n ];\n if (parts.length === 0)\n throw new Error(\"statewire: cannot send an empty message\");\n return { id, role: \"user\", parts };\n};\n\nconst toQueueItemState = (item: StatewireThread.RunQueueItem) => ({\n id: item.id,\n prompt: item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n parts: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n});\n\nconst placementFields = (placement: QueuePlacement) => ({\n ...(placement.insertAfter !== undefined && {\n insertAfter: placement.insertAfter,\n }),\n ...(placement.insertBefore !== undefined && {\n insertBefore: placement.insertBefore,\n }),\n});\n\nconst viewedLeafId = (\n messages: readonly { id: string; status?: { type: string } }[],\n): string | null => {\n // An in-flight assistant message is not host-committed history: anchor below it.\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]!.status?.type !== \"running\") return messages[i]!.id;\n }\n return null;\n};\n\nexport const resolveEditCommand = (\n messages: readonly { id: string }[],\n message: AppendMessage,\n runId: string | null,\n): StatewireThread.RunEditCommand => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n const index = messages.findIndex((m) => m.id === message.sourceId);\n if (index === -1)\n throw new Error(\n `statewire: run/edit source \"${message.sourceId}\" is unknown`,\n );\n return {\n type: \"run/edit\",\n runId: runId ?? crypto.randomUUID(),\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n runAnchorMessageId: messages[index - 1]?.id ?? null,\n };\n};\n\n/** The send fields for a run-creating or run-targeting enqueue/steer: target the live run, or mint a fresh one anchored at the viewed leaf. */\nexport const sendFields = (\n messages: readonly { id: string; status?: { type: string } }[],\n runId: string | null,\n message: StatewireThread.UserMessage,\n): {\n runId: string;\n message: StatewireThread.UserMessage;\n runAnchorMessageId?: string | null;\n} =>\n runId !== null\n ? { runId, message }\n : {\n runId: crypto.randomUUID(),\n message,\n runAnchorMessageId: viewedLeafId(messages),\n };\n\nexport const createRunQueueAdapter = (\n messages: readonly { id: string }[],\n runId: string | null,\n queueItems: readonly StatewireThread.RunQueueItem[],\n steerQueueItems: readonly StatewireThread.RunQueueItem[],\n dispatch: (command: StatewireThread.RunCommand) => void,\n dispatchSend: (\n command: StatewireThread.RunCommand,\n message: AppendMessage,\n ) => void,\n): ExternalThreadQueueAdapter => {\n const liveRunId = (): string => {\n if (runId === null) throw new Error(\"statewire: no live run to target\");\n return runId;\n };\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems.some((item) => item.id === queueItemId)) return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n // edit-composer sends carry a sourceId; they bypass the lanes into run/edit\n const sendCommand = (\n lane: \"queue\" | \"steer\",\n message: AppendMessage,\n ): StatewireThread.RunCommand => {\n if (message.sourceId != null)\n return resolveEditCommand(messages, message, runId);\n const fields = sendFields(\n messages,\n runId,\n toWireMessage(message, crypto.randomUUID()),\n );\n return lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields };\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: steerQueueItems.map(toQueueItemState),\n enqueue: (message) => dispatchSend(sendCommand(\"queue\", message), message),\n steer: (message) => dispatchSend(sendCommand(\"steer\", message), message),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\n runId: liveRunId(),\n messageId: queueItemId,\n ...placementFields(placement),\n };\n dispatch(\n lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields },\n );\n },\n edit: (queueItemId, message) => {\n const wireMessage = toWireMessage(message, queueItemId);\n dispatch(\n laneOf(queueItemId) === \"steer\"\n ? { type: \"run/steer\", runId: liveRunId(), message: wireMessage }\n : { type: \"run/enqueue\", runId: liveRunId(), message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({\n type: \"run/dequeue\",\n runId: liveRunId(),\n messageId: queueItemId,\n }),\n };\n};\n\nconst branchOf = (\n message: { metadata: { custom: Record<string, unknown> } } | undefined,\n): StatewireThread.BranchMetadata | undefined => {\n const branch = message?.metadata.custom[\"branch\"];\n if (branch === undefined) return undefined;\n const { id, siblings } = branch as StatewireThread.BranchMetadata;\n if (\n !Number.isInteger(id) ||\n !Array.isArray(siblings) ||\n !siblings.every(Number.isInteger) ||\n !siblings.includes(id)\n )\n throw new Error(\"statewire: malformed branch metadata\");\n return { id, siblings };\n};\n\n/** Branch surface over the host's thread-global branch: siblings come from `metadata.custom.branch`, switching sends `message/switch-branch`. */\nexport const createBranchCommandAdapter = (\n messages: readonly {\n id: string;\n metadata: { custom: Record<string, unknown> };\n }[],\n dispatch: (command: StatewireThread.SwitchBranchCommand) => void,\n): ExternalThreadBranchAdapter => ({\n getBranches: (messageId) => {\n const branch = branchOf(messages.find((m) => m.id === messageId));\n if (branch === undefined) return [];\n // the own slot carries the message id so the picker can locate its position\n return branch.siblings.map((sibling) =>\n sibling === branch.id ? messageId : String(sibling),\n );\n },\n switchToBranch: (branchId) => {\n const target = Number(branchId);\n if (!Number.isInteger(target))\n throw new Error(`statewire: unknown branch \"${branchId}\"`);\n dispatch({ type: \"message/switch-branch\", branchId: target });\n },\n});\n\nexport const resolveReloadCommand = (\n messages: readonly { id: string; role: string }[],\n parentId: string | null,\n runId: string | null,\n): StatewireThread.RunReloadCommand => {\n const index =\n parentId === null\n ? 0\n : messages.findIndex((message) => message.id === parentId) + 1;\n if (parentId !== null && index === 0)\n throw new Error(`statewire: run/reload parent \"${parentId}\" is unknown`);\n const target = messages[index];\n if (target === undefined || target.role !== \"assistant\")\n throw new Error(\n \"statewire: run/reload requires an assistant message to regenerate\",\n );\n return {\n type: \"run/reload\",\n runId: runId ?? crypto.randomUUID(),\n sourceId: target.id,\n runAnchorMessageId: parentId,\n };\n};\n"],"mappings":";AAQA,MAAaK,iBACXC,SACAC,OACgC;CAChC,IAAID,QAAQG,SAAS,QACnB,MAAM,IAAIC,MAAM,6CAA6C;CAC/D,MAAMC,QAAoC,CAAA;CAC1C,MAAME,QAAkB,CAAA;CACxB,MAAMC,SAAS,CACb,GAAGR,QAAQS,SACX,GAAIT,QAAQU,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAAG;CAE3D,KAAK,MAAMI,QAAQL,QACjB,IAAIK,KAAKC,SAAS,QAChBP,MAAMQ,KAAKF,KAAKG,IAAI;MACf,IAAIH,KAAKC,SAAS,SACvBT,MAAMU,KAAK;EAAED,MAAM;EAAQG,WAAW;EAAWC,KAAKL,KAAKM;CAAM,CAAC;MAC7D,IAAIN,KAAKC,SAAS,QACvBT,MAAMU,KAAK;EACTD,MAAM;EACNG,WAAWJ,KAAKO;EAChBF,KAAKL,KAAKQ;EACV,GAAIR,KAAKS,aAAaC,KAAAA,KAAa,EAAED,UAAUT,KAAKS,SAAS;CAC/D,CAAC;MAED,MAAM,IAAIlB,MAAM,wCAAwCS,KAAKC,KAAI,EAAG;CAIxE,MAAMU,QAAiE,CACrE,GAAGnB,OACH,GAAIE,MAAMmB,SAAS,IACf,CAAC;EAAEZ,MAAM;EAAiBE,MAAMT,MAAMqB,KAAK,MAAM;CAAE,CAAC,IACpD,CAAA,CAAG;CAET,IAAIJ,MAAME,WAAW,GACnB,MAAM,IAAItB,MAAM,yCAAyC;CAC3D,OAAO;EAAEH;EAAIE,MAAM;EAAQqB;CAAM;AACnC;AAEA,MAAMK,oBAAoBC,UAAwC;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AE1C,MAAM;GAAyBkF,UAAUC;EAAO,CAAC;CAC9D;AACF;AAEA,MAAaC,wBACX3D,UACA4D,UACAxD,UACqC;CACrC,MAAMG,QACJqD,aAAa,OACT,IACA5D,SAASQ,WAAW/C,YAAYA,QAAQC,OAAOkG,QAAQ,IAAI;CACjE,IAAIA,aAAa,QAAQrD,UAAU,GACjC,MAAM,IAAI1C,MAAM,iCAAiC+F,SAAQ,aAAc;CACzE,MAAMF,SAAS1D,SAASO;CACxB,IAAImD,WAAW1E,KAAAA,KAAa0E,OAAO9F,SAAS,aAC1C,MAAM,IAAIC,MACR,mEACF;CACF,OAAO;EACLU,MAAM;EACN6B,OAAOA,SAASM,OAAOC,WAAW;EAClCL,UAAUoD,OAAOhG;EACjBkD,oBAAoBgD;CACtB;AACF"}
1
+ {"version":3,"file":"runCommands.js","names":["AppendMessage","ExternalThreadBranchAdapter","ExternalThreadQueueAdapter","QueuePlacement","StatewireThread","toWireMessage","message","id","UserMessage","role","Error","files","FilePart","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","undefined","parts","TextPart","length","const","join","toQueueItemState","item","RunQueueItem","prompt","map","placementFields","placement","insertAfter","insertBefore","viewedLeafId","messages","status","i","resolveEditCommand","runId","RunEditCommand","sourceId","index","findIndex","m","crypto","randomUUID","runAnchorMessageId","sendFields","retryCommand","command","RunEnqueueCommand","RunSteerCommand","RunCommand","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","dispatchSend","liveRunId","laneOf","queueItemId","some","sendCommand","lane","fields","items","steerItems","enqueue","steer","move","messageId","edit","wireMessage","remove","branchOf","metadata","custom","Record","BranchMetadata","branch","siblings","Number","isInteger","Array","isArray","every","includes","createBranchCommandAdapter","SwitchBranchCommand","getBranches","find","sibling","String","switchToBranch","branchId","target","resolveReloadCommand","parentId","RunReloadCommand"],"sources":["../src/runCommands.ts"],"sourcesContent":["import type {\n AppendMessage,\n ExternalThreadBranchAdapter,\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"@assistant-ui/core\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nexport const toWireMessage = (\n message: AppendMessage,\n id: string,\n): StatewireThread.UserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: StatewireThread.FilePart[] = [];\n const texts: string[] = [];\n const source = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const part of source) {\n if (part.type === \"text\") {\n texts.push(part.text);\n } else if (part.type === \"image\") {\n files.push({ type: \"file\", mediaType: \"image/*\", url: part.image });\n } else if (part.type === \"file\") {\n files.push({\n type: \"file\",\n mediaType: part.mimeType,\n url: part.data,\n ...(part.filename !== undefined && { filename: part.filename }),\n });\n } else {\n throw new Error(`statewire: unsupported message part \"${part.type}\"`);\n }\n }\n // default-safe against host capabilities: files first, one merged text part\n const parts: (StatewireThread.TextPart | StatewireThread.FilePart)[] = [\n ...files,\n ...(texts.length > 0\n ? [{ type: \"text\" as const, text: texts.join(\"\\n\\n\") }]\n : []),\n ];\n if (parts.length === 0)\n throw new Error(\"statewire: cannot send an empty message\");\n return { id, role: \"user\", parts };\n};\n\nconst toQueueItemState = (item: StatewireThread.RunQueueItem) => ({\n id: item.id,\n prompt: item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n parts: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n});\n\nconst placementFields = (placement: QueuePlacement) => ({\n ...(placement.insertAfter !== undefined && {\n insertAfter: placement.insertAfter,\n }),\n ...(placement.insertBefore !== undefined && {\n insertBefore: placement.insertBefore,\n }),\n});\n\nconst viewedLeafId = (\n messages: readonly { id: string; status?: { type: string } }[],\n): string | null => {\n // An in-flight assistant message is not host-committed history: anchor below it.\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]!.status?.type !== \"running\") return messages[i]!.id;\n }\n return null;\n};\n\nexport const resolveEditCommand = (\n messages: readonly { id: string }[],\n message: AppendMessage,\n runId: string | null,\n): StatewireThread.RunEditCommand => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n const index = messages.findIndex((m) => m.id === message.sourceId);\n if (index === -1)\n throw new Error(\n `statewire: run/edit source \"${message.sourceId}\" is unknown`,\n );\n return {\n type: \"run/edit\",\n runId: runId ?? crypto.randomUUID(),\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n runAnchorMessageId: messages[index - 1]?.id ?? null,\n };\n};\n\n/** The send fields for a run-creating or run-targeting enqueue/steer: target the live run, or mint a fresh one anchored at the viewed leaf. */\nexport const sendFields = (\n messages: readonly { id: string; status?: { type: string } }[],\n runId: string | null,\n message: StatewireThread.UserMessage,\n): {\n runId: string;\n message: StatewireThread.UserMessage;\n runAnchorMessageId?: string | null;\n} =>\n runId !== null\n ? { runId, message }\n : {\n runId: crypto.randomUUID(),\n message,\n runAnchorMessageId: viewedLeafId(messages),\n };\n\n/** Rebuilds a failed send against the current thread: edits re-anchor at the source's current parent, sends whose target run is gone fall back to a fresh enqueue. */\nexport const retryCommand = (\n messages: readonly { id: string; status?: { type: string } }[],\n runId: string | null,\n command:\n | (StatewireThread.RunEnqueueCommand & {\n message: StatewireThread.UserMessage;\n })\n | (StatewireThread.RunSteerCommand & {\n message: StatewireThread.UserMessage;\n })\n | StatewireThread.RunEditCommand,\n): StatewireThread.RunCommand => {\n if (command.type === \"run/edit\") {\n const index = messages.findIndex((m) => m.id === command.sourceId);\n if (index === -1)\n throw new Error(\n `statewire: run/edit source \"${command.sourceId}\" is unknown`,\n );\n return {\n ...command,\n runId: runId ?? crypto.randomUUID(),\n runAnchorMessageId: messages[index - 1]?.id ?? null,\n };\n }\n if (runId !== null && command.runId === runId) return command;\n return {\n type: \"run/enqueue\",\n ...sendFields(messages, runId, command.message),\n };\n};\n\nexport const createRunQueueAdapter = (\n messages: readonly { id: string }[],\n runId: string | null,\n queueItems: readonly StatewireThread.RunQueueItem[],\n steerQueueItems: readonly StatewireThread.RunQueueItem[],\n dispatch: (command: StatewireThread.RunCommand) => void,\n dispatchSend: (\n command: StatewireThread.RunCommand,\n message: AppendMessage,\n ) => void,\n): ExternalThreadQueueAdapter => {\n const liveRunId = (): string => {\n if (runId === null) throw new Error(\"statewire: no live run to target\");\n return runId;\n };\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems.some((item) => item.id === queueItemId)) return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n // edit-composer sends carry a sourceId; they bypass the lanes into run/edit\n const sendCommand = (\n lane: \"queue\" | \"steer\",\n message: AppendMessage,\n ): StatewireThread.RunCommand => {\n if (message.sourceId != null)\n return resolveEditCommand(messages, message, runId);\n const fields = sendFields(\n messages,\n runId,\n toWireMessage(message, crypto.randomUUID()),\n );\n return lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields };\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: steerQueueItems.map(toQueueItemState),\n enqueue: (message) => dispatchSend(sendCommand(\"queue\", message), message),\n steer: (message) => dispatchSend(sendCommand(\"steer\", message), message),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\n runId: liveRunId(),\n messageId: queueItemId,\n ...placementFields(placement),\n };\n dispatch(\n lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields },\n );\n },\n edit: (queueItemId, message) => {\n const wireMessage = toWireMessage(message, queueItemId);\n dispatch(\n laneOf(queueItemId) === \"steer\"\n ? { type: \"run/steer\", runId: liveRunId(), message: wireMessage }\n : { type: \"run/enqueue\", runId: liveRunId(), message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({\n type: \"run/dequeue\",\n runId: liveRunId(),\n messageId: queueItemId,\n }),\n };\n};\n\nconst branchOf = (\n message: { metadata: { custom: Record<string, unknown> } } | undefined,\n): StatewireThread.BranchMetadata | undefined => {\n const branch = message?.metadata.custom[\"branch\"];\n if (branch === undefined) return undefined;\n const { id, siblings } = branch as StatewireThread.BranchMetadata;\n if (\n !Number.isInteger(id) ||\n !Array.isArray(siblings) ||\n !siblings.every(Number.isInteger) ||\n !siblings.includes(id)\n )\n throw new Error(\"statewire: malformed branch metadata\");\n return { id, siblings };\n};\n\n/** Branch surface over the host's thread-global branch: siblings come from `metadata.custom.branch`, switching sends `message/switch-branch`. */\nexport const createBranchCommandAdapter = (\n messages: readonly {\n id: string;\n metadata: { custom: Record<string, unknown> };\n }[],\n dispatch: (command: StatewireThread.SwitchBranchCommand) => void,\n): ExternalThreadBranchAdapter => ({\n getBranches: (messageId) => {\n const branch = branchOf(messages.find((m) => m.id === messageId));\n if (branch === undefined) return [];\n // the own slot carries the message id so the picker can locate its position\n return branch.siblings.map((sibling) =>\n sibling === branch.id ? messageId : String(sibling),\n );\n },\n switchToBranch: (branchId) => {\n const target = Number(branchId);\n if (!Number.isInteger(target))\n throw new Error(`statewire: unknown branch \"${branchId}\"`);\n dispatch({ type: \"message/switch-branch\", branchId: target });\n },\n});\n\nexport const resolveReloadCommand = (\n messages: readonly { id: string; role: string }[],\n parentId: string | null,\n runId: string | null,\n): StatewireThread.RunReloadCommand => {\n const index =\n parentId === null\n ? 0\n : messages.findIndex((message) => message.id === parentId) + 1;\n if (parentId !== null && index === 0)\n throw new Error(`statewire: run/reload parent \"${parentId}\" is unknown`);\n const target = messages[index];\n if (target === undefined || target.role !== \"assistant\")\n throw new Error(\n \"statewire: run/reload requires an assistant message to regenerate\",\n );\n return {\n type: \"run/reload\",\n runId: runId ?? crypto.randomUUID(),\n sourceId: target.id,\n runAnchorMessageId: parentId,\n };\n};\n"],"mappings":";AAQA,MAAaK,iBACXC,SACAC,OACgC;CAChC,IAAID,QAA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AYsB,OAAOD,OAAO,CACpD;CACF;CACAE,iBAAiBC,aAAa;EAC5B,MAAMC,SAASd,OAAOa,QAAQ;EAC9B,IAAI,CAACb,OAAOC,UAAUa,MAAM,GAC1B,MAAM,IAAIhG,MAAM,8BAA8B+F,SAAQ,EAAG;EAC3DtC,SAAS;GAAE/C,MAAM;GAAyBqF,UAAUC;EAAO,CAAC;CAC9D;AACF;AAEA,MAAaC,wBACX9D,UACA+D,UACA3D,UACqC;CACrC,MAAMG,QACJwD,aAAa,OACT,IACA/D,SAASQ,WAAW/C,YAAYA,QAAQC,OAAOqG,QAAQ,IAAI;CACjE,IAAIA,aAAa,QAAQxD,UAAU,GACjC,MAAM,IAAI1C,MAAM,iCAAiCkG,SAAQ,aAAc;CACzE,MAAMF,SAAS7D,SAASO;CACxB,IAAIsD,WAAW7E,KAAAA,KAAa6E,OAAOjG,SAAS,aAC1C,MAAM,IAAIC,MACR,mEACF;CACF,OAAO;EACLU,MAAM;EACN6B,OAAOA,SAASM,OAAOC,WAAW;EAClCL,UAAUuD,OAAOnG;EACjBkD,oBAAoBmD;CACtB;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/react-statewire",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "assistant-ui thread binding for statewire backends",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -37,7 +37,7 @@
37
37
  "@assistant-ui/store": "^0.3.0",
38
38
  "@assistant-ui/tap": "^0.9.7",
39
39
  "assistant-stream": "^0.3.37",
40
- "statewire": "^0.11.0"
40
+ "statewire": "^0.13.0"
41
41
  },
42
42
  "peerDependencies": {
43
43
  "@assistant-ui/core": ">=0.3.12",
@@ -0,0 +1,279 @@
1
+ // @vitest-environment jsdom
2
+
3
+ // Contract tests for StatewireThread's failed lane at its public seam: run
4
+ // sends that settle non-accepted project into the runs read as failed
5
+ // entries, with retry/discard/pop on the thread extras.
6
+
7
+ import { act, render, waitFor } from "@testing-library/react";
8
+ import type { FC } from "react";
9
+ import { describe, expect, it } from "vitest";
10
+ import { AuiProvider, useAui } from "@assistant-ui/store";
11
+ import { StatewireSSE } from "statewire";
12
+ import { asStatewireExtras, StatewireThread } from "./StatewireThread";
13
+ import { useStatewireRuns } from "./hooks";
14
+ import { sendCommand, toThreadMessage } from "./__tests__/testHelpers";
15
+
16
+ type ServerState = {
17
+ messages: { id: string; role: "user" | "assistant"; text: string }[];
18
+ status: "ready";
19
+ runs: never[];
20
+ };
21
+
22
+ const INITIAL_STATE: ServerState = { messages: [], status: "ready", runs: [] };
23
+
24
+ const converter: StatewireThread.StateConverter<ServerState> = (state) => ({
25
+ messages: state.messages.map(toThreadMessage),
26
+ });
27
+
28
+ const wireMessage = (
29
+ id: string,
30
+ text: string,
31
+ ): StatewireThread.UserMessage => ({
32
+ id,
33
+ role: "user",
34
+ parts: [{ type: "text", text }],
35
+ });
36
+
37
+ const extras = (aui: () => ReturnType<typeof useAui>) =>
38
+ asStatewireExtras(aui().thread().getState().extras);
39
+
40
+ // A remote SSE fake that settles every admitted command with a verdict on the
41
+ // stream: rejected by default, accepted after `accept()`. `sendOps` pushes
42
+ // canonical state, for the covered contract.
43
+ const createSettlingServer = (init?: Partial<ServerState>) => {
44
+ const received: { method: string; params: unknown[]; seq: number }[] = [];
45
+ const clients = new Map<string, { seq: number; ctxSeq: number }>();
46
+ const encoder = new TextEncoder();
47
+ const frame = (chunk: unknown) => `data: ${JSON.stringify(chunk)}\n\n`;
48
+ let stream: ReadableStreamDefaultController<Uint8Array> | undefined;
49
+ let verdict = (): Record<string, unknown> => ({
50
+ type: "rejected",
51
+ message: "nope",
52
+ });
53
+ const push = (chunk: unknown) =>
54
+ stream!.enqueue(encoder.encode(frame(chunk)));
55
+ type Frame = {
56
+ ctx?: { seq: number }[];
57
+ cmd?: { method: string; params: unknown[]; seq: number }[];
58
+ };
59
+ const admit = (clientId: string, body: Frame) => {
60
+ const rec = clients.get(clientId)!;
61
+ for (const statement of body.ctx ?? []) {
62
+ rec.ctxSeq = Math.max(rec.ctxSeq, statement.seq);
63
+ }
64
+ for (const statement of body.cmd ?? []) {
65
+ rec.seq = Math.max(rec.seq, statement.seq);
66
+ received.push({
67
+ method: statement.method,
68
+ params: statement.params,
69
+ seq: statement.seq,
70
+ });
71
+ push({ cmd: [{ seq: statement.seq, dur: true }] });
72
+ push({ cmd: [{ seq: statement.seq, ...verdict() }] });
73
+ }
74
+ };
75
+ const fetchImpl = (async (input: RequestInfo | URL, init2?: RequestInit) => {
76
+ const url = String(input);
77
+ const headers = new Headers(init2?.headers);
78
+ const clientId = headers.get("Statewire-Client-Id")!;
79
+ if (url.endsWith("/stream")) {
80
+ if (!clients.has(clientId)) clients.set(clientId, { seq: 0, ctxSeq: 0 });
81
+ const rec = clients.get(clientId)!;
82
+ const attachFrame = JSON.parse(String(init2?.body)) as Frame;
83
+ const body = new ReadableStream<Uint8Array>({
84
+ start: (c) => {
85
+ stream = c;
86
+ c.enqueue(
87
+ encoder.encode(
88
+ frame({
89
+ ops: [
90
+ {
91
+ op: "replace",
92
+ path: [],
93
+ value: { ...INITIAL_STATE, ...init },
94
+ },
95
+ ],
96
+ syn: { seq: rec.seq, ctxSeq: rec.ctxSeq },
97
+ }),
98
+ ),
99
+ );
100
+ admit(clientId, attachFrame);
101
+ },
102
+ });
103
+ return new Response(body, {
104
+ status: 200,
105
+ headers: {
106
+ "content-type": "text/event-stream",
107
+ "Statewire-Lease": "lease-1",
108
+ },
109
+ });
110
+ }
111
+ admit(clientId, JSON.parse(String(init2?.body)) as Frame);
112
+ return Response.json({});
113
+ }) as typeof fetch;
114
+ return {
115
+ received,
116
+ accept: () => {
117
+ verdict = () => ({ type: "result" });
118
+ },
119
+ sendOps: (ops: unknown[]) => push({ ops }),
120
+ transport: StatewireSSE<ServerState>({
121
+ url: "http://fake/api",
122
+ fetch: fetchImpl,
123
+ }),
124
+ };
125
+ };
126
+
127
+ const mountThread = (
128
+ options: Omit<
129
+ StatewireThread.Options<ServerState>,
130
+ "initialState" | "converter"
131
+ >,
132
+ ) => {
133
+ const captured: {
134
+ aui?: ReturnType<typeof useAui>;
135
+ runs?: StatewireThread.Runs;
136
+ } = {};
137
+ const Capture: FC = () => {
138
+ captured.aui = useAui();
139
+ captured.runs = useStatewireRuns();
140
+ return null;
141
+ };
142
+ const App: FC = () => {
143
+ const aui = useAui({
144
+ thread: StatewireThread<ServerState>({
145
+ initialState: INITIAL_STATE,
146
+ converter,
147
+ ...options,
148
+ }),
149
+ });
150
+ return (
151
+ <AuiProvider value={aui}>
152
+ <Capture />
153
+ </AuiProvider>
154
+ );
155
+ };
156
+ render(<App />);
157
+ return { aui: () => captured.aui!, runs: () => captured.runs! };
158
+ };
159
+
160
+ const mountFailed = async (
161
+ command: StatewireThread.RunCommand,
162
+ init?: Partial<ServerState>,
163
+ ) => {
164
+ const server = createSettlingServer(init);
165
+ const mounted = mountThread({ transport: server.transport });
166
+ await waitFor(() => expect(extras(mounted.aui).status).toBe("ready"));
167
+ act(() => {
168
+ sendCommand(mounted.aui, command);
169
+ });
170
+ await waitFor(() => expect(mounted.runs().failed).toHaveLength(1));
171
+ return { server, ...mounted };
172
+ };
173
+
174
+ describe("StatewireThread failed lane", () => {
175
+ it("projects a rejected enqueue as a failed entry", async () => {
176
+ const { runs } = await mountFailed({
177
+ type: "run/enqueue",
178
+ runId: "run-1",
179
+ message: wireMessage("m1", "hello"),
180
+ runAnchorMessageId: null,
181
+ });
182
+ expect(runs().failed[0]).toMatchObject({
183
+ id: "m1",
184
+ role: "user",
185
+ parts: [{ type: "text", text: "hello" }],
186
+ sendFailure: { fate: "rejected", cause: "server", message: "nope" },
187
+ });
188
+ expect(runs().runId).toBeNull();
189
+ });
190
+
191
+ it("retry re-dispatches the send and removes the entry", async () => {
192
+ const { server, aui, runs } = await mountFailed({
193
+ type: "run/enqueue",
194
+ runId: "run-1",
195
+ message: wireMessage("m1", "hello"),
196
+ runAnchorMessageId: null,
197
+ });
198
+ server.accept();
199
+ act(() => {
200
+ extras(aui).retryFailed("m1");
201
+ });
202
+ await waitFor(() => expect(runs().failed).toHaveLength(0));
203
+ const sends = server.received.filter((r) => r.method === "run/enqueue");
204
+ expect(sends).toHaveLength(2);
205
+ expect(sends[1]!.params[0]).toMatchObject({
206
+ message: { id: "m1" },
207
+ runAnchorMessageId: null,
208
+ });
209
+ expect((sends[1]!.params[0] as { runId: string }).runId).not.toBe("run-1");
210
+ });
211
+
212
+ it("a failed steer whose run is gone retries as a plain enqueue", async () => {
213
+ const { server, aui, runs } = await mountFailed({
214
+ type: "run/steer",
215
+ runId: "run-9",
216
+ message: wireMessage("s1", "now"),
217
+ runAnchorMessageId: null,
218
+ });
219
+ server.accept();
220
+ act(() => {
221
+ extras(aui).retryFailed("s1");
222
+ });
223
+ await waitFor(() => expect(runs().failed).toHaveLength(0));
224
+ expect(server.received.at(-1)).toMatchObject({
225
+ method: "run/enqueue",
226
+ params: [{ message: { id: "s1" } }],
227
+ });
228
+ });
229
+
230
+ it("discard removes the entry and refuses an unknown one", async () => {
231
+ const { aui, runs } = await mountFailed({
232
+ type: "run/enqueue",
233
+ runId: "run-1",
234
+ message: wireMessage("m1", "hello"),
235
+ runAnchorMessageId: null,
236
+ });
237
+ act(() => {
238
+ extras(aui).discardFailed("m1");
239
+ });
240
+ await waitFor(() => expect(runs().failed).toHaveLength(0));
241
+ expect(() => extras(aui).discardFailed("m1")).toThrow(
242
+ /unknown failed entry/,
243
+ );
244
+ });
245
+
246
+ it("pop returns the entry's text and removes it", async () => {
247
+ const { aui, runs } = await mountFailed({
248
+ type: "run/enqueue",
249
+ runId: "run-1",
250
+ message: wireMessage("m1", "hello"),
251
+ runAnchorMessageId: null,
252
+ });
253
+ let text = "";
254
+ act(() => {
255
+ text = extras(aui).popFailed("m1");
256
+ });
257
+ expect(text).toBe("hello");
258
+ await waitFor(() => expect(runs().failed).toHaveLength(0));
259
+ });
260
+
261
+ it("drops the entry once the canonical state carries its message", async () => {
262
+ const { server, runs } = await mountFailed({
263
+ type: "run/enqueue",
264
+ runId: "run-1",
265
+ message: wireMessage("m1", "hello"),
266
+ runAnchorMessageId: null,
267
+ });
268
+ act(() => {
269
+ server.sendOps([
270
+ {
271
+ op: "replace",
272
+ path: ["messages"],
273
+ value: [{ id: "m1", role: "user", text: "hello" }],
274
+ },
275
+ ]);
276
+ });
277
+ await waitFor(() => expect(runs().failed).toHaveLength(0));
278
+ });
279
+ });
@@ -563,7 +563,7 @@ describe("StatewireThread", () => {
563
563
  });
564
564
 
565
565
  await waitFor(() => expect(statuses).toEqual(["live"]));
566
- await mock.finish("superseded");
566
+ await mock.finish("gone");
567
567
  await waitFor(() => expect(statuses).toEqual(["live", "gone"]));
568
568
  await new Promise((r) => setTimeout(r, 20));
569
569
  expect(statuses).toEqual(["live", "gone"]);
@@ -1293,7 +1293,7 @@ describe("StatewireThread", () => {
1293
1293
  await waitFor(() => expect(threadStatus(aui())).toBe("ready"));
1294
1294
  expect(seen).toEqual(["connecting", "live"]);
1295
1295
 
1296
- await mock.finish("superseded", "taken over");
1296
+ await mock.finish("gone", "taken over");
1297
1297
  await waitFor(() => expect(seen.at(-1)).toBe("gone"));
1298
1298
  });
1299
1299
 
@@ -1317,7 +1317,7 @@ describe("StatewireThread", () => {
1317
1317
  });
1318
1318
 
1319
1319
  await waitFor(() => expect(threadStatus(aui())).toBe("ready"));
1320
- await mock.finish("superseded");
1320
+ await mock.finish("gone");
1321
1321
  await waitFor(() => expect(seen.at(-1)).toBe("gone"));
1322
1322
 
1323
1323
  asStatewireExtras(aui().thread().getState().extras).reconnect();
@@ -33,6 +33,7 @@ import {
33
33
  createBranchCommandAdapter,
34
34
  createRunQueueAdapter,
35
35
  resolveEditCommand,
36
+ retryCommand,
36
37
  resolveReloadCommand,
37
38
  sendFields,
38
39
  toWireMessage,
@@ -66,6 +67,30 @@ const RESTING_RUNS: StatewireThread.Runs = {
66
67
  runId: null,
67
68
  queue: [],
68
69
  steerQueue: [],
70
+ failed: [],
71
+ };
72
+
73
+ /** The failed run sends the thread can project: enqueue/steer/edit invocations carrying a message. */
74
+ const failedRunCommand = (
75
+ entry: StatewireClient.FailedCommand,
76
+ ):
77
+ | ((
78
+ | StatewireThread.RunEnqueueCommand
79
+ | StatewireThread.RunSteerCommand
80
+ | StatewireThread.RunEditCommand
81
+ ) & { message: StatewireThread.UserMessage })
82
+ | undefined => {
83
+ if (
84
+ entry.command !== "run/enqueue" &&
85
+ entry.command !== "run/steer" &&
86
+ entry.command !== "run/edit"
87
+ )
88
+ return undefined;
89
+ const command = entry.params[0] as
90
+ | { message?: StatewireThread.UserMessage }
91
+ | undefined;
92
+ if (command?.message === undefined) return undefined;
93
+ return command as ReturnType<typeof failedRunCommand>;
69
94
  };
70
95
 
71
96
  // Derived presentation while the connection can't vouch for progress:
@@ -111,10 +136,15 @@ const useStatewireThread = (
111
136
  ),
112
137
  );
113
138
 
114
- const { state, commands, connection, setContext, isBusy } = useStatewire<
115
- unknown,
116
- AnyCommands
117
- >({
139
+ const {
140
+ state,
141
+ commands,
142
+ connection,
143
+ setContext,
144
+ isBusy,
145
+ failed,
146
+ discardFailed,
147
+ } = useStatewire<unknown, AnyCommands>({
118
148
  transport: options.transport,
119
149
  storage: options.storage,
120
150
  initialState: options.initialState,
@@ -131,8 +161,22 @@ const useStatewireThread = (
131
161
  onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),
132
162
  onConnectionChange: (connection) =>
133
163
  latest.current.onConnectionChange?.(connection),
164
+ failureCovered: (state, entry) => {
165
+ const command = failedRunCommand(entry);
166
+ if (command === undefined) return false;
167
+ const messages = (state as { messages?: readonly { id: string }[] })
168
+ .messages;
169
+ return messages?.some((m) => m.id === command.message.id) ?? false;
170
+ },
134
171
  });
135
172
 
173
+ // Failures the thread cannot project stay onError-only, as before the lane.
174
+ useEffect(() => {
175
+ for (const entry of failed) {
176
+ if (failedRunCommand(entry) === undefined) discardFailed(entry);
177
+ }
178
+ }, [failed, discardFailed]);
179
+
136
180
  const clientRef = useAssistantClientRef();
137
181
  const setContextRef = useRef(setContext);
138
182
  setContextRef.current = setContext;
@@ -197,33 +241,48 @@ const useStatewireThread = (
197
241
  state as { runs?: readonly StatewireThread.RunState[] } | undefined
198
242
  )?.runs;
199
243
  const entry = entries?.[0];
244
+ const failedEntries = failed.flatMap(
245
+ (failure): StatewireThread.RunsFailedEntry[] => {
246
+ const command = failedRunCommand(failure);
247
+ return command === undefined
248
+ ? []
249
+ : [{ ...command.message, sendFailure: failure.failure }];
250
+ },
251
+ );
200
252
  return {
201
253
  status: presentStatus(
202
254
  entries === undefined ? "loading" : (entry?.status ?? "ready"),
203
255
  connection,
204
256
  ),
205
257
  runs:
206
- entry === undefined
258
+ entry === undefined && failedEntries.length === 0
207
259
  ? RESTING_RUNS
208
260
  : {
209
- runId: entry.runId,
210
- ...(entry.epoch !== undefined && { epoch: entry.epoch }),
211
- queue: entry.queue,
212
- steerQueue: entry.steerQueue,
213
- ...(entry.dispatching !== undefined && {
214
- dispatching: entry.dispatching,
215
- }),
216
- ...(entry.stopping !== undefined && { stopping: entry.stopping }),
217
- ...(entry.nextDispatch !== undefined && {
218
- nextDispatch: entry.nextDispatch,
219
- }),
220
- ...(entry.inputRequests !== undefined && {
221
- inputRequests: entry.inputRequests,
222
- }),
223
- ...(entry.error !== undefined && { error: entry.error }),
261
+ ...(entry === undefined
262
+ ? RESTING_RUNS
263
+ : {
264
+ runId: entry.runId,
265
+ ...(entry.epoch !== undefined && { epoch: entry.epoch }),
266
+ queue: entry.queue,
267
+ steerQueue: entry.steerQueue,
268
+ ...(entry.dispatching !== undefined && {
269
+ dispatching: entry.dispatching,
270
+ }),
271
+ ...(entry.stopping !== undefined && {
272
+ stopping: entry.stopping,
273
+ }),
274
+ ...(entry.nextDispatch !== undefined && {
275
+ nextDispatch: entry.nextDispatch,
276
+ }),
277
+ ...(entry.inputRequests !== undefined && {
278
+ inputRequests: entry.inputRequests,
279
+ }),
280
+ ...(entry.error !== undefined && { error: entry.error }),
281
+ }),
282
+ failed: failedEntries,
224
283
  },
225
284
  };
226
- }, [state, connection]);
285
+ }, [state, connection, failed]);
227
286
 
228
287
  const { converter } = options;
229
288
  const metadata = useMemo(
@@ -264,8 +323,16 @@ const useStatewireThread = (
264
323
 
265
324
  const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;
266
325
 
267
- const extras = useMemo(
268
- (): StatewireThread.Extras => ({
326
+ const extras = useMemo((): StatewireThread.Extras => {
327
+ const takeFailed = (messageId: string): StatewireClient.FailedCommand => {
328
+ const entry = failed.find(
329
+ (f) => failedRunCommand(f)?.message.id === messageId,
330
+ );
331
+ if (entry === undefined)
332
+ throw new Error(`statewire: unknown failed entry "${messageId}"`);
333
+ return entry;
334
+ };
335
+ return {
269
336
  [symbolStatewireExtras]: true,
270
337
  sendCommand: dispatch,
271
338
  reconnect: connection.reconnect,
@@ -274,17 +341,38 @@ const useStatewireThread = (
274
341
  isBusy,
275
342
  inputRequests,
276
343
  runs,
277
- }),
278
- [
279
- dispatch,
280
- connection.reconnect,
281
- state,
282
- status,
283
- isBusy,
284
- inputRequests,
285
- runs,
286
- ],
287
- );
344
+ retryFailed: (messageId) => {
345
+ const entry = takeFailed(messageId);
346
+ const command = retryCommand(
347
+ messages,
348
+ liveRunId,
349
+ failedRunCommand(entry)!,
350
+ );
351
+ discardFailed(entry);
352
+ void dispatch(command);
353
+ },
354
+ discardFailed: (messageId) => discardFailed(takeFailed(messageId)),
355
+ popFailed: (messageId) => {
356
+ const entry = takeFailed(messageId);
357
+ discardFailed(entry);
358
+ return failedRunCommand(entry)!
359
+ .message.parts.flatMap((p) => (p.type === "text" ? [p.text] : []))
360
+ .join("\n\n");
361
+ },
362
+ };
363
+ }, [
364
+ dispatch,
365
+ connection.reconnect,
366
+ state,
367
+ status,
368
+ isBusy,
369
+ inputRequests,
370
+ runs,
371
+ failed,
372
+ discardFailed,
373
+ messages,
374
+ liveRunId,
375
+ ]);
288
376
 
289
377
  const handleAppend = (message: AppendMessage) => {
290
378
  dispatchSend(
@@ -444,7 +532,8 @@ export namespace StatewireThread {
444
532
 
445
533
  export type Extras = {
446
534
  [symbolStatewireExtras]: true;
447
- sendCommand: (command: Command) => void;
535
+ /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */
536
+ sendCommand: (command: Command) => Promise<unknown>;
448
537
  reconnect: () => void;
449
538
  state: unknown;
450
539
  status: ThreadStatus;
@@ -452,6 +541,12 @@ export namespace StatewireThread {
452
541
  isBusy: boolean;
453
542
  inputRequests: readonly InputRequestState[];
454
543
  runs: Runs;
544
+ /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */
545
+ retryFailed: (messageId: string) => void;
546
+ /** Removes the failed entry; keyed by the entry's message id. */
547
+ discardFailed: (messageId: string) => void;
548
+ /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */
549
+ popFailed: (messageId: string) => string;
455
550
  };
456
551
 
457
552
  export type TextPart = {
@@ -612,6 +707,11 @@ export namespace StatewireThread {
612
707
  readonly meta?: ReadonlyJSONValue;
613
708
  };
614
709
 
710
+ /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */
711
+ export type RunsFailedEntry = RunsQueueEntry & {
712
+ readonly sendFailure: StatewireClient.SendFailure;
713
+ };
714
+
615
715
  /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */
616
716
  export type RunsInputOutcome = {
617
717
  readonly request: InputRequest;
@@ -702,6 +802,8 @@ export namespace StatewireThread {
702
802
  readonly inputRequests?: readonly InputRequestState[];
703
803
  /** Set only by an unhandled throw; cleared by the next user-initiated run. */
704
804
  readonly error?: RunsError;
805
+ /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */
806
+ readonly failed: readonly RunsFailedEntry[];
705
807
  };
706
808
 
707
809
  export type ConnectionMetadata = {
package/src/hooks.ts CHANGED
@@ -12,10 +12,8 @@ type UserExternalState = keyof Assistant.ExternalState extends never
12
12
  export const useStatewireSendCommand = () => {
13
13
  const aui = useAui();
14
14
 
15
- return (command: StatewireThread.Command) => {
16
- const extras = aui.thread().getState().extras;
17
- asStatewireExtras(extras).sendCommand(command);
18
- };
15
+ return (command: StatewireThread.Command) =>
16
+ asStatewireExtras(aui.thread().getState().extras).sendCommand(command);
19
17
  };
20
18
 
21
19
  /** The typed runs read. */