@assistant-ui/react-statewire 0.15.0 → 0.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/StatewireThread.d.ts +3 -3
- package/dist/StatewireThread.js.map +1 -1
- package/dist/runsOptimistic.js +3 -3
- package/dist/runsOptimistic.js.map +1 -1
- package/package.json +1 -1
- package/src/StatewireThread.runs.test.tsx +11 -11
- package/src/StatewireThread.ts +5 -5
- package/src/runsMaterialize.test.ts +4 -4
- package/src/runsOptimistic.test.ts +11 -11
- package/src/runsOptimistic.ts +5 -5
|
@@ -142,7 +142,7 @@ declare namespace StatewireThread {
|
|
|
142
142
|
};
|
|
143
143
|
/** The dispatch record — the unacked batch handed to the run; absent between the ack and the next dispatch or take. */
|
|
144
144
|
export type RunsDispatch = {
|
|
145
|
-
readonly trigger: "send
|
|
145
|
+
readonly trigger: "message-send" | "message-edit" | "message-reload" | "input-resume" | "error-continue" | "stop-continue" | "steer";
|
|
146
146
|
readonly messages: readonly RunsQueueEntry[];
|
|
147
147
|
/** Present on rewind dispatches: truncate the thread at this id first; null names the root. */
|
|
148
148
|
readonly rollbackTo?: string | null;
|
|
@@ -151,9 +151,9 @@ declare namespace StatewireThread {
|
|
|
151
151
|
/** Present when input outcomes ride the dispatch; visible until the ack. */
|
|
152
152
|
readonly inputOutcomes?: readonly RunsInputOutcome[];
|
|
153
153
|
};
|
|
154
|
-
/** The stopping window: present while a stop of the live run is underway; `"edit
|
|
154
|
+
/** The stopping window: present while a stop of the live run is underway; `"message-edit"` / `"message-reload"` pair with `nextDispatch`. */
|
|
155
155
|
export type RunsStopping = {
|
|
156
|
-
readonly reason: "stop" | "edit
|
|
156
|
+
readonly reason: "stop" | "message-edit" | "message-reload";
|
|
157
157
|
};
|
|
158
158
|
/** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */
|
|
159
159
|
export type RunsError = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","createRunQueueAdapter","resolveEditCommand","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","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","Options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","state","commands","connection","setContext","transport","initialState","optimistic","draft","ctx","materialize","onCommandChange","update","status","params","onStateChange","onConnectionChange","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","error","onError","subscribe","dispatch","settled","type","threadRef","dispatchSend","message","sourceId","text","content","flatMap","part","join","setText","composer","next","runs","ThreadStatus","entries","RunState","entry","dispatching","stopping","nextDispatch","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","State","messages","liveRunId","sendCommand","reconnect","handleAppend","crypto","randomUUID","handleReload","parentId","handleEdit","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","UserCommands","Commands","Transport","TextPart","FilePart","mediaType","url","filename","UserMessage","id","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","runAnchorMessageId","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","RunsQueueEntry","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","reason","RunsError","MaterializeEffects","append","rollback","to","RunsState","Exclude","ConnectionState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/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 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 createRunQueueAdapter,\n resolveEditCommand,\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};\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 { state, commands, connection, setContext } = useStatewire<\n unknown,\n AnyCommands\n >({\n transport: options.transport,\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 === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n });\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n void setContextRef.current(value).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n const { 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 return {\n status: entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n runs:\n entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && { stopping: entry.stopping }),\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 };\n }, [state]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n runs,\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 inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo(\n (): StatewireThread.Extras => ({\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n status,\n inputRequests,\n runs,\n }),\n [dispatch, connection.reconnect, state, status, inputRequests, runs],\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 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\"]!({ ...payload, runId: runs.runId }).catch(\n (error: Error) => {\n latest.current.onError?.(error);\n },\n );\n },\n }),\n );\n threadRef.current = thread;\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 export type Extras = {\n [symbolStatewireExtras]: true;\n sendCommand: (command: Command) => void;\n reconnect: () => void;\n state: unknown;\n status: ThreadStatus;\n inputRequests: readonly InputRequestState[];\n runs: Runs;\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 export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\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 RunSteerCommand = {\n readonly type: \"run/steer\";\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 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 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, derived from the state: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status. */\n export type ThreadStatus = \"loading\" | \"ready\" | 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 /** 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 unacked batch handed to the run; absent between the ack and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"send-message\"\n | \"edit-message\"\n | \"reload-message\"\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 the ack. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The stopping window: present while a stop of the live run is underway; `\"edit-message\"` / `\"reload-message\"` pair with `nextDispatch`. */\n export type RunsStopping = {\n readonly reason: \"stop\" | \"edit-message\" | \"reload-message\";\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 readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */\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: Exclude<ThreadStatus, \"loading\">;\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 readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */\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 export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\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, acked, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n}\n\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 }\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":";;;;;;;;;;AAwCA,MAAasC,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;AACd;AAEA,MAAMC,oBA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,UAAU;EAC/C,CAAC,EACL;EACA,GAAI/E,QAAQkG,cAAcK,UAAU,EAAEC,UAAUnB,aAAa;EAC7DoB,kBAAkBC,gBAChB5D,SAASzE,uBAAuBgG,eAAeqC,aAAa3B,SAAS,CAAC;EACxE4B,0BAA0BC,aACxB9D,SAAS1E,yBAAyBiG,eAAeuC,UAAU7B,SAAS,CAAC;EACvE8B,gBAAgB;GACd,MAAMC,UAAU5G,OAAOC,QAAQ4G,cAAc;GAC7C,IACED,YAAYnH,KAAAA,MACX,OAAOmH,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAI9H,MAAM,mDAAmD;GACrE,SAAc,WAAW,CAAE;IAAE,GAAG8H;IAASzH,OAAOwE,KAAKxE;GAAM,CAAC,CAAC,CAACqD,OAC3DC,YAAiB;IAChBzC,OAAOC,QAAQyC,UAAUD,OAAK;GAChC,CACF;EACF;CACF,CAAC,CACH;CACAM,UAAU9C,UAAUqF;CACpB,OAAOA;AACT;AAEA,MAAa1G,mBACXkB,YAEAvD,SAASsD,kBAAkB,CAAC,CAACC,OAAuC;AAwWtEjD,uBACEgD,oBACAnD,eAAe+C,KAAAA,CAAkB,CAAC,CAAC+L,IACrC"}
|
|
1
|
+
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","createRunQueueAdapter","resolveEditCommand","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","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","Options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","state","commands","connection","setContext","transport","initialState","optimistic","draft","ctx","materialize","onCommandChange","update","status","params","onStateChange","onConnectionChange","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","error","onError","subscribe","dispatch","settled","type","threadRef","dispatchSend","message","sourceId","text","content","flatMap","part","join","setText","composer","next","runs","ThreadStatus","entries","RunState","entry","dispatching","stopping","nextDispatch","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","State","messages","liveRunId","sendCommand","reconnect","handleAppend","crypto","randomUUID","handleReload","parentId","handleEdit","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","UserCommands","Commands","Transport","TextPart","FilePart","mediaType","url","filename","UserMessage","id","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","runAnchorMessageId","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","RunsQueueEntry","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","reason","RunsError","MaterializeEffects","append","rollback","to","RunsState","Exclude","ConnectionState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/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 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 createRunQueueAdapter,\n resolveEditCommand,\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};\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 { state, commands, connection, setContext } = useStatewire<\n unknown,\n AnyCommands\n >({\n transport: options.transport,\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 === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n });\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n void setContextRef.current(value).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n const { 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 return {\n status: entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n runs:\n entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && { stopping: entry.stopping }),\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 };\n }, [state]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n runs,\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 inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo(\n (): StatewireThread.Extras => ({\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n status,\n inputRequests,\n runs,\n }),\n [dispatch, connection.reconnect, state, status, inputRequests, runs],\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 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\"]!({ ...payload, runId: runs.runId }).catch(\n (error: Error) => {\n latest.current.onError?.(error);\n },\n );\n },\n }),\n );\n threadRef.current = thread;\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 export type Extras = {\n [symbolStatewireExtras]: true;\n sendCommand: (command: Command) => void;\n reconnect: () => void;\n state: unknown;\n status: ThreadStatus;\n inputRequests: readonly InputRequestState[];\n runs: Runs;\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 export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\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 RunSteerCommand = {\n readonly type: \"run/steer\";\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 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 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, derived from the state: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status. */\n export type ThreadStatus = \"loading\" | \"ready\" | 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 /** 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 unacked batch handed to the run; absent between the ack 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 the ack. */\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 readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */\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: Exclude<ThreadStatus, \"loading\">;\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 readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */\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 export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\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, acked, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n}\n\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 }\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":";;;;;;;;;;AAwCA,MAAasC,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;AACd;AAEA,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOlC,kBAAkB+B,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,sBACJC,YAC2B;CAC3B,MAAME,SAAS3D,OAAOyD,OAAO;CAC7BE,OAAOC,UAAUH;CAEjB,MAAM,CAACI,SAASC,cAAc7D,SA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;IAAE,GAAG8H;IAASzH,OAAOwE,KAAKxE;GAAM,CAAC,CAAC,CAACqD,OAC3DC,YAAiB;IAChBzC,OAAOC,QAAQyC,UAAUD,OAAK;GAChC,CACF;EACF;CACF,CAAC,CACH;CACAM,UAAU9C,UAAUqF;CACpB,OAAOA;AACT;AAEA,MAAa1G,mBACXkB,YAEAvD,SAASsD,kBAAkB,CAAC,CAACC,OAAuC;AAwWtEjD,uBACEgD,oBACAnD,eAAe+C,KAAAA,CAAkB,CAAC,CAAC+L,IACrC"}
|
package/dist/runsOptimistic.js
CHANGED
|
@@ -38,7 +38,7 @@ const enqueueOrSteer = (draft, command, runId) => {
|
|
|
38
38
|
}
|
|
39
39
|
const steer = command.type === "run/steer";
|
|
40
40
|
if (steer ? status === "ready" || status === "input-required" : sourceLane === void 0 && (status === "ready" || (status === "stopped" || status === "error") && run !== void 0 && run.queue.length === 0 && run.steerQueue.length === 0)) {
|
|
41
|
-
const trigger = status === "error" ? "error-continue" : status === "stopped" ? "stop-continue" : "send
|
|
41
|
+
const trigger = status === "error" ? "error-continue" : status === "stopped" ? "stop-continue" : "message-send";
|
|
42
42
|
const target = startRun(draft, runId);
|
|
43
43
|
if (steer) {
|
|
44
44
|
if (sourceLane === target.steerQueue) target.steerQueue.splice(sourceIndex, 0, entry);
|
|
@@ -77,7 +77,7 @@ const runsOptimistic = (mount, command, ctx) => {
|
|
|
77
77
|
case "run/edit": {
|
|
78
78
|
const { message, runAnchorMessageId } = command.params[0];
|
|
79
79
|
const dispatch = {
|
|
80
|
-
trigger: "edit
|
|
80
|
+
trigger: "message-edit",
|
|
81
81
|
messages: [{ ...message }],
|
|
82
82
|
rollbackTo: runAnchorMessageId
|
|
83
83
|
};
|
|
@@ -89,7 +89,7 @@ const runsOptimistic = (mount, command, ctx) => {
|
|
|
89
89
|
case "run/reload": {
|
|
90
90
|
const { runAnchorMessageId } = command.params[0];
|
|
91
91
|
const dispatch = {
|
|
92
|
-
trigger: "reload
|
|
92
|
+
trigger: "message-reload",
|
|
93
93
|
messages: [],
|
|
94
94
|
rollbackTo: runAnchorMessageId
|
|
95
95
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runsOptimistic.js","names":["Statewire","StatewireClient","StatewireThread","LaneEntry","id","role","parts","TextPart","FilePart","metadata","Record","meta","Dispatch","trigger","messages","rollbackTo","RunEntry","runId","status","RunStatus","queue","steerQueue","dispatching","stopping","reason","nextDispatch","inputRequests","response","error","RunsDraft","Exclude","ThreadStatus","runs","startRun","draft","entry","insert","lane","insertAfter","insertBefore","Placement","index","undefined","findIndex","e","length","splice","enqueueOrSteer","command","RunEnqueueCommand","RunSteerCommand","run","message","messageId","some","sourceLane","find","l","sourceIndex","steer","type","direct","target","push","continues","Error","hasPlacement","stageRewind","dispatch","runsOptimistic","mount","Command","args","ctx","OptimisticContext","commandRunId","params","seq","method","runAnchorMessageId","RunEditCommand","RunReloadCommand","RunDequeueCommand","requestId","RunInputCommand","requests","r","every"],"sources":["../src/runsOptimistic.ts"],"sourcesContent":["import type { Statewire, StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\ntype LaneEntry = {\n id: string;\n role: \"user\";\n parts: readonly (StatewireThread.TextPart | StatewireThread.FilePart)[];\n metadata?: Record<string, unknown>;\n meta?: unknown;\n};\n\ntype Dispatch = {\n trigger: string;\n messages: LaneEntry[];\n rollbackTo?: string | null;\n};\n\ntype RunEntry = {\n runId: string | null;\n status: StatewireThread.RunStatus;\n queue: LaneEntry[];\n steerQueue: LaneEntry[];\n dispatching?: Dispatch;\n stopping?: { reason: \"stop\" | \"edit-message\" | \"reload-message\" };\n nextDispatch?: Dispatch;\n inputRequests?: { id: string; response?: unknown }[];\n error?: unknown;\n};\n\ntype RunsDraft = {\n status: Exclude<StatewireThread.ThreadStatus, \"loading\">;\n runs?: RunEntry[];\n};\n\nconst startRun = (draft: RunsDraft, runId: string): RunEntry => {\n const entry = ((draft.runs ??= [])[0] ??= {\n runId: null,\n status: \"running\",\n queue: [],\n steerQueue: [],\n });\n entry.status = \"running\";\n // A live run keeps its identity; a mint folds the client-generated id.\n if (entry.runId === null) entry.runId = runId;\n delete entry.error;\n delete entry.inputRequests;\n draft.status = \"running\";\n return entry;\n};\n\nconst insert = (\n lane: LaneEntry[],\n entry: LaneEntry,\n { insertAfter, insertBefore }: StatewireThread.Placement,\n): void => {\n const index =\n insertAfter !== undefined\n ? insertAfter === null\n ? 0\n : lane.findIndex((e) => e.id === insertAfter) + 1\n : insertBefore === undefined || insertBefore === null\n ? lane.length\n : lane.findIndex((e) => e.id === insertBefore);\n lane.splice(index < 0 ? lane.length : index, 0, entry);\n};\n\nconst enqueueOrSteer = (\n draft: RunsDraft,\n command: StatewireThread.RunEnqueueCommand | StatewireThread.RunSteerCommand,\n runId: string,\n): void => {\n const run = draft.runs?.[0];\n // The entry status is the truth; hosts replicating the top-level projection agree.\n const status = run?.status ?? \"ready\";\n const id = \"message\" in command ? command.message.id : command.messageId;\n // In dispatch limbo the canonical state already tells the story: no fold.\n if (run?.dispatching?.messages.some((e) => e.id === id)) return;\n const sourceLane =\n run === undefined\n ? undefined\n : [run.queue, run.steerQueue].find((l) => l.some((e) => e.id === id));\n\n let entry: LaneEntry;\n let sourceIndex = -1;\n if (sourceLane !== undefined) {\n sourceIndex = sourceLane.findIndex((e) => e.id === id);\n entry = sourceLane.splice(sourceIndex, 1)[0]!;\n if (\"message\" in command) {\n entry.parts = command.message.parts;\n if (command.message.metadata !== undefined)\n entry.metadata = command.message.metadata;\n }\n } else {\n if (!(\"message\" in command)) return;\n entry = { ...command.message };\n }\n\n const steer = command.type === \"run/steer\";\n const direct = steer\n ? status === \"ready\" || status === \"input-required\"\n : sourceLane === undefined &&\n (status === \"ready\" ||\n ((status === \"stopped\" || status === \"error\") &&\n run !== undefined &&\n run.queue.length === 0 &&\n run.steerQueue.length === 0));\n if (direct) {\n const trigger =\n status === \"error\"\n ? \"error-continue\"\n : status === \"stopped\"\n ? \"stop-continue\"\n : \"send-message\";\n const target = startRun(draft, runId);\n if (steer) {\n // The whole steer lane rides the dispatch, in lane order.\n if (sourceLane === target.steerQueue)\n target.steerQueue.splice(sourceIndex, 0, entry);\n else target.steerQueue.push(entry);\n target.dispatching = {\n trigger,\n messages: target.steerQueue.splice(0),\n };\n } else target.dispatching = { trigger, messages: [entry] };\n return;\n }\n const continues = steer && status !== \"running\";\n\n if (run === undefined)\n throw new Error(\"statewire: non-direct fold without a run entry\");\n const lane = steer ? run.steerQueue : run.queue;\n const hasPlacement =\n command.insertAfter !== undefined || command.insertBefore !== undefined;\n if (sourceLane === lane && !hasPlacement) lane.splice(sourceIndex, 0, entry);\n else insert(lane, entry, command);\n if (continues) startRun(draft, runId);\n};\n\nconst stageRewind = (run: RunEntry, dispatch: Dispatch): void => {\n run.stopping = {\n reason: dispatch.trigger as \"edit-message\" | \"reload-message\",\n };\n run.nextDispatch = dispatch;\n};\n\n/** The run dialect's optimistic reducer: folds an unsettled `run/*` command into the mount draft. */\nexport const runsOptimistic = (\n mount: unknown,\n command: Statewire.Command<Record<string, (...args: any[]) => unknown>>,\n ctx: StatewireClient.OptimisticContext,\n): void => {\n const draft = mount as RunsDraft;\n const commandRunId = (command.params[0] as { runId?: string } | undefined)\n ?.runId;\n const runId = commandRunId ?? `optimistic-${ctx.seq}`;\n switch (command.method) {\n case \"run/enqueue\":\n case \"run/steer\": {\n enqueueOrSteer(\n draft,\n command.params[0] as\n | StatewireThread.RunEnqueueCommand\n | StatewireThread.RunSteerCommand,\n runId,\n );\n break;\n }\n case \"run/edit\": {\n const { message, runAnchorMessageId } = command\n .params[0] as StatewireThread.RunEditCommand;\n const dispatch: Dispatch = {\n trigger: \"edit-message\",\n messages: [{ ...message }],\n rollbackTo: runAnchorMessageId,\n };\n const run = draft.runs?.[0];\n if (run?.status === \"running\") stageRewind(run, dispatch);\n else startRun(draft, runId).dispatching = dispatch;\n break;\n }\n case \"run/reload\": {\n const { runAnchorMessageId } = command\n .params[0] as StatewireThread.RunReloadCommand;\n const dispatch: Dispatch = {\n trigger: \"reload-message\",\n messages: [],\n rollbackTo: runAnchorMessageId,\n };\n const run = draft.runs?.[0];\n if (run?.status === \"running\") stageRewind(run, dispatch);\n else startRun(draft, runId).dispatching = dispatch;\n break;\n }\n case \"run/stop\": {\n const run = draft.runs?.[0];\n if (run?.status !== \"running\") break;\n run.stopping = { reason: \"stop\" };\n delete run.nextDispatch;\n break;\n }\n case \"run/continue\": {\n const run = draft.runs?.[0];\n if (run !== undefined) run.steerQueue = [];\n startRun(draft, runId);\n break;\n }\n case \"run/dequeue\": {\n const { messageId } = command\n .params[0] as StatewireThread.RunDequeueCommand;\n const run = draft.runs?.[0];\n if (run === undefined) break;\n for (const lane of [run.queue, run.steerQueue]) {\n const index = lane.findIndex((e) => e.id === messageId);\n if (index !== -1) lane.splice(index, 1);\n }\n break;\n }\n case \"run/input\": {\n const { requestId, response } = command\n .params[0] as StatewireThread.RunInputCommand;\n const requests = draft.runs?.[0]?.inputRequests;\n if (requests === undefined) break;\n const target = requests.find((r) => r.id === requestId);\n if (target === undefined) break;\n target.response = response;\n if (requests.every((r) => \"response\" in r)) startRun(draft, runId);\n break;\n }\n default:\n break;\n }\n};\n"],"mappings":";AAkCA,MAAMiC,YAAYC,OAAkBjB,UAA4B;CAC9D,MAAMkB,QAAS,CAACD,MAAMF,SAAS,CAAA,EAAA,CAAI,OAAO;EACxCf,OAAO;EACPC,QAAQ;EACRE,OAAO,CAAA;EACPC,YAAY,CAAA;CACd;CACAc,MAAMjB,SAAS;CAEf,IAAIiB,MAAMlB,UAAU,MAAMkB,MAAMlB,QAAQA;CACxC,OAAOkB,MAAMP;CACb,OAAOO,MAAMT;CACbQ,MAAMhB,SAAS;CACf,OAAOiB;AACT;AAEA,MAAMC,UACJC,MACAF,OACA,EAAEG,aAAaC,mBACN;CACT,MAAME,QACJH,gBAAgBI,KAAAA,IACZJ,gBAAgB,OACd,IACAD,KAAKM,WAAWC,MAAMA,EAAExC,OA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C;GACA;EACF;EACA,KAAK,aAAa;GAChB,MAAM,EAAE0C,WAAWxD,aAAaqB,QAC7B4B,OAAO;GACV,MAAMS,WAAWnD,MAAMF,OAAO,EAAE,EAAEN;GAClC,IAAI2D,aAAa3C,KAAAA,GAAW;GAC5B,MAAMoB,SAASuB,SAAS7B,MAAM8B,MAAMA,EAAElF,OAAO+E,SAAS;GACtD,IAAIrB,WAAWpB,KAAAA,GAAW;GAC1BoB,OAAOnC,WAAWA;GAClB,IAAI0D,SAASE,OAAOD,MAAM,cAAcA,CAAC,GAAGrD,SAASC,OAAOjB,KAAK;GACjE;EACF;CAGF;AACF"}
|
|
1
|
+
{"version":3,"file":"runsOptimistic.js","names":["Statewire","StatewireClient","StatewireThread","LaneEntry","id","role","parts","TextPart","FilePart","metadata","Record","meta","Dispatch","trigger","messages","rollbackTo","RunEntry","runId","status","RunStatus","queue","steerQueue","dispatching","stopping","reason","nextDispatch","inputRequests","response","error","RunsDraft","Exclude","ThreadStatus","runs","startRun","draft","entry","insert","lane","insertAfter","insertBefore","Placement","index","undefined","findIndex","e","length","splice","enqueueOrSteer","command","RunEnqueueCommand","RunSteerCommand","run","message","messageId","some","sourceLane","find","l","sourceIndex","steer","type","direct","target","push","continues","Error","hasPlacement","stageRewind","dispatch","runsOptimistic","mount","Command","args","ctx","OptimisticContext","commandRunId","params","seq","method","runAnchorMessageId","RunEditCommand","RunReloadCommand","RunDequeueCommand","requestId","RunInputCommand","requests","r","every"],"sources":["../src/runsOptimistic.ts"],"sourcesContent":["import type { Statewire, StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\ntype LaneEntry = {\n id: string;\n role: \"user\";\n parts: readonly (StatewireThread.TextPart | StatewireThread.FilePart)[];\n metadata?: Record<string, unknown>;\n meta?: unknown;\n};\n\ntype Dispatch = {\n trigger: string;\n messages: LaneEntry[];\n rollbackTo?: string | null;\n};\n\ntype RunEntry = {\n runId: string | null;\n status: StatewireThread.RunStatus;\n queue: LaneEntry[];\n steerQueue: LaneEntry[];\n dispatching?: Dispatch;\n stopping?: { reason: \"stop\" | \"message-edit\" | \"message-reload\" };\n nextDispatch?: Dispatch;\n inputRequests?: { id: string; response?: unknown }[];\n error?: unknown;\n};\n\ntype RunsDraft = {\n status: Exclude<StatewireThread.ThreadStatus, \"loading\">;\n runs?: RunEntry[];\n};\n\nconst startRun = (draft: RunsDraft, runId: string): RunEntry => {\n const entry = ((draft.runs ??= [])[0] ??= {\n runId: null,\n status: \"running\",\n queue: [],\n steerQueue: [],\n });\n entry.status = \"running\";\n // A live run keeps its identity; a mint folds the client-generated id.\n if (entry.runId === null) entry.runId = runId;\n delete entry.error;\n delete entry.inputRequests;\n draft.status = \"running\";\n return entry;\n};\n\nconst insert = (\n lane: LaneEntry[],\n entry: LaneEntry,\n { insertAfter, insertBefore }: StatewireThread.Placement,\n): void => {\n const index =\n insertAfter !== undefined\n ? insertAfter === null\n ? 0\n : lane.findIndex((e) => e.id === insertAfter) + 1\n : insertBefore === undefined || insertBefore === null\n ? lane.length\n : lane.findIndex((e) => e.id === insertBefore);\n lane.splice(index < 0 ? lane.length : index, 0, entry);\n};\n\nconst enqueueOrSteer = (\n draft: RunsDraft,\n command: StatewireThread.RunEnqueueCommand | StatewireThread.RunSteerCommand,\n runId: string,\n): void => {\n const run = draft.runs?.[0];\n // The entry status is the truth; hosts replicating the top-level projection agree.\n const status = run?.status ?? \"ready\";\n const id = \"message\" in command ? command.message.id : command.messageId;\n // In dispatch limbo the canonical state already tells the story: no fold.\n if (run?.dispatching?.messages.some((e) => e.id === id)) return;\n const sourceLane =\n run === undefined\n ? undefined\n : [run.queue, run.steerQueue].find((l) => l.some((e) => e.id === id));\n\n let entry: LaneEntry;\n let sourceIndex = -1;\n if (sourceLane !== undefined) {\n sourceIndex = sourceLane.findIndex((e) => e.id === id);\n entry = sourceLane.splice(sourceIndex, 1)[0]!;\n if (\"message\" in command) {\n entry.parts = command.message.parts;\n if (command.message.metadata !== undefined)\n entry.metadata = command.message.metadata;\n }\n } else {\n if (!(\"message\" in command)) return;\n entry = { ...command.message };\n }\n\n const steer = command.type === \"run/steer\";\n const direct = steer\n ? status === \"ready\" || status === \"input-required\"\n : sourceLane === undefined &&\n (status === \"ready\" ||\n ((status === \"stopped\" || status === \"error\") &&\n run !== undefined &&\n run.queue.length === 0 &&\n run.steerQueue.length === 0));\n if (direct) {\n const trigger =\n status === \"error\"\n ? \"error-continue\"\n : status === \"stopped\"\n ? \"stop-continue\"\n : \"message-send\";\n const target = startRun(draft, runId);\n if (steer) {\n // The whole steer lane rides the dispatch, in lane order.\n if (sourceLane === target.steerQueue)\n target.steerQueue.splice(sourceIndex, 0, entry);\n else target.steerQueue.push(entry);\n target.dispatching = {\n trigger,\n messages: target.steerQueue.splice(0),\n };\n } else target.dispatching = { trigger, messages: [entry] };\n return;\n }\n const continues = steer && status !== \"running\";\n\n if (run === undefined)\n throw new Error(\"statewire: non-direct fold without a run entry\");\n const lane = steer ? run.steerQueue : run.queue;\n const hasPlacement =\n command.insertAfter !== undefined || command.insertBefore !== undefined;\n if (sourceLane === lane && !hasPlacement) lane.splice(sourceIndex, 0, entry);\n else insert(lane, entry, command);\n if (continues) startRun(draft, runId);\n};\n\nconst stageRewind = (run: RunEntry, dispatch: Dispatch): void => {\n run.stopping = {\n reason: dispatch.trigger as \"message-edit\" | \"message-reload\",\n };\n run.nextDispatch = dispatch;\n};\n\n/** The run dialect's optimistic reducer: folds an unsettled `run/*` command into the mount draft. */\nexport const runsOptimistic = (\n mount: unknown,\n command: Statewire.Command<Record<string, (...args: any[]) => unknown>>,\n ctx: StatewireClient.OptimisticContext,\n): void => {\n const draft = mount as RunsDraft;\n const commandRunId = (command.params[0] as { runId?: string } | undefined)\n ?.runId;\n const runId = commandRunId ?? `optimistic-${ctx.seq}`;\n switch (command.method) {\n case \"run/enqueue\":\n case \"run/steer\": {\n enqueueOrSteer(\n draft,\n command.params[0] as\n | StatewireThread.RunEnqueueCommand\n | StatewireThread.RunSteerCommand,\n runId,\n );\n break;\n }\n case \"run/edit\": {\n const { message, runAnchorMessageId } = command\n .params[0] as StatewireThread.RunEditCommand;\n const dispatch: Dispatch = {\n trigger: \"message-edit\",\n messages: [{ ...message }],\n rollbackTo: runAnchorMessageId,\n };\n const run = draft.runs?.[0];\n if (run?.status === \"running\") stageRewind(run, dispatch);\n else startRun(draft, runId).dispatching = dispatch;\n break;\n }\n case \"run/reload\": {\n const { runAnchorMessageId } = command\n .params[0] as StatewireThread.RunReloadCommand;\n const dispatch: Dispatch = {\n trigger: \"message-reload\",\n messages: [],\n rollbackTo: runAnchorMessageId,\n };\n const run = draft.runs?.[0];\n if (run?.status === \"running\") stageRewind(run, dispatch);\n else startRun(draft, runId).dispatching = dispatch;\n break;\n }\n case \"run/stop\": {\n const run = draft.runs?.[0];\n if (run?.status !== \"running\") break;\n run.stopping = { reason: \"stop\" };\n delete run.nextDispatch;\n break;\n }\n case \"run/continue\": {\n const run = draft.runs?.[0];\n if (run !== undefined) run.steerQueue = [];\n startRun(draft, runId);\n break;\n }\n case \"run/dequeue\": {\n const { messageId } = command\n .params[0] as StatewireThread.RunDequeueCommand;\n const run = draft.runs?.[0];\n if (run === undefined) break;\n for (const lane of [run.queue, run.steerQueue]) {\n const index = lane.findIndex((e) => e.id === messageId);\n if (index !== -1) lane.splice(index, 1);\n }\n break;\n }\n case \"run/input\": {\n const { requestId, response } = command\n .params[0] as StatewireThread.RunInputCommand;\n const requests = draft.runs?.[0]?.inputRequests;\n if (requests === undefined) break;\n const target = requests.find((r) => r.id === requestId);\n if (target === undefined) break;\n target.response = response;\n if (requests.every((r) => \"response\" in r)) startRun(draft, runId);\n break;\n }\n default:\n break;\n }\n};\n"],"mappings":";AAkCA,MAAMiC,YAAYC,OAAkBjB,UAA4B;CAC9D,MAAMkB,QAAS,CAACD,MAAMF,SAAS,CAAA,EAAA,CAAI,OAAO;EACxCf,OAAO;EACPC,QAAQ;EACRE,OAAO,CAAA;EACPC,YAAY,CAAA;CACd;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M,EAAEoC,cAAcL,QACnB4B,OAAO;GACV,MAAMzB,MAAMjB,MAAMF,OAAO;GACzB,IAAImB,QAAQT,KAAAA,GAAW;GACvB,KAAK,MAAML,QAAQ,CAACc,IAAI/B,OAAO+B,IAAI9B,UAAU,GAAG;IAC9C,MAAMoB,QAAQJ,KAAKM,WAAWC,MAAMA,EAAExC,OAAOiD,SAAS;IACtD,IAAIZ,UAAU,IAAIJ,KAAKS,OAAOL,OAAO,CAAC;GACxC;GACA;EACF;EACA,KAAK,aAAa;GAChB,MAAM,EAAE0C,WAAWxD,aAAaqB,QAC7B4B,OAAO;GACV,MAAMS,WAAWnD,MAAMF,OAAO,EAAE,EAAEN;GAClC,IAAI2D,aAAa3C,KAAAA,GAAW;GAC5B,MAAMoB,SAASuB,SAAS7B,MAAM8B,MAAMA,EAAElF,OAAO+E,SAAS;GACtD,IAAIrB,WAAWpB,KAAAA,GAAW;GAC1BoB,OAAOnC,WAAWA;GAClB,IAAI0D,SAASE,OAAOD,MAAM,cAAcA,CAAC,GAAGrD,SAASC,OAAOjB,KAAK;GACjE;EACF;CAGF;AACF"}
|
package/package.json
CHANGED
|
@@ -277,9 +277,9 @@ describe("StatewireThread runs mode", () => {
|
|
|
277
277
|
withRun({
|
|
278
278
|
status: "running",
|
|
279
279
|
runId: "run-1",
|
|
280
|
-
stopping: { reason: "edit
|
|
280
|
+
stopping: { reason: "message-edit" },
|
|
281
281
|
nextDispatch: {
|
|
282
|
-
trigger: "edit
|
|
282
|
+
trigger: "message-edit",
|
|
283
283
|
messages: [
|
|
284
284
|
{ id: "m1b", role: "user", parts: [{ type: "text", text: "b" }] },
|
|
285
285
|
],
|
|
@@ -290,14 +290,14 @@ describe("StatewireThread runs mode", () => {
|
|
|
290
290
|
const { aui, runs } = mountThread({ transport: server.transport });
|
|
291
291
|
|
|
292
292
|
await waitFor(() => expect(threadStatus(aui())).toBe("running"));
|
|
293
|
-
expect(runs().stopping).toEqual({ reason: "edit
|
|
294
|
-
expect(runs().nextDispatch!.trigger).toBe("edit
|
|
293
|
+
expect(runs().stopping).toEqual({ reason: "message-edit" });
|
|
294
|
+
expect(runs().nextDispatch!.trigger).toBe("message-edit");
|
|
295
295
|
expect(runs().dispatching).toBeUndefined();
|
|
296
296
|
|
|
297
297
|
act(() => {
|
|
298
298
|
const entry = server.cell.state!.runs![0]!;
|
|
299
299
|
entry.dispatching = {
|
|
300
|
-
trigger: "edit
|
|
300
|
+
trigger: "message-edit",
|
|
301
301
|
messages: [
|
|
302
302
|
{ id: "m1b", role: "user", parts: [{ type: "text", text: "b" }] },
|
|
303
303
|
],
|
|
@@ -308,7 +308,7 @@ describe("StatewireThread runs mode", () => {
|
|
|
308
308
|
});
|
|
309
309
|
await waitFor(() => expect(runs().stopping).toBeUndefined());
|
|
310
310
|
expect(runs().nextDispatch).toBeUndefined();
|
|
311
|
-
expect(runs().dispatching!.trigger).toBe("edit
|
|
311
|
+
expect(runs().dispatching!.trigger).toBe("message-edit");
|
|
312
312
|
});
|
|
313
313
|
|
|
314
314
|
it("stamps the live run's id onto run/stop", async () => {
|
|
@@ -402,7 +402,7 @@ describe("StatewireThread runs mode", () => {
|
|
|
402
402
|
status: "running",
|
|
403
403
|
runId: "run-1",
|
|
404
404
|
dispatching: {
|
|
405
|
-
trigger: "send
|
|
405
|
+
trigger: "message-send",
|
|
406
406
|
messages: [
|
|
407
407
|
{ id: "d1", role: "user", parts: [{ type: "text", text: "go" }] },
|
|
408
408
|
],
|
|
@@ -427,7 +427,7 @@ describe("StatewireThread runs mode", () => {
|
|
|
427
427
|
status: "running",
|
|
428
428
|
runId: "run-1",
|
|
429
429
|
dispatching: {
|
|
430
|
-
trigger: "send
|
|
430
|
+
trigger: "message-send",
|
|
431
431
|
messages: [
|
|
432
432
|
{ id: "d1", role: "user", parts: [{ type: "text", text: "go" }] },
|
|
433
433
|
],
|
|
@@ -480,7 +480,7 @@ describe("StatewireThread runs mode", () => {
|
|
|
480
480
|
status: "running",
|
|
481
481
|
runId: "run-1",
|
|
482
482
|
dispatching: {
|
|
483
|
-
trigger: "edit
|
|
483
|
+
trigger: "message-edit",
|
|
484
484
|
messages: [
|
|
485
485
|
{
|
|
486
486
|
id: "u2b",
|
|
@@ -516,7 +516,7 @@ describe("StatewireThread runs mode", () => {
|
|
|
516
516
|
status: "running",
|
|
517
517
|
runId: "run-1",
|
|
518
518
|
dispatching: {
|
|
519
|
-
trigger: "reload
|
|
519
|
+
trigger: "message-reload",
|
|
520
520
|
messages: [],
|
|
521
521
|
rollbackTo: "u1",
|
|
522
522
|
},
|
|
@@ -546,7 +546,7 @@ describe("StatewireThread runs mode", () => {
|
|
|
546
546
|
status: "running",
|
|
547
547
|
runId: "run-1",
|
|
548
548
|
dispatching: {
|
|
549
|
-
trigger: "edit
|
|
549
|
+
trigger: "message-edit",
|
|
550
550
|
messages: [
|
|
551
551
|
{
|
|
552
552
|
id: "u1b",
|
package/src/StatewireThread.ts
CHANGED
|
@@ -499,9 +499,9 @@ export namespace StatewireThread {
|
|
|
499
499
|
/** The dispatch record — the unacked batch handed to the run; absent between the ack and the next dispatch or take. */
|
|
500
500
|
export type RunsDispatch = {
|
|
501
501
|
readonly trigger:
|
|
502
|
-
| "send
|
|
503
|
-
| "edit
|
|
504
|
-
| "reload
|
|
502
|
+
| "message-send"
|
|
503
|
+
| "message-edit"
|
|
504
|
+
| "message-reload"
|
|
505
505
|
| "input-resume"
|
|
506
506
|
| "error-continue"
|
|
507
507
|
| "stop-continue"
|
|
@@ -515,9 +515,9 @@ export namespace StatewireThread {
|
|
|
515
515
|
readonly inputOutcomes?: readonly RunsInputOutcome[];
|
|
516
516
|
};
|
|
517
517
|
|
|
518
|
-
/** The stopping window: present while a stop of the live run is underway; `"edit
|
|
518
|
+
/** The stopping window: present while a stop of the live run is underway; `"message-edit"` / `"message-reload"` pair with `nextDispatch`. */
|
|
519
519
|
export type RunsStopping = {
|
|
520
|
-
readonly reason: "stop" | "edit
|
|
520
|
+
readonly reason: "stop" | "message-edit" | "message-reload";
|
|
521
521
|
};
|
|
522
522
|
|
|
523
523
|
/** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */
|
|
@@ -53,7 +53,7 @@ describe("runsMaterialize", () => {
|
|
|
53
53
|
const { appended, effects } = record();
|
|
54
54
|
runsMaterialize(
|
|
55
55
|
mount({
|
|
56
|
-
trigger: "send
|
|
56
|
+
trigger: "message-send",
|
|
57
57
|
messages: [message("m1"), message("m2")],
|
|
58
58
|
}),
|
|
59
59
|
effects,
|
|
@@ -65,14 +65,14 @@ describe("runsMaterialize", () => {
|
|
|
65
65
|
const { appended, rollbacks, effects } = record();
|
|
66
66
|
runsMaterialize(
|
|
67
67
|
mount({
|
|
68
|
-
trigger: "edit
|
|
68
|
+
trigger: "message-edit",
|
|
69
69
|
messages: [message("m3")],
|
|
70
70
|
rollbackTo: "m1",
|
|
71
71
|
}),
|
|
72
72
|
effects,
|
|
73
73
|
);
|
|
74
74
|
runsMaterialize(
|
|
75
|
-
mount({ trigger: "reload
|
|
75
|
+
mount({ trigger: "message-reload", messages: [], rollbackTo: null }),
|
|
76
76
|
effects,
|
|
77
77
|
);
|
|
78
78
|
expect(appended).toEqual(["(rollback)", "m3", "(rollback)"]);
|
|
@@ -82,7 +82,7 @@ describe("runsMaterialize", () => {
|
|
|
82
82
|
it("throws on a rewind dispatch without a rollback effect", () => {
|
|
83
83
|
expect(() =>
|
|
84
84
|
runsMaterialize(
|
|
85
|
-
mount({ trigger: "edit
|
|
85
|
+
mount({ trigger: "message-edit", messages: [], rollbackTo: "m1" }),
|
|
86
86
|
{ append: () => {} },
|
|
87
87
|
),
|
|
88
88
|
).toThrow("rollbackTo");
|
|
@@ -87,7 +87,7 @@ describe("runsOptimistic", () => {
|
|
|
87
87
|
expect(draft.status).toBe("running");
|
|
88
88
|
expect(run(draft).runId).toBe("run-1");
|
|
89
89
|
expect(run(draft).steerQueue).toEqual([]);
|
|
90
|
-
expect(run(draft).dispatching.trigger).toBe("send
|
|
90
|
+
expect(run(draft).dispatching.trigger).toBe("message-send");
|
|
91
91
|
expect(run(draft).dispatching.messages.map((e: Draft) => e.id)).toEqual([
|
|
92
92
|
"s1",
|
|
93
93
|
"s2",
|
|
@@ -105,7 +105,7 @@ describe("runsOptimistic", () => {
|
|
|
105
105
|
expect(ready.status).toBe("running");
|
|
106
106
|
expect(run(ready).runId).toBe("mint-1");
|
|
107
107
|
expect(run(ready).queue).toEqual([]);
|
|
108
|
-
expect(run(ready).dispatching.trigger).toBe("send
|
|
108
|
+
expect(run(ready).dispatching.trigger).toBe("message-send");
|
|
109
109
|
expect(run(ready).dispatching.messages.map((e: Draft) => e.id)).toEqual([
|
|
110
110
|
"a",
|
|
111
111
|
]);
|
|
@@ -155,7 +155,7 @@ describe("runsOptimistic", () => {
|
|
|
155
155
|
const draft = mount({
|
|
156
156
|
status: "running",
|
|
157
157
|
runId: "r",
|
|
158
|
-
dispatching: { trigger: "send
|
|
158
|
+
dispatching: { trigger: "message-send", messages: [message("d1")] },
|
|
159
159
|
});
|
|
160
160
|
apply(draft, "run/enqueue", {
|
|
161
161
|
type: "run/enqueue",
|
|
@@ -222,7 +222,7 @@ describe("runsOptimistic", () => {
|
|
|
222
222
|
expect(run(draft).runId).toBe("run-1");
|
|
223
223
|
expect(run(draft).inputRequests).toBeUndefined();
|
|
224
224
|
expect(run(draft).dispatching).toEqual({
|
|
225
|
-
trigger: "edit
|
|
225
|
+
trigger: "message-edit",
|
|
226
226
|
messages: [message("m2b")],
|
|
227
227
|
rollbackTo: "a1",
|
|
228
228
|
});
|
|
@@ -232,7 +232,7 @@ describe("runsOptimistic", () => {
|
|
|
232
232
|
const draft = mount({
|
|
233
233
|
status: "running",
|
|
234
234
|
runId: "run-1",
|
|
235
|
-
dispatching: { trigger: "send
|
|
235
|
+
dispatching: { trigger: "message-send", messages: [message("m1")] },
|
|
236
236
|
});
|
|
237
237
|
apply(draft, "run/edit", {
|
|
238
238
|
type: "run/edit",
|
|
@@ -243,9 +243,9 @@ describe("runsOptimistic", () => {
|
|
|
243
243
|
});
|
|
244
244
|
expect(draft.status).toBe("running");
|
|
245
245
|
expect(run(draft).status).toBe("running");
|
|
246
|
-
expect(run(draft).stopping).toEqual({ reason: "edit
|
|
246
|
+
expect(run(draft).stopping).toEqual({ reason: "message-edit" });
|
|
247
247
|
expect(run(draft).nextDispatch).toEqual({
|
|
248
|
-
trigger: "edit
|
|
248
|
+
trigger: "message-edit",
|
|
249
249
|
messages: [message("m1b")],
|
|
250
250
|
rollbackTo: "p0",
|
|
251
251
|
});
|
|
@@ -262,9 +262,9 @@ describe("runsOptimistic", () => {
|
|
|
262
262
|
sourceId: "a1",
|
|
263
263
|
runAnchorMessageId: "m1",
|
|
264
264
|
});
|
|
265
|
-
expect(run(draft).stopping).toEqual({ reason: "reload
|
|
265
|
+
expect(run(draft).stopping).toEqual({ reason: "message-reload" });
|
|
266
266
|
expect(run(draft).nextDispatch).toEqual({
|
|
267
|
-
trigger: "reload
|
|
267
|
+
trigger: "message-reload",
|
|
268
268
|
messages: [],
|
|
269
269
|
rollbackTo: "m1",
|
|
270
270
|
});
|
|
@@ -301,7 +301,7 @@ describe("runsOptimistic", () => {
|
|
|
301
301
|
expect(run(draft).runId).toBe("run-1");
|
|
302
302
|
expect(run(draft).error).toBeUndefined();
|
|
303
303
|
expect(run(draft).dispatching).toEqual({
|
|
304
|
-
trigger: "reload
|
|
304
|
+
trigger: "message-reload",
|
|
305
305
|
messages: [],
|
|
306
306
|
rollbackTo: null,
|
|
307
307
|
});
|
|
@@ -334,7 +334,7 @@ describe("runsOptimistic", () => {
|
|
|
334
334
|
status: "running",
|
|
335
335
|
queue: [],
|
|
336
336
|
steerQueue: [],
|
|
337
|
-
dispatching: { trigger: "send
|
|
337
|
+
dispatching: { trigger: "message-send", messages: [message("s1")] },
|
|
338
338
|
});
|
|
339
339
|
});
|
|
340
340
|
|
package/src/runsOptimistic.ts
CHANGED
|
@@ -21,7 +21,7 @@ type RunEntry = {
|
|
|
21
21
|
queue: LaneEntry[];
|
|
22
22
|
steerQueue: LaneEntry[];
|
|
23
23
|
dispatching?: Dispatch;
|
|
24
|
-
stopping?: { reason: "stop" | "edit
|
|
24
|
+
stopping?: { reason: "stop" | "message-edit" | "message-reload" };
|
|
25
25
|
nextDispatch?: Dispatch;
|
|
26
26
|
inputRequests?: { id: string; response?: unknown }[];
|
|
27
27
|
error?: unknown;
|
|
@@ -110,7 +110,7 @@ const enqueueOrSteer = (
|
|
|
110
110
|
? "error-continue"
|
|
111
111
|
: status === "stopped"
|
|
112
112
|
? "stop-continue"
|
|
113
|
-
: "send
|
|
113
|
+
: "message-send";
|
|
114
114
|
const target = startRun(draft, runId);
|
|
115
115
|
if (steer) {
|
|
116
116
|
// The whole steer lane rides the dispatch, in lane order.
|
|
@@ -138,7 +138,7 @@ const enqueueOrSteer = (
|
|
|
138
138
|
|
|
139
139
|
const stageRewind = (run: RunEntry, dispatch: Dispatch): void => {
|
|
140
140
|
run.stopping = {
|
|
141
|
-
reason: dispatch.trigger as "edit
|
|
141
|
+
reason: dispatch.trigger as "message-edit" | "message-reload",
|
|
142
142
|
};
|
|
143
143
|
run.nextDispatch = dispatch;
|
|
144
144
|
};
|
|
@@ -169,7 +169,7 @@ export const runsOptimistic = (
|
|
|
169
169
|
const { message, runAnchorMessageId } = command
|
|
170
170
|
.params[0] as StatewireThread.RunEditCommand;
|
|
171
171
|
const dispatch: Dispatch = {
|
|
172
|
-
trigger: "edit
|
|
172
|
+
trigger: "message-edit",
|
|
173
173
|
messages: [{ ...message }],
|
|
174
174
|
rollbackTo: runAnchorMessageId,
|
|
175
175
|
};
|
|
@@ -182,7 +182,7 @@ export const runsOptimistic = (
|
|
|
182
182
|
const { runAnchorMessageId } = command
|
|
183
183
|
.params[0] as StatewireThread.RunReloadCommand;
|
|
184
184
|
const dispatch: Dispatch = {
|
|
185
|
-
trigger: "reload
|
|
185
|
+
trigger: "message-reload",
|
|
186
186
|
messages: [],
|
|
187
187
|
rollbackTo: runAnchorMessageId,
|
|
188
188
|
};
|